diff --git a/runner/bitbybit-runner.js b/runner/bitbybit-runner.js index 8e167bf..17b290e 100644 --- a/runner/bitbybit-runner.js +++ b/runner/bitbybit-runner.js @@ -1,2 +1,2 @@ /*! For license information please see bitbybit-runner.js.LICENSE.txt */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bitbybitRunner=t():e.bitbybitRunner=t()}(this,(()=>(()=>{var e={615:(e,t,i)=>{e.exports=function e(t,i,s){function r(o,a){if(!i[o]){if(!t[o]){if(n)return n(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};t[o][0].call(h.exports,(function(e){return r(t[o][1][e]||e)}),h,h.exports,e,t,i,s)}return i[o].exports}for(var n=void 0,o=0;o=48&&e<=57}function T(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function y(e){return"01234567".indexOf(e)>=0}function S(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(e)>=0}function C(e){return 10===e||13===e||8232===e||8233===e}function E(e){return 64==e||36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||92===e||e>=128&&a.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function A(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||92===e||e>=128&&a.NonAsciiIdentifierPart.test(String.fromCharCode(e))}function P(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}}function R(e){return"eval"===e||"arguments"===e}function I(e){if(c&&P(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e||"let"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function M(e,t,i,s,r){var n;x("number"==typeof i,"Comment must have valid position"),g.lastCommentStart>=i||(g.lastCommentStart=i,n={type:e,value:t},v.range&&(n.range=[i,s]),v.loc&&(n.loc=r),v.comments.push(n),v.attachComment&&(v.leadingComments.push(n),v.trailingComments.push(n)))}function O(e){var t,i,s,r;for(t=u-e,i={start:{line:d,column:u-_-e}};u=p&&j({},o.UnexpectedToken,"ILLEGAL");else if(42===i){if(47===h.charCodeAt(u+1))return++u,++u,void(v.comments&&(s=h.slice(e+2,u-2),t.end={line:d,column:u-_},M("Block",s,e,u,t)));++u}else++u;j({},o.UnexpectedToken,"ILLEGAL")}function w(){var e,t;for(t=0===u;u>>="===(r=h.substr(u,4))?(u+=4,{type:t.Punctuator,value:r,lineNumber:d,lineStart:_,start:n,end:u}):">>>"===(s=r.substr(0,3))||"<<="===s||">>="===s?(u+=3,{type:t.Punctuator,value:s,lineNumber:d,lineStart:_,start:n,end:u}):l===(i=s.substr(0,2))[1]&&"+-<>&|".indexOf(l)>=0||"=>"===i?(u+=2,{type:t.Punctuator,value:i,lineNumber:d,lineStart:_,start:n,end:u}):"<>=!+-*%&|^/".indexOf(l)>=0?(++u,{type:t.Punctuator,value:l,lineNumber:d,lineStart:_,start:n,end:u}):void j({},o.UnexpectedToken,"ILLEGAL")}function k(){var e,i,s;if(x(b((s=h[u]).charCodeAt(0))||"."===s,"Numeric literal must start with a decimal digit or a decimal point"),i=u,e="","."!==s){if(e=h[u++],s=h[u],"0"===e){if("x"===s||"X"===s)return++u,function(e){for(var i="";u0&&(s=v.tokens[v.tokens.length-1]).range[0]===e&&"Punctuator"===s.type&&("/"!==s.value&&"/="!==s.value||v.tokens.pop()),v.tokens.push({type:"RegularExpression",value:i.literal,range:[e,u],loc:t})),i}function G(){var e,i,r;return w(),u>=p?{type:t.EOF,lineNumber:d,lineStart:_,start:u,end:u}:E(e=h.charCodeAt(u))?(i=u,{type:1===(r=92===h.charCodeAt(u)?F():B()).length?t.Identifier:I(r)?t.Keyword:"null"===r?t.NullLiteral:"true"===r||"false"===r?t.BooleanLiteral:t.Identifier,value:r,lineNumber:d,lineStart:_,start:i,end:u}):40===e||41===e||59===e?L():39===e||34===e?function(){var e,i,s,r,n,a,l,c,f="",m=!1;for(l=d,c=_,x("'"===(e=h[u])||'"'===e,"String literal must starts with a quote"),i=u,++u;u=0&&u=0?L():U()}return U()}return"Keyword"===e.type?U():L()}():L()}function z(){var e,s,r;return w(),e={start:{line:d,column:u-_}},s=G(),e.end={line:d,column:u-_},s.type!==t.EOF&&(r=h.slice(s.start,s.end),v.tokens.push({type:i[s.type],value:r,range:[s.start,s.end],loc:e})),s}function W(){var e;return u=(e=m).end,d=e.lineNumber,_=e.lineStart,m=void 0!==v.tokens?z():G(),u=e.end,d=e.lineNumber,_=e.lineStart,e}function H(){var e,t,i;e=u,t=d,i=_,m=void 0!==v.tokens?z():G(),u=e,d=t,_=i}function X(e,t){this.line=e,this.column=t}function Y(e,t,i,s){this.start=new X(e,t),this.end=new X(i,s)}function Q(){var e,t,i,s;return e=u,t=d,i=_,w(),s=d!==t,u=e,d=t,_=i,s}function j(e,t){var i,s=Array.prototype.slice.call(arguments,2),r=t.replace(/%(\d)/g,(function(e,t){return x(t":case"<=":case">=":case"instanceof":s=7;break;case"in":s=i?7:0;break;case"<<":case">>":case">>>":s=8;break;case"+":case"-":s=9;break;case"*":case"/":case"%":s=11}return s}function fe(){var e,t,i,s,r;return r=m,e=function(){var e,t,i,s,r,n,o,a,l,h;if(e=m,l=_e(),0===(r=pe(s=m,g.allowIn)))return l;for(s.prec=r,W(),t=[e,m],n=[l,s,o=_e()];(r=pe(m,g.allowIn))>0;){for(;n.length>2&&r<=n[n.length-2].prec;)o=n.pop(),a=n.pop().value,l=n.pop(),i=f.createBinaryExpression(a,l,o),t.pop(),e=t[t.length-1],f.markEnd(i,e),n.push(i);(s=W()).prec=r,n.push(s),t.push(m),i=_e(),n.push(i)}for(i=n[h=n.length-1],t.pop();h>1;)i=f.createBinaryExpression(n[h-1].value,n[h-2],i),h-=2,e=t.pop(),f.markEnd(i,e);return i}(),J("?")&&(W(),t=g.allowIn,g.allowIn=!0,i=me(),g.allowIn=t,q(":"),s=me(),e=f.createConditionalExpression(e,i,s),f.markEnd(e,r)),e}function me(){var e,i,s,n,a,l;return e=m,a=m,n=i=fe(),m.type===t.Punctuator&&("="===(l=m.value)||"*="===l||"/="===l||"%="===l||"+="===l||"-="===l||"<<="===l||">>="===l||">>>="===l||"&="===l||"^="===l||"|="===l)&&(ie(i)||K({},o.InvalidLHSInAssignment),c&&i.type===r.Identifier&&R(i.name)&&K(e,o.StrictLHSAssignment),e=W(),s=me(),n=f.markEnd(f.createAssignmentExpression(e.value,i,s),a)),n}function ge(){var e,t=m;if(e=me(),J(",")){for(e=f.createSequenceExpression([e]);u",i[t.Identifier]="Identifier",i[t.Keyword]="Keyword",i[t.NullLiteral]="Null",i[t.NumericLiteral]="Numeric",i[t.Punctuator]="Punctuator",i[t.StringLiteral]="String",i[t.RegularExpression]="RegularExpression",s=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="],r={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement"},n={Data:1,Get:2,Set:4},o={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalReturn:"Illegal return statement",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode"},a={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")},l={name:"SyntaxTree",processComment:function(e){var t,i;if(!(e.type===r.Program&&e.body.length>0)){for(v.trailingComments.length>0?v.trailingComments[0].range[0]>=e.range[1]?(i=v.trailingComments,v.trailingComments=[]):v.trailingComments.length=0:v.bottomRightStack.length>0&&v.bottomRightStack[v.bottomRightStack.length-1].trailingComments&&v.bottomRightStack[v.bottomRightStack.length-1].trailingComments[0].range[0]>=e.range[1]&&(i=v.bottomRightStack[v.bottomRightStack.length-1].trailingComments,delete v.bottomRightStack[v.bottomRightStack.length-1].trailingComments);v.bottomRightStack.length>0&&v.bottomRightStack[v.bottomRightStack.length-1].range[0]>=e.range[0];)t=v.bottomRightStack.pop();t?t.leadingComments&&t.leadingComments[t.leadingComments.length-1].range[1]<=e.range[0]&&(e.leadingComments=t.leadingComments,delete t.leadingComments):v.leadingComments.length>0&&v.leadingComments[v.leadingComments.length-1].range[1]<=e.range[0]&&(e.leadingComments=v.leadingComments,v.leadingComments=[]),i&&(e.trailingComments=i),v.bottomRightStack.push(e)}},markEnd:function(e,t){return v.range&&(e.range=[t.start,u]),v.loc&&(e.loc=new Y(void 0===t.startLineNumber?t.lineNumber:t.startLineNumber,t.start-(void 0===t.startLineStart?t.lineStart:t.startLineStart),d,u-_),this.postProcess(e)),v.attachComment&&this.processComment(e),e},postProcess:function(e){return v.source&&(e.loc.source=v.source),e},createArrayExpression:function(e){return{type:r.ArrayExpression,elements:e}},createAssignmentExpression:function(e,t,i){return{type:r.AssignmentExpression,operator:e,left:t,right:i}},createBinaryExpression:function(e,t,i){return{type:"||"===e||"&&"===e?r.LogicalExpression:r.BinaryExpression,operator:e,left:t,right:i}},createBlockStatement:function(e){return{type:r.BlockStatement,body:e}},createBreakStatement:function(e){return{type:r.BreakStatement,label:e}},createCallExpression:function(e,t){return{type:r.CallExpression,callee:e,arguments:t}},createCatchClause:function(e,t){return{type:r.CatchClause,param:e,body:t}},createConditionalExpression:function(e,t,i){return{type:r.ConditionalExpression,test:e,consequent:t,alternate:i}},createContinueStatement:function(e){return{type:r.ContinueStatement,label:e}},createDebuggerStatement:function(){return{type:r.DebuggerStatement}},createDoWhileStatement:function(e,t){return{type:r.DoWhileStatement,body:e,test:t}},createEmptyStatement:function(){return{type:r.EmptyStatement}},createExpressionStatement:function(e){return{type:r.ExpressionStatement,expression:e}},createForStatement:function(e,t,i,s){return{type:r.ForStatement,init:e,test:t,update:i,body:s}},createForInStatement:function(e,t,i){return{type:r.ForInStatement,left:e,right:t,body:i,each:!1}},createFunctionDeclaration:function(e,t,i,s){return{type:r.FunctionDeclaration,id:e,params:t,defaults:i,body:s,rest:null,generator:!1,expression:!1}},createFunctionExpression:function(e,t,i,s){return{type:r.FunctionExpression,id:e,params:t,defaults:i,body:s,rest:null,generator:!1,expression:!1}},createIdentifier:function(e){return{type:r.Identifier,name:e}},createIfStatement:function(e,t,i){return{type:r.IfStatement,test:e,consequent:t,alternate:i}},createLabeledStatement:function(e,t){return{type:r.LabeledStatement,label:e,body:t}},createLiteral:function(e){return{type:r.Literal,value:e.value,raw:h.slice(e.start,e.end)}},createMemberExpression:function(e,t,i){return{type:r.MemberExpression,computed:"["===e,object:t,property:i}},createNewExpression:function(e,t){return{type:r.NewExpression,callee:e,arguments:t}},createObjectExpression:function(e){return{type:r.ObjectExpression,properties:e}},createPostfixExpression:function(e,t){return{type:r.UpdateExpression,operator:e,argument:t,prefix:!1}},createProgram:function(e){return{type:r.Program,body:e}},createProperty:function(e,t,i){return{type:r.Property,key:t,value:i,kind:e}},createReturnStatement:function(e){return{type:r.ReturnStatement,argument:e}},createSequenceExpression:function(e){return{type:r.SequenceExpression,expressions:e}},createSwitchCase:function(e,t){return{type:r.SwitchCase,test:e,consequent:t}},createSwitchStatement:function(e,t){return{type:r.SwitchStatement,discriminant:e,cases:t}},createThisExpression:function(){return{type:r.ThisExpression}},createThrowStatement:function(e){return{type:r.ThrowStatement,argument:e}},createTryStatement:function(e,t,i,s){return{type:r.TryStatement,block:e,guardedHandlers:t,handlers:i,finalizer:s}},createUnaryExpression:function(e,t){return"++"===e||"--"===e?{type:r.UpdateExpression,operator:e,argument:t,prefix:!0}:{type:r.UnaryExpression,operator:e,argument:t,prefix:!0}},createVariableDeclaration:function(e,t){return{type:r.VariableDeclaration,declarations:e,kind:t}},createVariableDeclarator:function(e,t){return{type:r.VariableDeclarator,id:e,init:t}},createWhileStatement:function(e,t){return{type:r.WhileStatement,test:e,body:t}},createWithStatement:function(e,t){return{type:r.WithStatement,object:e,body:t}}},e.version="1.2.2",e.tokenize=function(e,i){var s;"string"==typeof e||e instanceof String||(e=String(e)),f=l,u=0,d=(h=e).length>0?1:0,_=0,p=h.length,m=null,g={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1,lastCommentStart:-1},v={},(i=i||{}).tokens=!0,v.tokens=[],v.tokenize=!0,v.openParenToken=-1,v.openCurlyToken=-1,v.range="boolean"==typeof i.range&&i.range,v.loc="boolean"==typeof i.loc&&i.loc,"boolean"==typeof i.comment&&i.comment&&(v.comments=[]),"boolean"==typeof i.tolerant&&i.tolerant&&(v.errors=[]);try{if(H(),m.type===t.EOF)return v.tokens;for(W();m.type!==t.EOF;)try{W()}catch(e){if(v.errors){v.errors.push(e);break}throw e}Oe(),s=v.tokens,void 0!==v.comments&&(s.comments=v.comments),void 0!==v.errors&&(s.errors=v.errors)}catch(e){throw e}finally{v={}}return s},e.parse=function(e,t){var i,s;s=String,"string"==typeof e||e instanceof String||(e=s(e)),f=l,u=0,d=(h=e).length>0?1:0,_=0,p=h.length,m=null,g={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1,lastCommentStart:-1},v={},void 0!==t&&(v.range="boolean"==typeof t.range&&t.range,v.loc="boolean"==typeof t.loc&&t.loc,v.attachComment="boolean"==typeof t.attachComment&&t.attachComment,v.loc&&null!==t.source&&void 0!==t.source&&(v.source=s(t.source)),"boolean"==typeof t.tokens&&t.tokens&&(v.tokens=[]),"boolean"==typeof t.comment&&t.comment&&(v.comments=[]),"boolean"==typeof t.tolerant&&t.tolerant&&(v.errors=[]),v.attachComment&&(v.range=!0,v.comments=[],v.bottomRightStack=[],v.trailingComments=[],v.leadingComments=[]));try{i=Me(),void 0!==v.comments&&(i.comments=v.comments),void 0!==v.tokens&&(Oe(),i.tokens=v.tokens),void 0!==v.errors&&(i.errors=v.errors)}catch(e){throw e}finally{v={}}return i},e.Syntax=function(){var e,t={};for(e in"function"==typeof Object.create&&(t=Object.create(null)),r)r.hasOwnProperty(e)&&(t[e]=r[e]);return"function"==typeof Object.freeze&&Object.freeze(t),t}()}))},{}],1:[function(e,t,i){(function(s){var r=function(){var e={trace:function(){},yy:{},symbols_:{error:2,JSON_PATH:3,DOLLAR:4,PATH_COMPONENTS:5,LEADING_CHILD_MEMBER_EXPRESSION:6,PATH_COMPONENT:7,MEMBER_COMPONENT:8,SUBSCRIPT_COMPONENT:9,CHILD_MEMBER_COMPONENT:10,DESCENDANT_MEMBER_COMPONENT:11,DOT:12,MEMBER_EXPRESSION:13,DOT_DOT:14,STAR:15,IDENTIFIER:16,SCRIPT_EXPRESSION:17,INTEGER:18,END:19,CHILD_SUBSCRIPT_COMPONENT:20,DESCENDANT_SUBSCRIPT_COMPONENT:21,"[":22,SUBSCRIPT:23,"]":24,SUBSCRIPT_EXPRESSION:25,SUBSCRIPT_EXPRESSION_LIST:26,SUBSCRIPT_EXPRESSION_LISTABLE:27,",":28,STRING_LITERAL:29,ARRAY_SLICE:30,FILTER_EXPRESSION:31,QQ_STRING:32,Q_STRING:33,$accept:0,$end:1},terminals_:{2:"error",4:"DOLLAR",12:"DOT",14:"DOT_DOT",15:"STAR",16:"IDENTIFIER",17:"SCRIPT_EXPRESSION",18:"INTEGER",19:"END",22:"[",24:"]",28:",",30:"ARRAY_SLICE",31:"FILTER_EXPRESSION",32:"QQ_STRING",33:"Q_STRING"},productions_:[0,[3,1],[3,2],[3,1],[3,2],[5,1],[5,2],[7,1],[7,1],[8,1],[8,1],[10,2],[6,1],[11,2],[13,1],[13,1],[13,1],[13,1],[13,1],[9,1],[9,1],[20,3],[21,4],[23,1],[23,1],[26,1],[26,3],[27,1],[27,1],[27,1],[25,1],[25,1],[25,1],[29,1],[29,1]],performAction:function(e,i,s,r,n,o,a){r.ast||(r.ast=t,t.initialize());var l=o.length-1;switch(n){case 1:return r.ast.set({expression:{type:"root",value:o[l]}}),r.ast.unshift(),r.ast.yield();case 2:return r.ast.set({expression:{type:"root",value:o[l-1]}}),r.ast.unshift(),r.ast.yield();case 3:return r.ast.unshift(),r.ast.yield();case 4:return r.ast.set({operation:"member",scope:"child",expression:{type:"identifier",value:o[l-1]}}),r.ast.unshift(),r.ast.yield();case 5:case 6:case 11:case 13:case 18:case 21:case 22:case 23:break;case 7:r.ast.set({operation:"member"}),r.ast.push();break;case 8:r.ast.set({operation:"subscript"}),r.ast.push();break;case 9:case 19:r.ast.set({scope:"child"});break;case 10:case 20:r.ast.set({scope:"descendant"});break;case 12:r.ast.set({scope:"child",operation:"member"});break;case 14:r.ast.set({expression:{type:"wildcard",value:o[l]}});break;case 15:r.ast.set({expression:{type:"identifier",value:o[l]}});break;case 16:r.ast.set({expression:{type:"script_expression",value:o[l]}});break;case 17:r.ast.set({expression:{type:"numeric_literal",value:parseInt(o[l])}});break;case 24:o[l].length>1?r.ast.set({expression:{type:"union",value:o[l]}}):this.$=o[l];break;case 25:this.$=[o[l]];break;case 26:this.$=o[l-2].concat(o[l]);break;case 27:this.$={expression:{type:"numeric_literal",value:parseInt(o[l])}},r.ast.set(this.$);break;case 28:this.$={expression:{type:"string_literal",value:o[l]}},r.ast.set(this.$);break;case 29:this.$={expression:{type:"slice",value:o[l]}},r.ast.set(this.$);break;case 30:this.$={expression:{type:"wildcard",value:o[l]}},r.ast.set(this.$);break;case 31:this.$={expression:{type:"script_expression",value:o[l]}},r.ast.set(this.$);break;case 32:this.$={expression:{type:"filter_expression",value:o[l]}},r.ast.set(this.$);break;case 33:case 34:this.$=o[l]}},table:[{3:1,4:[1,2],6:3,13:4,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{1:[3]},{1:[2,1],5:10,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,3],5:21,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,12],12:[2,12],14:[2,12],22:[2,12]},{1:[2,14],12:[2,14],14:[2,14],22:[2,14]},{1:[2,15],12:[2,15],14:[2,15],22:[2,15]},{1:[2,16],12:[2,16],14:[2,16],22:[2,16]},{1:[2,17],12:[2,17],14:[2,17],22:[2,17]},{1:[2,18],12:[2,18],14:[2,18],22:[2,18]},{1:[2,2],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,5],12:[2,5],14:[2,5],22:[2,5]},{1:[2,7],12:[2,7],14:[2,7],22:[2,7]},{1:[2,8],12:[2,8],14:[2,8],22:[2,8]},{1:[2,9],12:[2,9],14:[2,9],22:[2,9]},{1:[2,10],12:[2,10],14:[2,10],22:[2,10]},{1:[2,19],12:[2,19],14:[2,19],22:[2,19]},{1:[2,20],12:[2,20],14:[2,20],22:[2,20]},{13:23,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{13:24,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9],22:[1,25]},{15:[1,29],17:[1,30],18:[1,33],23:26,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{1:[2,4],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,6],12:[2,6],14:[2,6],22:[2,6]},{1:[2,11],12:[2,11],14:[2,11],22:[2,11]},{1:[2,13],12:[2,13],14:[2,13],22:[2,13]},{15:[1,29],17:[1,30],18:[1,33],23:38,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{24:[1,39]},{24:[2,23]},{24:[2,24],28:[1,40]},{24:[2,30]},{24:[2,31]},{24:[2,32]},{24:[2,25],28:[2,25]},{24:[2,27],28:[2,27]},{24:[2,28],28:[2,28]},{24:[2,29],28:[2,29]},{24:[2,33],28:[2,33]},{24:[2,34],28:[2,34]},{24:[1,41]},{1:[2,21],12:[2,21],14:[2,21],22:[2,21]},{18:[1,33],27:42,29:34,30:[1,35],32:[1,36],33:[1,37]},{1:[2,22],12:[2,22],14:[2,22],22:[2,22]},{24:[2,26],28:[2,26]}],defaultActions:{27:[2,23],29:[2,30],30:[2,31],31:[2,32]},parseError:function(e,t){if(!t.recoverable)throw new Error(e);this.trace(e)},parse:function(e){var t=this,i=[0],s=[null],r=[],n=this.table,o="",a=0,l=0,h=0,c=r.slice.call(arguments,1);this.lexer.setInput(e),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,void 0===this.lexer.yylloc&&(this.lexer.yylloc={});var u=this.lexer.yylloc;r.push(u);var d,_=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError?this.parseError=this.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var p,f,m,g,v,x,b,T,y,S={};;){if(m=i[i.length-1],this.defaultActions[m]?g=this.defaultActions[m]:(null==p&&(d=void 0,"number"!=typeof(d=t.lexer.lex()||1)&&(d=t.symbols_[d]||d),p=d),g=n[m]&&n[m][p]),void 0===g||!g.length||!g[0]){var C;for(x in y=[],n[m])this.terminals_[x]&&x>2&&y.push("'"+this.terminals_[x]+"'");C=this.lexer.showPosition?"Parse error on line "+(a+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+y.join(", ")+", got '"+(this.terminals_[p]||p)+"'":"Parse error on line "+(a+1)+": Unexpected "+(1==p?"end of input":"'"+(this.terminals_[p]||p)+"'"),this.parseError(C,{text:this.lexer.match,token:this.terminals_[p]||p,line:this.lexer.yylineno,loc:u,expected:y})}if(g[0]instanceof Array&&g.length>1)throw new Error("Parse Error: multiple actions possible at state: "+m+", token: "+p);switch(g[0]){case 1:i.push(p),s.push(this.lexer.yytext),r.push(this.lexer.yylloc),i.push(g[1]),p=null,f?(p=f,f=null):(l=this.lexer.yyleng,o=this.lexer.yytext,a=this.lexer.yylineno,u=this.lexer.yylloc,h>0&&h--);break;case 2:if(b=this.productions_[g[1]][1],S.$=s[s.length-b],S._$={first_line:r[r.length-(b||1)].first_line,last_line:r[r.length-1].last_line,first_column:r[r.length-(b||1)].first_column,last_column:r[r.length-1].last_column},_&&(S._$.range=[r[r.length-(b||1)].range[0],r[r.length-1].range[1]]),void 0!==(v=this.performAction.apply(S,[o,l,a,this.yy,g[1],s,r].concat(c))))return v;b&&(i=i.slice(0,-1*b*2),s=s.slice(0,-1*b),r=r.slice(0,-1*b)),i.push(this.productions_[g[1]][0]),s.push(S.$),r.push(S._$),T=n[i[i.length-2]][i[i.length-1]],i.push(T);break;case 3:return!0}}return!0}},t={initialize:function(){this._nodes=[],this._node={},this._stash=[]},set:function(e){for(var t in e)this._node[t]=e[t];return this._node},node:function(e){return arguments.length&&(this._node=e),this._node},push:function(){this._nodes.push(this._node),this._node={}},unshift:function(){this._nodes.unshift(this._node),this._node={}},yield:function(){var e=this._nodes;return this.initialize(),e}},i={EOF:1,parseError:function(e,t){if(!this.yy.parser)throw new Error(e);this.yy.parser.parseError(e,t)},setInput:function(e){return this._input=e,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},unput:function(e){var t=e.length,i=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t-1),this.offset-=t;var s=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),i.length-1&&(this.yylineno-=i.length-1);var r=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:i?(i.length===s.length?this.yylloc.first_column:0)+s[s.length-i.length].length-i[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[r[0],r[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(e){this.unput(this.match.slice(e))},pastInput:function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?"...":"")+e.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var e=this.pastInput(),t=new Array(e.length+1).join("-");return e+this.upcomingInput()+"\n"+t+"^"},test_match:function(e,t){var i,s,r;if(this.options.backtrack_lexer&&(r={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(r.yylloc.range=this.yylloc.range.slice(0))),(s=e[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=s.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:s?s[s.length-1].length-s[s.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],i=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),i)return i;if(this._backtrack){for(var n in r)this[n]=r[n];return!1}return!1},next:function(){if(this.done)return this.EOF;var e,t,i,s;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var r=this._currentRules(),n=0;nt[0].length)){if(t=i,s=n,this.options.backtrack_lexer){if(!1!==(e=this.test_match(i,r[n])))return e;if(this._backtrack){t=!1;continue}return!1}if(!this.options.flex)break}return t?!1!==(e=this.test_match(t,r[s]))&&e:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(e){this.conditionStack.push(e)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(e){return(e=this.conditionStack.length-1-Math.abs(e||0))>=0?this.conditionStack[e]:"INITIAL"},pushState:function(e){this.begin(e)},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(e,t,i,s){switch(i){case 0:return 4;case 1:return 14;case 2:return 12;case 3:return 15;case 4:return 16;case 5:return 22;case 6:return 24;case 7:return 28;case 8:return 30;case 9:return 18;case 10:return t.yytext=t.yytext.substr(1,t.yyleng-2),32;case 11:return t.yytext=t.yytext.substr(1,t.yyleng-2),33;case 12:return 17;case 13:return 31}},rules:[/^(?:\$)/,/^(?:\.\.)/,/^(?:\.)/,/^(?:\*)/,/^(?:[a-zA-Z_]+[a-zA-Z0-9_]*)/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?:((-?(?:0|[1-9][0-9]*)))?\:((-?(?:0|[1-9][0-9]*)))?(\:((-?(?:0|[1-9][0-9]*)))?)?)/,/^(?:(-?(?:0|[1-9][0-9]*)))/,/^(?:"(?:\\["bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*")/,/^(?:'(?:\\['bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^'\\])*')/,/^(?:\(.+?\)(?=\]))/,/^(?:\?\(.+?\)(?=\]))/],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13],inclusive:!0}}};function s(){this.yy={}}return e.lexer=i,s.prototype=e,e.Parser=s,new s}();void 0!==e&&void 0!==i&&(i.parser=r,i.Parser=r.Parser,i.parse=function(){return r.parse.apply(r,arguments)},i.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),s.exit(1));var r=e("fs").readFileSync(e("path").normalize(t[1]),"utf8");return i.parser.parse(r)},void 0!==t&&e.main===t&&i.main(s.argv.slice(1)))}).call(this,e("_process"))},{_process:14,fs:12,path:13}],2:[function(e,t,i){t.exports={identifier:"[a-zA-Z_]+[a-zA-Z0-9_]*",integer:"-?(?:0|[1-9][0-9]*)",qq_string:'"(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^"\\\\])*"',q_string:"'(?:\\\\['bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^'\\\\])*'"}},{}],3:[function(e,t,i){var s=e("./dict"),r=e("fs"),n={lex:{macros:{esc:"\\\\",int:s.integer},rules:[["\\$","return 'DOLLAR'"],["\\.\\.","return 'DOT_DOT'"],["\\.","return 'DOT'"],["\\*","return 'STAR'"],[s.identifier,"return 'IDENTIFIER'"],["\\[","return '['"],["\\]","return ']'"],[",","return ','"],["({int})?\\:({int})?(\\:({int})?)?","return 'ARRAY_SLICE'"],["{int}","return 'INTEGER'"],[s.qq_string,"yytext = yytext.substr(1,yyleng-2); return 'QQ_STRING';"],[s.q_string,"yytext = yytext.substr(1,yyleng-2); return 'Q_STRING';"],["\\(.+?\\)(?=\\])","return 'SCRIPT_EXPRESSION'"],["\\?\\(.+?\\)(?=\\])","return 'FILTER_EXPRESSION'"]]},start:"JSON_PATH",bnf:{JSON_PATH:[["DOLLAR",'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()'],["DOLLAR PATH_COMPONENTS",'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()'],["LEADING_CHILD_MEMBER_EXPRESSION","yy.ast.unshift(); return yy.ast.yield()"],["LEADING_CHILD_MEMBER_EXPRESSION PATH_COMPONENTS",'yy.ast.set({ operation: "member", scope: "child", expression: { type: "identifier", value: $1 }}); yy.ast.unshift(); return yy.ast.yield()']],PATH_COMPONENTS:[["PATH_COMPONENT",""],["PATH_COMPONENTS PATH_COMPONENT",""]],PATH_COMPONENT:[["MEMBER_COMPONENT",'yy.ast.set({ operation: "member" }); yy.ast.push()'],["SUBSCRIPT_COMPONENT",'yy.ast.set({ operation: "subscript" }); yy.ast.push() ']],MEMBER_COMPONENT:[["CHILD_MEMBER_COMPONENT",'yy.ast.set({ scope: "child" })'],["DESCENDANT_MEMBER_COMPONENT",'yy.ast.set({ scope: "descendant" })']],CHILD_MEMBER_COMPONENT:[["DOT MEMBER_EXPRESSION",""]],LEADING_CHILD_MEMBER_EXPRESSION:[["MEMBER_EXPRESSION",'yy.ast.set({ scope: "child", operation: "member" })']],DESCENDANT_MEMBER_COMPONENT:[["DOT_DOT MEMBER_EXPRESSION",""]],MEMBER_EXPRESSION:[["STAR",'yy.ast.set({ expression: { type: "wildcard", value: $1 } })'],["IDENTIFIER",'yy.ast.set({ expression: { type: "identifier", value: $1 } })'],["SCRIPT_EXPRESSION",'yy.ast.set({ expression: { type: "script_expression", value: $1 } })'],["INTEGER",'yy.ast.set({ expression: { type: "numeric_literal", value: parseInt($1) } })'],["END",""]],SUBSCRIPT_COMPONENT:[["CHILD_SUBSCRIPT_COMPONENT",'yy.ast.set({ scope: "child" })'],["DESCENDANT_SUBSCRIPT_COMPONENT",'yy.ast.set({ scope: "descendant" })']],CHILD_SUBSCRIPT_COMPONENT:[["[ SUBSCRIPT ]",""]],DESCENDANT_SUBSCRIPT_COMPONENT:[["DOT_DOT [ SUBSCRIPT ]",""]],SUBSCRIPT:[["SUBSCRIPT_EXPRESSION",""],["SUBSCRIPT_EXPRESSION_LIST",'$1.length > 1? yy.ast.set({ expression: { type: "union", value: $1 } }) : $$ = $1']],SUBSCRIPT_EXPRESSION_LIST:[["SUBSCRIPT_EXPRESSION_LISTABLE","$$ = [$1]"],["SUBSCRIPT_EXPRESSION_LIST , SUBSCRIPT_EXPRESSION_LISTABLE","$$ = $1.concat($3)"]],SUBSCRIPT_EXPRESSION_LISTABLE:[["INTEGER",'$$ = { expression: { type: "numeric_literal", value: parseInt($1) } }; yy.ast.set($$)'],["STRING_LITERAL",'$$ = { expression: { type: "string_literal", value: $1 } }; yy.ast.set($$)'],["ARRAY_SLICE",'$$ = { expression: { type: "slice", value: $1 } }; yy.ast.set($$)']],SUBSCRIPT_EXPRESSION:[["STAR",'$$ = { expression: { type: "wildcard", value: $1 } }; yy.ast.set($$)'],["SCRIPT_EXPRESSION",'$$ = { expression: { type: "script_expression", value: $1 } }; yy.ast.set($$)'],["FILTER_EXPRESSION",'$$ = { expression: { type: "filter_expression", value: $1 } }; yy.ast.set($$)']],STRING_LITERAL:[["QQ_STRING","$$ = $1"],["Q_STRING","$$ = $1"]]}};r.readFileSync&&(n.moduleInclude=r.readFileSync(e.resolve("../include/module.js")),n.actionInclude=r.readFileSync(e.resolve("../include/action.js"))),t.exports=n},{"./dict":2,fs:12}],4:[function(e,t,i){var s=e("./aesprim"),r=e("./slice"),n=e("static-eval"),o=e("underscore").uniq,a=function(){return this.initialize.apply(this,arguments)};function l(t,i,r){var n=e("./index"),o=_(s.parse(i).body[0].expression,{"@":t.value}),a=r.replace(/\{\{\s*value\s*\}\}/g,o),l=n.nodes(t.value,a);return l.forEach((function(e){e.path=t.path.concat(e.path.slice(1))})),l}function h(e){return Array.isArray(e)}function c(e){return function(t,i,s,r){var n=t.value,o=t.path,a=[],l=function(t,n){var o;h(t)?(t.forEach((function(e,t){a.length>=r||s(t,e,i)&&a.push({path:n.concat(t),value:e})})),t.forEach((function(t,i){a.length>=r||e&&l(t,n.concat(i))}))):(o=t)&&!(o instanceof Array)&&o instanceof Object&&(this.keys(t).forEach((function(e){a.length>=r||s(e,t[e],i)&&a.push({path:n.concat(e),value:t[e]})})),this.keys(t).forEach((function(i){a.length>=r||e&&l(t[i],n.concat(i))})))}.bind(this);return l(n,o),a}}function u(e){return function(t,i,s){return this.descend(i,t.expression.value,e,s)}}function d(e){return function(t,i,s){return this.traverse(i,t.expression.value,e,s)}}function _(){try{return n.apply(this,arguments)}catch(e){}}function p(e){return e=e.filter((function(e){return e})),o(e,(function(e){return e.path.map((function(e){return String(e).replace("-","--")})).join("-")}))}function f(e){var t=String(e);return t.match(/^-?[0-9]+$/)?parseInt(t):null}a.prototype.initialize=function(){this.traverse=c(!0),this.descend=c()},a.prototype.keys=Object.keys,a.prototype.resolve=function(e){var t=[e.operation,e.scope,e.expression.type].join("-"),i=this._fns[t];if(!i)throw new Error("couldn't resolve key: "+t);return i.bind(this)},a.prototype.register=function(e,t){if(!t instanceof Function)throw new Error("handler must be a function");this._fns[e]=t},a.prototype._fns={"member-child-identifier":function(e,t){var i=e.expression.value,s=t.value;if(s instanceof Object&&i in s)return[{value:s[i],path:t.path.concat(i)}]},"member-descendant-identifier":d((function(e,t,i){return e==i})),"subscript-child-numeric_literal":u((function(e,t,i){return e===i})),"member-child-numeric_literal":u((function(e,t,i){return String(e)===String(i)})),"subscript-descendant-numeric_literal":d((function(e,t,i){return e===i})),"member-child-wildcard":u((function(){return!0})),"member-descendant-wildcard":d((function(){return!0})),"subscript-descendant-wildcard":d((function(){return!0})),"subscript-child-wildcard":u((function(){return!0})),"subscript-child-slice":function(e,t){if(h(t.value)){var i=e.expression.value.split(":").map(f),s=t.value.map((function(e,i){return{value:e,path:t.path.concat(i)}}));return r.apply(null,[s].concat(i))}},"subscript-child-union":function(e,t){var i=[];return e.expression.value.forEach((function(e){var s={operation:"subscript",scope:"child",expression:e.expression},r=this.resolve(s)(s,t);r&&(i=i.concat(r))}),this),p(i)},"subscript-descendant-union":function(t,i,s){var r=e(".."),n=this,o=[];return r.nodes(i,"$..*").slice(1).forEach((function(e){o.length>=s||t.expression.value.forEach((function(t){var i={operation:"subscript",scope:"child",expression:t.expression},s=n.resolve(i)(i,e);o=o.concat(s)}))})),p(o)},"subscript-child-filter_expression":function(e,t,i){var r=e.expression.value.slice(2,-1),n=s.parse(r).body[0].expression;return this.descend(t,null,(function(e,t){return _(n,{"@":t})}),i)},"subscript-descendant-filter_expression":function(e,t,i){var r=e.expression.value.slice(2,-1),n=s.parse(r).body[0].expression;return this.traverse(t,null,(function(e,t){return _(n,{"@":t})}),i)},"subscript-child-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$[{{value}}]")},"member-child-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$.{{value}}")},"member-descendant-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$..value")}},a.prototype._fns["subscript-child-string_literal"]=a.prototype._fns["member-child-identifier"],a.prototype._fns["member-descendant-numeric_literal"]=a.prototype._fns["subscript-descendant-string_literal"]=a.prototype._fns["member-descendant-identifier"],t.exports=a},{"..":"jsonpath","./aesprim":"./aesprim","./index":5,"./slice":7,"static-eval":15,underscore:12}],5:[function(e,t,i){var s=e("assert"),r=e("./dict"),n=e("./parser"),o=e("./handlers"),a=function(){this.initialize.apply(this,arguments)};function l(e){return"[object String]"==Object.prototype.toString.call(e)}a.prototype.initialize=function(){this.parser=new n,this.handlers=new o},a.prototype.parse=function(e){return s.ok(l(e),"we need a path"),this.parser.parse(e)},a.prototype.parent=function(e,t){s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path");var i=this.nodes(e,t)[0];return i.path.pop(),this.value(e,i.path)},a.prototype.apply=function(e,t,i){s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),s.equal(typeof i,"function","fn needs to be function");var r=this.nodes(e,t).sort((function(e,t){return t.path.length-e.path.length}));return r.forEach((function(t){var s=t.path.pop(),r=this.value(e,this.stringify(t.path)),n=t.value=i.call(e,r[s]);r[s]=n}),this),r},a.prototype.value=function(e,t,i){if(s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),arguments.length>=3){var r=this.nodes(e,t).shift();if(!r)return this._vivify(e,t,i);var n=r.path.slice(-1).shift();this.parent(e,this.stringify(r.path))[n]=i}return this.query(e,this.stringify(t),1).shift()},a.prototype._vivify=function(e,t,i){var r=this;s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path");var n=this.parser.parse(t).map((function(e){return e.expression.value})),o=function(t,i){var s=t.pop(),n=r.value(e,t);n||(o(t.concat(),"string"==typeof s?{}:[]),n=r.value(e,t)),n[s]=i};return o(n,i),this.query(e,t)[0]},a.prototype.query=function(e,t,i){return s.ok(e instanceof Object,"obj needs to be an object"),s.ok(l(t),"we need a path"),this.nodes(e,t,i).map((function(e){return e.value}))},a.prototype.paths=function(e,t,i){return s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),this.nodes(e,t,i).map((function(e){return e.path}))},a.prototype.nodes=function(e,t,i){if(s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),0===i)return[];var r=this.parser.parse(t),n=this.handlers,o=[{path:["$"],value:e}],a=[];return r.length&&"root"==r[0].expression.type&&r.shift(),r.length?(r.forEach((function(e,t){if(!(a.length>=i)){var s=n.resolve(e),l=[];o.forEach((function(n){if(!(a.length>=i)){var o=s(e,n,i);t==r.length-1?a=a.concat(o||[]):l=l.concat(o||[])}})),o=l}})),i?a.slice(0,i):a):o},a.prototype.stringify=function(e){s.ok(e,"we need a path");var t="$",i={"descendant-member":"..{{value}}","child-member":".{{value}}","descendant-subscript":"..[{{value}}]","child-subscript":"[{{value}}]"};return(e=this._normalize(e)).forEach((function(e){if("root"!=e.expression.type){var s,r=[e.scope,e.operation].join("-"),n=i[r];if(s="string_literal"==e.expression.type?JSON.stringify(e.expression.value):e.expression.value,!n)throw new Error("couldn't find template "+r);t+=n.replace(/{{value}}/,s)}})),t},a.prototype._normalize=function(e){if(s.ok(e,"we need a path"),"string"==typeof e)return this.parser.parse(e);if(Array.isArray(e)&&"string"==typeof e[0]){var t=[{expression:{type:"root",value:"$"}}];return e.forEach((function(e,i){if("$"!=e||0!==i)if("string"==typeof e&&e.match("^"+r.identifier+"$"))t.push({operation:"member",scope:"child",expression:{value:e,type:"identifier"}});else{var s="number"==typeof e?"numeric_literal":"string_literal";t.push({operation:"subscript",scope:"child",expression:{value:e,type:s}})}})),t}if(Array.isArray(e)&&"object"==typeof e[0])return e;throw new Error("couldn't understand path "+e)},a.Handlers=o,a.Parser=n;var h=new a;h.JSONPath=a,t.exports=h},{"./dict":2,"./handlers":4,"./parser":6,assert:8}],6:[function(e,t,i){var s=e("./grammar"),r=e("../generated/parser"),n=function(){var e=new r.Parser,t=e.parseError;return e.yy.parseError=function(){e.yy.ast&&e.yy.ast.initialize(),t.apply(e,arguments)},e};n.grammar=s,t.exports=n},{"../generated/parser":1,"./grammar":3}],7:[function(e,t,i){function s(e){return String(e).match(/^[0-9]+$/)?parseInt(e):Number.isFinite(e)?parseInt(e,10):0}t.exports=function(e,t,i,r){if("string"==typeof t)throw new Error("start cannot be a string");if("string"==typeof i)throw new Error("end cannot be a string");if("string"==typeof r)throw new Error("step cannot be a string");var n=e.length;if(0===r)throw new Error("step cannot be zero");if(r=r?s(r):1,i=i<0?n+i:i,t=s(0===(t=t<0?n+t:t)?0:t||(r>0?0:n-1)),i=s(0===i?0:i||(r>0?n:-1)),t=r>0?Math.max(0,t):Math.min(n,t),i=r>0?Math.min(i,n):Math.max(-1,i),r>0&&i<=t)return[];if(r<0&&t<=i)return[];for(var o=[],a=t;a!=i&&!(r<0&&a<=i||r>0&&a>=i);a+=r)o.push(e[a]);return o}},{}],8:[function(e,t,i){var s=e("util/"),r=Array.prototype.slice,n=Object.prototype.hasOwnProperty,o=t.exports=c;function a(e,t){return s.isUndefined(t)?""+t:s.isNumber(t)&&!isFinite(t)||s.isFunction(t)||s.isRegExp(t)?t.toString():t}function l(e,t){return s.isString(e)?e.length=0;a--)if(l[a]!=h[a])return!1;for(a=l.length-1;a>=0;a--)if(!u(e[o=l[a]],t[o]))return!1;return!0}(e,t):e==t}function d(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function _(e,t){return!(!e||!t)&&("[object RegExp]"==Object.prototype.toString.call(t)?t.test(e):e instanceof t||!0===t.call({},e))}function p(e,t,i,r){var n;s.isString(i)&&(r=i,i=null);try{t()}catch(e){n=e}if(r=(i&&i.name?" ("+i.name+").":".")+(r?" "+r:"."),e&&!n&&h(n,i,"Missing expected exception"+r),!e&&_(n,i)&&h(n,i,"Got unwanted exception"+r),e&&n&&i&&!_(n,i)||!e&&n)throw n}o.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=function(e){return l(JSON.stringify(e.actual,a),128)+" "+e.operator+" "+l(JSON.stringify(e.expected,a),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||h;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var i=new Error;if(i.stack){var s=i.stack,r=t.name,n=s.indexOf("\n"+r);if(n>=0){var o=s.indexOf("\n",n+1);s=s.substring(o+1)}this.stack=s}}},s.inherits(o.AssertionError,Error),o.fail=h,o.ok=c,o.equal=function(e,t,i){e!=t&&h(e,t,i,"==",o.equal)},o.notEqual=function(e,t,i){e==t&&h(e,t,i,"!=",o.notEqual)},o.deepEqual=function(e,t,i){u(e,t)||h(e,t,i,"deepEqual",o.deepEqual)},o.notDeepEqual=function(e,t,i){u(e,t)&&h(e,t,i,"notDeepEqual",o.notDeepEqual)},o.strictEqual=function(e,t,i){e!==t&&h(e,t,i,"===",o.strictEqual)},o.notStrictEqual=function(e,t,i){e===t&&h(e,t,i,"!==",o.notStrictEqual)},o.throws=function(e,t,i){p.apply(this,[!0].concat(r.call(arguments)))},o.doesNotThrow=function(e,t){p.apply(this,[!1].concat(r.call(arguments)))},o.ifError=function(e){if(e)throw e};var f=Object.keys||function(e){var t=[];for(var i in e)n.call(e,i)&&t.push(i);return t}},{"util/":11}],9:[function(e,t,i){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}},{}],10:[function(e,t,i){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],11:[function(e,t,s){(function(t,i){var r=/%[sdj%]/g;s.format=function(e){if(!g(e)){for(var t=[],i=0;i=n)return e;switch(e){case"%s":return String(s[i++]);case"%d":return Number(s[i++]);case"%j":try{return JSON.stringify(s[i++])}catch(e){return"[Circular]"}default:return e}})),l=s[i];i=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),p(t)?i.showHidden=t:t&&s._extend(i,t),v(i.showHidden)&&(i.showHidden=!1),v(i.depth)&&(i.depth=2),v(i.colors)&&(i.colors=!1),v(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=l),c(i,e,i.depth)}function l(e,t){var i=a.styles[t];return i?"["+a.colors[i][0]+"m"+e+"["+a.colors[i][1]+"m":e}function h(e,t){return e}function c(e,t,i){if(e.customInspect&&t&&S(t.inspect)&&t.inspect!==s.inspect&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(i,e);return g(r)||(r=c(e,r,i)),r}var n=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(g(t)){var i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}return m(t)?e.stylize(""+t,"number"):p(t)?e.stylize(""+t,"boolean"):f(t)?e.stylize("null","null"):void 0}(e,t);if(n)return n;var o=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,i){t[e]=!0})),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),y(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return u(t);if(0===o.length){if(S(t)){var l=t.name?": "+t.name:"";return e.stylize("[Function"+l+"]","special")}if(x(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(T(t))return e.stylize(Date.prototype.toString.call(t),"date");if(y(t))return u(t)}var h,b="",C=!1,E=["{","}"];return _(t)&&(C=!0,E=["[","]"]),S(t)&&(b=" [Function"+(t.name?": "+t.name:"")+"]"),x(t)&&(b=" "+RegExp.prototype.toString.call(t)),T(t)&&(b=" "+Date.prototype.toUTCString.call(t)),y(t)&&(b=" "+u(t)),0!==o.length||C&&0!=t.length?i<0?x(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),h=C?function(e,t,i,s,r){for(var n=[],o=0,a=t.length;o60?i[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}(h,b,E)):E[0]+b+E[1]}function u(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,i,s,r,n){var o,a,l;if((l=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?a=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(a=e.stylize("[Setter]","special")),P(s,r)||(o="["+r+"]"),a||(e.seen.indexOf(l.value)<0?(a=f(i)?c(e,l.value,null):c(e,l.value,i-1)).indexOf("\n")>-1&&(a=n?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),v(o)){if(n&&r.match(/^\d+$/))return a;(o=JSON.stringify(""+r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+a}function _(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function f(e){return null===e}function m(e){return"number"==typeof e}function g(e){return"string"==typeof e}function v(e){return void 0===e}function x(e){return b(e)&&"[object RegExp]"===C(e)}function b(e){return"object"==typeof e&&null!==e}function T(e){return b(e)&&"[object Date]"===C(e)}function y(e){return b(e)&&("[object Error]"===C(e)||e instanceof Error)}function S(e){return"function"==typeof e}function C(e){return Object.prototype.toString.call(e)}function E(e){return e<10?"0"+e.toString(10):e.toString(10)}s.debuglog=function(e){if(v(n)&&(n=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!o[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var i=t.pid;o[e]=function(){var t=s.format.apply(s,arguments);console.error("%s %d: %s",e,i,t)}}else o[e]=function(){};return o[e]},s.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},s.isArray=_,s.isBoolean=p,s.isNull=f,s.isNullOrUndefined=function(e){return null==e},s.isNumber=m,s.isString=g,s.isSymbol=function(e){return"symbol"==typeof e},s.isUndefined=v,s.isRegExp=x,s.isObject=b,s.isDate=T,s.isError=y,s.isFunction=S,s.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},s.isBuffer=e("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function P(e,t){return Object.prototype.hasOwnProperty.call(e,t)}s.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[E(e.getHours()),E(e.getMinutes()),E(e.getSeconds())].join(":"),[e.getDate(),A[e.getMonth()],t].join(" ")),s.format.apply(s,arguments))},s.inherits=e("inherits"),s._extend=function(e,t){if(!t||!b(t))return e;for(var i=Object.keys(t),s=i.length;s--;)e[i[s]]=t[i[s]];return e}}).call(this,e("_process"),void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":10,_process:14,inherits:9}],12:[function(e,t,i){},{}],13:[function(e,t,i){(function(e){function t(e,t){for(var i=0,s=e.length-1;s>=0;s--){var r=e[s];"."===r?e.splice(s,1):".."===r?(e.splice(s,1),i++):i&&(e.splice(s,1),i--)}if(t)for(;i--;i)e.unshift("..");return e}function s(e,t){if(e.filter)return e.filter(t);for(var i=[],s=0;s=-1&&!r;n--){var o=n>=0?arguments[n]:e.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(i=o+"/"+i,r="/"===o.charAt(0))}return(r?"/":"")+(i=t(s(i.split("/"),(function(e){return!!e})),!r).join("/"))||"."},i.normalize=function(e){var n=i.isAbsolute(e),o="/"===r(e,-1);return(e=t(s(e.split("/"),(function(e){return!!e})),!n).join("/"))||n||(e="."),e&&o&&(e+="/"),(n?"/":"")+e},i.isAbsolute=function(e){return"/"===e.charAt(0)},i.join=function(){var e=Array.prototype.slice.call(arguments,0);return i.normalize(s(e,(function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e})).join("/"))},i.relative=function(e,t){function s(e){for(var t=0;t=0&&""===e[i];i--);return t>i?[]:e.slice(t,i-t+1)}e=i.resolve(e).substr(1),t=i.resolve(t).substr(1);for(var r=s(e.split("/")),n=s(t.split("/")),o=Math.min(r.length,n.length),a=o,l=0;l=1;--n)if(47===(t=e.charCodeAt(n))){if(!r){s=n;break}}else r=!1;return-1===s?i?"/":".":i&&1===s?"/":e.slice(0,s)},i.basename=function(e,t){var i=function(e){"string"!=typeof e&&(e+="");var t,i=0,s=-1,r=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!r){i=t+1;break}}else-1===s&&(r=!1,s=t+1);return-1===s?"":e.slice(i,s)}(e);return t&&i.substr(-1*t.length)===t&&(i=i.substr(0,i.length-t.length)),i},i.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,i=0,s=-1,r=!0,n=0,o=e.length-1;o>=0;--o){var a=e.charCodeAt(o);if(47!==a)-1===s&&(r=!1,s=o+1),46===a?-1===t?t=o:1!==n&&(n=1):-1!==t&&(n=-1);else if(!r){i=o+1;break}}return-1===t||-1===s||0===n||1===n&&t===s-1&&t===i+1?"":e.slice(t,s)};var r=function(e,t,i){return e.substr(t,i)}}).call(this,e("_process"))},{_process:14}],14:[function(e,t,i){var s,r,n=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function l(e){if(s===setTimeout)return setTimeout(e,0);if((s===o||!s)&&setTimeout)return s=setTimeout,setTimeout(e,0);try{return s(e,0)}catch(t){try{return s.call(null,e,0)}catch(t){return s.call(this,e,0)}}}!function(){try{s="function"==typeof setTimeout?setTimeout:o}catch(e){s=o}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var h,c=[],u=!1,d=-1;function _(){u&&h&&(u=!1,h.length?c=h.concat(c):d=-1,c.length&&p())}function p(){if(!u){var e=l(_);u=!0;for(var t=c.length;t;){for(h=c,c=[];++d1)for(var i=1;i"===_?h>d:">="===_?h>=d:"|"===_?h|d:"&"===_?h&d:"^"===_?h^d:"&&"===_?h&&d:"||"===_?h||d:i}if("Identifier"===r.type)return{}.hasOwnProperty.call(t,r.name)?t[r.name]:i;if("ThisExpression"===r.type)return{}.hasOwnProperty.call(t,"this")?t.this:i;if("CallExpression"===r.type){var p=e(r.callee);if(p===i)return i;if("function"!=typeof p)return i;var f=r.callee.object?e(r.callee.object):i;f===i&&(f=null);var m=[];for(l=0,h=r.arguments.length;l{e.exports=function(){var e={},t=this,i=(new Function("try {return this===window;}catch(e){ return false;}"),new Function("try {return this===global;}catch(e){return false;}")),s=new Function("try {return typeof importScripts === 'function';}catch(e){return false;}");if(i()&&s(),i()||s()){var r=t;if(s()){onmessage=function(e){if(e.data.className&&e.data.methodName){var i=(s=e.data.className,r=e.data.methodName,n=t,s.split(".").forEach((function(e){n&&(n=n[e])})),n?n[r]:null);if(!i)return console.error("could not find "+e.data.className+"."+e.data.methodName);postMessage({result:i.apply(null,e.data.args),id:e.data.id})}var s,r,n}}}return function(e,t,i){"use strict";t.geom=t.geom||{},t.exe=t.exe||{},t.eval=t.eval||{},t.core=t.core||{},t.promhx=t.promhx||{};var s={},r=function(){return P.__string_rec(this,"")};function n(e,t){function i(){}i.prototype=e;var s=new i;for(var r in t)s[r]=t[r];return t.toString!==Object.prototype.toString&&(s.toString=t.toString),s}var o=function(){};s.HxOverrides=o,o.__name__=["HxOverrides"],o.strDate=function(e){switch(e.length){case 8:var t=e.split(":"),i=new Date;return i.setTime(0),i.setUTCHours(t[0]),i.setUTCMinutes(t[1]),i.setUTCSeconds(t[2]),i;case 10:var s=e.split("-");return new Date(s[0],s[1]-1,s[2],0,0,0);case 19:var r=e.split(" "),n=r[0].split("-"),o=r[1].split(":");return new Date(n[0],n[1]-1,n[2],o[0],o[1],o[2]);default:throw new A("Invalid date format : "+e)}},o.cca=function(e,t){var i=e.charCodeAt(t);if(i==i)return i},o.substr=function(e,t,i){return null!=t&&0!=t&&null!=i&&i<0?"":(null==i&&(i=e.length),t<0?(t=e.length+t)<0&&(t=0):i<0&&(i=e.length+i-t),e.substr(t,i))},o.iter=function(e){return{cur:0,arr:e,hasNext:function(){return this.cur0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n),n=0),this.serialize(e[d]))}n>0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n)),this.buf.b+="h";break;case l:this.buf.b+="l";for(var _=e.h,f=null;null!=_;){var m;f=_[0],_=_[1],m=f,this.serialize(m)}this.buf.b+="h";break;case Date:var v=e;this.buf.b+="v",this.buf.add(v.getTime());break;case y:this.buf.b+="b";for(var T=e,C=T.keys();C.hasNext();){var E=C.next();this.serializeString(E),this.serialize(null!=ft[E]?T.getReserved(E):T.h[E])}this.buf.b+="h";break;case x:this.buf.b+="q";for(var R=e,I=R.keys();I.hasNext();){var M=I.next();this.buf.b+=":",this.buf.b+=null==M?"null":""+M,this.serialize(R.h[M])}this.buf.b+="h";break;case b:this.buf.b+="M";for(var O=e,D=O.keys();D.hasNext();){var w=D.next(),N=h.field(w,"__id__");h.deleteField(w,"__id__"),this.serialize(w),w.__id__=N,this.serialize(O.h[w.__id__])}this.buf.b+="h";break;case S:for(var F=e,B=0,L=F.length-2,k=new u,V=g.BASE64;B>2)),k.add(V.charAt(63&(U<<4|G>>4))),k.add(V.charAt(63&(G<<2|z>>6))),k.add(V.charAt(63&z))}if(B==L){var W=F.get(B++),H=F.get(B++);k.add(V.charAt(W>>2)),k.add(V.charAt(63&(W<<4|H>>4))),k.add(V.charAt(H<<2&63))}else if(B==L+1){var X=F.get(B++);k.add(V.charAt(X>>2)),k.add(V.charAt(X<<4&63))}var Y=k.b;this.buf.b+="s",null==Y.length?this.buf.b+="null":this.buf.b+=""+Y.length,this.buf.b+=":",this.buf.b+=null==Y?"null":""+Y;break;default:this.useCache&&this.cache.pop(),null!=e.hxSerialize?(this.buf.b+="C",this.serializeString(p.getClassName(r)),this.useCache&&this.cache.push(e),e.hxSerialize(this),this.buf.b+="g"):(this.buf.b+="c",this.serializeString(p.getClassName(r)),this.useCache&&this.cache.push(e),this.serializeFields(e))}break;case 4:if(P.__instanceof(e,_t)){var Q=p.getClassName(e);this.buf.b+="A",this.serializeString(Q)}else if(P.__instanceof(e,pt))this.buf.b+="B",this.serializeString(p.getEnumName(e));else{if(this.useCache&&this.serializeRef(e))return;this.buf.b+="o",this.serializeFields(e)}break;case 7:var j=t[2];if(this.useCache){if(this.serializeRef(e))return;this.cache.pop()}this.useEnumIndex?this.buf.b+="j":this.buf.b+="w",this.serializeString(p.getEnumName(j)),this.useEnumIndex?(this.buf.b+=":",this.buf.b+=c.string(e[1])):this.serializeString(e[0]),this.buf.b+=":";var K=e.length;this.buf.b+=c.string(K-2);for(var $=2;$57)break;e=10*e+(s-48),this.pos++}else{if(this.pos!=i)break;t=!0,this.pos++}}return t&&(e*=-1),e},readFloat:function(){for(var e=this.pos;;){var t=this.buf.charCodeAt(this.pos);if(!(t>=43&&t<58||101==t||69==t))break;this.pos++}return c.parseFloat(o.substr(this.buf,e,this.pos-e))},unserializeObject:function(e){for(;;){if(this.pos>=this.length)throw new A("Invalid object");if(103==this.buf.charCodeAt(this.pos))break;var t=this.unserialize();if("string"!=typeof t)throw new A("Invalid object key");var i=this.unserialize();e[t]=i}this.pos++},unserializeEnum:function(e,t){if(58!=this.get(this.pos++))throw new A("Invalid enum format");var i=this.readDigits();if(0==i)return p.createEnum(e,t);for(var s=[];i-- >0;)s.push(this.unserialize());return p.createEnum(e,t,s)},unserialize:function(){switch(this.get(this.pos++)){case 110:return null;case 116:return!0;case 102:return!1;case 122:return 0;case 105:return this.readDigits();case 100:return this.readFloat();case 121:var e=this.readDigits();if(58!=this.get(this.pos++)||this.length-this.pos=this.cache.length)throw new A("Invalid reference");return this.cache[a];case 82:var h=this.readDigits();if(h<0||h>=this.scache.length)throw new A("Invalid string reference");return this.scache[h];case 120:throw new A(this.unserialize());case 99:var c=this.unserialize(),u=this.resolver.resolveClass(c);if(null==u)throw new A("Class not found "+c);var _=p.createEmptyInstance(u);return this.cache.push(_),this.unserializeObject(_),_;case 119:var f=this.unserialize(),m=this.resolver.resolveEnum(f);if(null==m)throw new A("Enum not found "+f);var g=this.unserializeEnum(m,this.unserialize());return this.cache.push(g),g;case 106:var T=this.unserialize(),C=this.resolver.resolveEnum(T);if(null==C)throw new A("Enum not found "+T);this.pos++;var E=this.readDigits(),P=p.getEnumConstructs(C)[E];if(null==P)throw new A("Unknown enum index "+T+"@"+E);var R=this.unserializeEnum(C,P);return this.cache.push(R),R;case 108:var I=new l;for(this.cache.push(I),this.buf;104!=this.buf.charCodeAt(this.pos);)I.add(this.unserialize());return this.pos++,I;case 98:var M=new y;for(this.cache.push(M),this.buf;104!=this.buf.charCodeAt(this.pos);){var O=this.unserialize();M.set(O,this.unserialize())}return this.pos++,M;case 113:var D=new x;this.cache.push(D),this.buf;for(var w=this.get(this.pos++);58==w;){var N=this.readDigits();D.set(N,this.unserialize()),w=this.get(this.pos++)}if(104!=w)throw new A("Invalid IntMap format");return D;case 77:var F=new b;for(this.cache.push(F),this.buf;104!=this.buf.charCodeAt(this.pos);){var B=this.unserialize();F.set(B,this.unserialize())}return this.pos++,F;case 118:var L;if(this.buf.charCodeAt(this.pos)>=48&&this.buf.charCodeAt(this.pos)<=57&&this.buf.charCodeAt(this.pos+1)>=48&&this.buf.charCodeAt(this.pos+1)<=57&&this.buf.charCodeAt(this.pos+2)>=48&&this.buf.charCodeAt(this.pos+2)<=57&&this.buf.charCodeAt(this.pos+3)>=48&&this.buf.charCodeAt(this.pos+3)<=57&&45==this.buf.charCodeAt(this.pos+4)){var k=o.substr(this.buf,this.pos,19);L=o.strDate(k),this.pos+=19}else{var V=this.readFloat(),U=new Date;U.setTime(V),L=U}return this.cache.push(L),L;case 115:var G=this.readDigits(),z=this.buf;if(58!=this.get(this.pos++)||this.length-this.pos>2)+(Y>=2?Y-1:0);for(var Q=X+(G-Y),j=S.alloc(H),K=0;X>4);var Z=W[d.fastCodeAt(z,X++)];j.set(K++,q<<4|Z>>2);var J=W[d.fastCodeAt(z,X++)];j.set(K++,Z<<6|J)}if(Y>=2){var ee=W[d.fastCodeAt(z,X++)],te=W[d.fastCodeAt(z,X++)];if(j.set(K++,ee<<2|te>>4),3==Y){var ie=W[d.fastCodeAt(z,X++)];j.set(K++,te<<4|ie>>2)}}return this.pos+=G,this.cache.push(j),j;case 67:var se=this.unserialize(),re=this.resolver.resolveClass(se);if(null==re)throw new A("Class not found "+se);var ne=p.createEmptyInstance(re);if(this.cache.push(ne),ne.hxUnserialize(this),103!=this.get(this.pos++))throw new A("Invalid custom data");return ne;case 65:var oe=this.unserialize(),ae=this.resolver.resolveClass(oe);if(null==ae)throw new A("Class not found "+oe);return ae;case 66:var le=this.unserialize(),he=this.resolver.resolveEnum(le);if(null==he)throw new A("Enum not found "+le);return he}throw this.pos--,new A("Invalid char "+this.buf.charAt(this.pos)+" at position "+this.pos)},__class__:v};var x=function(){this.h={}};s["haxe.ds.IntMap"]=x,x.__name__=["haxe","ds","IntMap"],x.__interfaces__=[f],x.prototype={set:function(e,t){this.h[e]=t},remove:function(e){return!!this.h.hasOwnProperty(e)&&(delete this.h[e],!0)},keys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(0|t);return o.iter(e)},__class__:x};var b=function(){this.h={},this.h.__keys__={}};s["haxe.ds.ObjectMap"]=b,b.__name__=["haxe","ds","ObjectMap"],b.__interfaces__=[f],b.prototype={set:function(e,t){var i=e.__id__||(e.__id__=++b.count);this.h[i]=t,this.h.__keys__[i]=e},keys:function(){var e=[];for(var t in this.h.__keys__)this.h.hasOwnProperty(t)&&e.push(this.h.__keys__[t]);return o.iter(e)},__class__:b};var T=s["haxe.ds.Option"]={__ename__:["haxe","ds","Option"],__constructs__:["Some","None"]};T.Some=function(e){var t=["Some",0,e];return t.__enum__=T,t.toString=r,t},T.None=["None",1],T.None.toString=r,T.None.__enum__=T;var y=function(){this.h={}};s["haxe.ds.StringMap"]=y,y.__name__=["haxe","ds","StringMap"],y.__interfaces__=[f],y.prototype={set:function(e,t){null!=ft[e]?this.setReserved(e,t):this.h[e]=t},get:function(e){return null!=ft[e]?this.getReserved(e):this.h[e]},setReserved:function(e,t){null==this.rh&&(this.rh={}),this.rh["$"+e]=t},getReserved:function(e){return null==this.rh?null:this.rh["$"+e]},keys:function(){var e=this.arrayKeys();return o.iter(e)},arrayKeys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(t);if(null!=this.rh)for(var t in this.rh)36==t.charCodeAt(0)&&e.push(t.substr(1));return e},__class__:y};var S=function(e){this.length=e.byteLength,this.b=new gt(e),this.b.bufferValue=e,e.hxBytes=this,e.bytes=this.b};s["haxe.io.Bytes"]=S,S.__name__=["haxe","io","Bytes"],S.alloc=function(e){return new S(new mt(e))},S.prototype={get:function(e){return this.b[e]},set:function(e,t){this.b[e]=255&t},__class__:S};var C=s["haxe.io.Error"]={__ename__:["haxe","io","Error"],__constructs__:["Blocked","Overflow","OutsideBounds","Custom"]};C.Blocked=["Blocked",0],C.Blocked.toString=r,C.Blocked.__enum__=C,C.Overflow=["Overflow",1],C.Overflow.toString=r,C.Overflow.__enum__=C,C.OutsideBounds=["OutsideBounds",2],C.OutsideBounds.toString=r,C.OutsideBounds.__enum__=C,C.Custom=function(e){var t=["Custom",3,e];return t.__enum__=C,t.toString=r,t};var E=function(){};s["haxe.io.FPHelper"]=E,E.__name__=["haxe","io","FPHelper"],E.i32ToFloat=function(e){var t=e>>>23&255,i=8388607&e;return 0==i&&0==t?0:(1-(e>>>31<<1))*(1+Math.pow(2,-23)*i)*Math.pow(2,t-127)},E.floatToI32=function(e){if(0==e)return 0;var t;t=e<0?-e:e;var i=Math.floor(Math.log(t)/.6931471805599453);return i<-127?i=-127:i>128&&(i=128),(e<0?-2147483648:0)|i+127<<23|8388607&Math.round(8388608*(t/Math.pow(2,i)-1))},E.i64ToDouble=function(e,t){var i=(t>>20&2047)-1023,s=4294967296*(1048575&t)+2147483648*(e>>>31)+(2147483647&e);return 0==s&&-1023==i?0:(1-(t>>>31<<1))*(1+Math.pow(2,-52)*s)*Math.pow(2,i)},E.doubleToI64=function(e){var t=E.i64tmp;if(0==e)t.low=0,t.high=0;else{var i;i=e<0?-e:e;var s,r=Math.floor(Math.log(i)/.6931471805599453),n=4503599627370496*(i/Math.pow(2,r)-1),o=0|(s=Math.round(n)),a=s/4294967296|0;t.low=o,t.high=(e<0?-2147483648:0)|r+1023<<20|a}return t};var A=function(e){Error.call(this),this.val=e,this.message=String(e),Error.captureStackTrace&&Error.captureStackTrace(this,A)};s["js._Boot.HaxeError"]=A,A.__name__=["js","_Boot","HaxeError"],A.__super__=Error,A.prototype=n(Error.prototype,{__class__:A});var P=function(){};s["js.Boot"]=P,P.__name__=["js","Boot"],P.getClass=function(e){if(e instanceof Array&&null==e.__enum__)return Array;var t=e.__class__;if(null!=t)return t;var i=P.__nativeClassName(e);return null!=i?P.__resolveNativeClass(i):null},P.__string_rec=function(e,t){if(null==e)return"null";if(t.length>=5)return"<...>";var i=typeof e;switch("function"==i&&(e.__name__||e.__ename__)&&(i="object"),i){case"object":if(e instanceof Array){if(e.__enum__){if(2==e.length)return e[0];var s=e[0]+"(";t+="\t";for(var r=2,n=e.length;r0?",":"")+P.__string_rec(e[c],t)}return l+"]"}var u;try{u=e.toString}catch(e){return e instanceof A&&(e=e.val),"???"}if(null!=u&&u!=Object.toString&&"function"==typeof u){var d=e.toString();if("[object Object]"!=d)return d}var _=null,p="{\n";t+="\t";var f=null!=e.hasOwnProperty;for(var _ in e)f&&!e.hasOwnProperty(_)||"prototype"!=_&&"__class__"!=_&&"__super__"!=_&&"__interfaces__"!=_&&"__properties__"!=_&&(2!=p.length&&(p+=", \n"),p+=t+_+" : "+P.__string_rec(e[_],t));return p+"\n"+(t=t.substring(1))+"}";case"function":return"";case"string":return e;default:return String(e)}},P.__interfLoop=function(e,t){if(null==e)return!1;if(e==t)return!0;var i=e.__interfaces__;if(null!=i)for(var s=0,r=i.length;se.byteLength)throw new A(C.OutsideBounds)};s["js.html.compat.DataView"]=I,I.__name__=["js","html","compat","DataView"],I.prototype={getInt8:function(e){var t=this.buf.a[this.offset+e];return t>=128?t-256:t},getUint8:function(e){return this.buf.a[this.offset+e]},getInt16:function(e,t){var i=this.getUint16(e,t);return i>=32768?i-65536:i},getUint16:function(e,t){return t?this.buf.a[this.offset+e]|this.buf.a[this.offset+e+1]<<8:this.buf.a[this.offset+e]<<8|this.buf.a[this.offset+e+1]},getInt32:function(e,t){var i=this.offset+e,s=this.buf.a[i++],r=this.buf.a[i++],n=this.buf.a[i++],o=this.buf.a[i++];return t?s|r<<8|n<<16|o<<24:o|n<<8|r<<16|s<<24},getUint32:function(e,t){var i=this.getInt32(e,t);return i<0?i+4294967296:i},getFloat32:function(e,t){return E.i32ToFloat(this.getInt32(e,t))},getFloat64:function(e,t){var i=this.getInt32(e,t),s=this.getInt32(e+4,t);return E.i64ToDouble(t?i:s,t?s:i)},setInt8:function(e,t){this.buf.a[e+this.offset]=t<0?t+128&255:255&t},setUint8:function(e,t){this.buf.a[e+this.offset]=255&t},setInt16:function(e,t,i){this.setUint16(e,t<0?t+65536:t,i)},setUint16:function(e,t,i){var s=e+this.offset;i?(this.buf.a[s]=255&t,this.buf.a[s++]=t>>8&255):(this.buf.a[s++]=t>>8&255,this.buf.a[s]=255&t)},setInt32:function(e,t,i){this.setUint32(e,t,i)},setUint32:function(e,t,i){var s=e+this.offset;i?(this.buf.a[s++]=255&t,this.buf.a[s++]=t>>8&255,this.buf.a[s++]=t>>16&255,this.buf.a[s++]=t>>>24):(this.buf.a[s++]=t>>>24,this.buf.a[s++]=t>>16&255,this.buf.a[s++]=t>>8&255,this.buf.a[s++]=255&t)},setFloat32:function(e,t,i){this.setUint32(e,E.floatToI32(t),i)},setFloat64:function(e,t,i){var s=E.doubleToI64(t);i?(this.setUint32(e,s.low),this.setUint32(e,s.high)):(this.setUint32(e,s.high),this.setUint32(e,s.low))},__class__:I};var M=function(){};s["js.html.compat.Uint8Array"]=M,M.__name__=["js","html","compat","Uint8Array"],M._new=function(e,t,i){var s;if("number"==typeof e){s=[];for(var r=0;ri.byteLength)throw new A("set() outside of range");for(var r=0,n=e.byteLength;ri.byteLength)throw new A("set() outside of range");for(var l=0,h=a.length;l0||t.handleError(e._errorVal),e._resolved&&!e._pending)try{t.handleResolve(i(e._val))}catch(e){e instanceof A&&(e=e.val),t.handleError(e)}},O.linkAll=function(e,t){for(var i=function(i,s,r){if(0==i.length||O.allFulfilled(i)){for(var n,o=[],a=nt(e)();a.hasNext();){var l=a.next();o.push(l==s?r:l._val)}n=o,t.handleResolve(n)}},s=nt(e)();s.hasNext();){var r=s.next();r._update.push({async:t,linkf:function(e,t,i){return function(s){e(t,i,s)}}(i,function(t){for(var i=[],s=nt(e)();s.hasNext();){var n=s.next();n!=r&&i.push(n)}return i}(),r)})}O.allFulfilled(e)&&t.handleResolve(function(t){for(var i=[],s=nt(e)();s.hasNext();){var r=s.next();i.push(r._val)}return i}())},O.pipeLink=function(e,t,i){var s=!1,r=function(e){if(!s){s=!0;var r=i(e);r._update.push({async:t,linkf:lt(t,t.handleResolve)}),O.immediateLinkUpdate(r,t,(function(e){return e}))}};if(e._update.push({async:t,linkf:r}),e._resolved&&!e._pending)try{r(e._val)}catch(e){e instanceof A&&(e=e.val),t.handleError(e)}},O.allResolved=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._resolved)return!1;return!0},O.allFulfilled=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._fulfilled)return!1;return!0},O.prototype={catchError:function(e){return this._error.push(e),this},errorThen:function(e){return this._errorMap=e,this},isResolved:function(){return this._resolved},isErrored:function(){return this._errored},isErrorHandled:function(){return this._error.length>0},isErrorPending:function(){return this._errorPending},isFulfilled:function(){return this._fulfilled},isPending:function(){return this._pending},handleResolve:function(e){this._resolve(e)},_resolve:function(e){var t,i,s=this;this._pending?B.enqueue((t=lt(this,this._resolve),i=e,function(){t(i)})):(this._resolved=!0,this._pending=!0,B.queue.add((function(){s._val=e;for(var t=0,i=s._update;t0)for(var i=0,s=t._error;i0))throw new A(e);for(var n=0,o=t._update;n0&&null!=(t=B.queue.pop());)t();return B.queue.isEmpty()},B.clear=function(){B.queue=new l},B.f=function(){var e=B.queue.pop();null!=e&&e(),B.queue.isEmpty()||B.continueOnNextLoop()},B.continueOnNextLoop=function(){null!=B.nextLoop?B.nextLoop(B.f):setImmediate(B.f)};var L=s["promhx.error.PromiseError"]={__ename__:["promhx","error","PromiseError"],__constructs__:["AlreadyResolved","DownstreamNotFullfilled"]};L.AlreadyResolved=function(e){var t=["AlreadyResolved",0,e];return t.__enum__=L,t.toString=r,t},L.DownstreamNotFullfilled=function(e){var t=["DownstreamNotFullfilled",1,e];return t.__enum__=L,t.toString=r,t};var k=function(){};s["verb.Verb"]=k,k.__name__=["verb","Verb"],k.main=function(){e.log("verb 2.1.0")};var V=function(){};s["verb.core.ArrayExtensions"]=V,V.__name__=["verb","core","ArrayExtensions"],V.alloc=function(e,t){if(!(t<0))for(;e.length0;){for(var s=e.pop(),r=!0,n=0;ne)return 0;if(t>e-t&&(t=e-t),U.memo_exists(e,t))return U.get_memo(e,t);for(var i=1,s=e,r=1,n=t+1;re)return 0;t>e-t&&(t=e-t);for(var i=1,s=1,r=t+1;s=l&&o<=h||a>=l&&a<=h||l>=o&&l<=a||h>=o&&h<=a},G.prototype={fromPoint:function(e){return new G([e])},add:function(e){if(!this.initialized)return this.dim=e.length,this.min=e.slice(0),this.max=e.slice(0),this.initialized=!0,this;for(var t=0,i=this.dim;tthis.max[s]&&(this.max[s]=e[s]),e[s]e&&(e=n,t=r)}return t},getAxisLength:function(e){return e<0||e>this.dim-1?0:Math.abs(this.min[e]-this.max[e])},intersect:function(e,t){if(!this.initialized)return null;var i=this.min,s=this.max,r=e.min,n=e.max;if(!this.intersects(e,t))return null;for(var o=[],a=[],l=0,h=this.dim;l0?1:-1})),s=Math.floor(e.length/2),(r=new ue(e[s],n,i)).left=this.buildTree(e.slice(0,s),t+1,r),r.right=this.buildTree(e.slice(s+1),t+1,r),r)},nearest:function(e,t,i){var s,r=this,n=new he((function(e){return-e.item1})),o=null;s=o=function(i){for(var s,a,l,h,c=i.dimension,u=r.distanceFunction(e,i.kdPoint.point),d=[],_=0,p=r.dim;_t&&n.pop()},m=0,g=r.dim;m0&&(this.content[0]=t,this.sinkDown(0)),e},peek:function(){return this.content[0]},remove:function(e){for(var t=this.content.length,i=0;i0;){var i=Math.floor((e+1)/2)-1,s=this.content[i];if(!(this.scoreFunction(t)=0;){for(o=[],a=e[c],d=r-1;d>=0;){for(l=a[s-1]*t[s-1][d],u=s-2;u>=1;)h=u-1,l+=a[u]*t[u][d]+a[h]*t[h][d],u-=2;0==u&&(l+=a[0]*t[0][d]),o[d]=l,d--}n[c]=o,c--}return n},ge.add=function(e,t){for(var i=[],s=0,r=e.length;s=0;){for(n=a[i],s=i+1;ss?1:-1}));for(var l=[],h=0,c=r.length;h=.1*m*n||isNaN(u));)m*=.5,++x;if(m*g20)throw new A("Numerical gradient fails");if(d[m]=t[m]+g,r=e(d),d[m]=t[m]-g,n=e(d),d[m]=t[m],isNaN(r)||isNaN(n))g/=16;else{if(_[m]=(r-n)/(2*g),o=t[m]-g,a=t[m],l=t[m]+g,h=(r-s)/g,c=(s-n)/g,u=Ae.max([Math.abs(_[m]),Math.abs(s),Math.abs(r),Math.abs(n),Math.abs(o),Math.abs(a),Math.abs(l),1e-8]),!(Math.min(Ae.max([Math.abs(h-_[m]),Math.abs(c-_[m]),Math.abs(h-c)])/u,g/u)>.001))break;g/=16}}return _},Te.tensor=function(e,t){for(var i,s,r=e.length,n=t.length,o=[],a=r-1;a>=0;){i=[],s=e[a];for(var l=n-1;l>=3;)i[l]=s*t[l],i[--l]=s*t[l],i[--l]=s*t[l],i[--l]=s*t[l],--l;for(;l>=0;)i[l]=s*t[l],--l;o[a]=i,a--}return o};var ye=function(e,t,i,s,r,n){this.solution=e,this.value=t,this.gradient=i,this.invHessian=s,this.iterations=r,this.message=n};s["verb.core.MinimizationResult"]=ye,ye.__name__=["verb","core","MinimizationResult"],ye.prototype={__class__:ye};var Se=function(){};s["verb.core.ISerializable"]=Se,Se.__name__=["verb","core","ISerializable"],Se.prototype={__class__:Se};var Ce=t.core.Deserializer=function(){};s["verb.core.Deserializer"]=Ce,Ce.__name__=["verb","core","Deserializer"],Ce.deserialize=function(e){return new v(e).unserialize()};var Ee=t.core.Trig=function(){};s["verb.core.Trig"]=Ee,Ee.__name__=["verb","core","Trig"],Ee.isPointInPlane=function(e,t,i){return Math.abs(Ae.dot(Ae.sub(e,t.origin),t.normal))o?{u:r,pt:i}:{u:s+(r-s)*c/o,pt:Ae.add(a,Ae.mul(c,l))}};var Ae=t.core.Vec=function(){};s["verb.core.Vec"]=Ae,Ae.__name__=["verb","core","Vec"],Ae.angleBetween=function(e,t){return Math.acos(Ae.dot(e,t)/(Ae.norm(e)*Ae.norm(t)))},Ae.positiveAngleBetween=function(e,t,i){var s=Ae.cross(e,t),r=Ae.norm(e)*Ae.norm(t),n=Ae.dot(e,t),o=Ae.norm(s)/r,a=n/r,l=Math.atan2(o,a),h=Ae.dot(i,s);return Math.abs(h)0?l:-l},Ae.signedAngleBetween=function(e,t,i){var s=Ae.cross(e,t),r=Ae.norm(e)*Ae.norm(t),n=Ae.dot(e,t),o=Ae.norm(s)/r,a=n/r,l=Math.atan2(o,a);return Ae.dot(i,s)>0?l:2*Math.PI-l},Ae.angleBetweenNormalized2d=function(e,t){var i=e[0]*t[1]-e[1]*t[0];return Math.atan2(i,Ae.dot(e,t))},Ae.domain=function(e){return V.last(e)-V.first(e)},Ae.range=function(e){for(var t=[],i=0,s=0;st&&i>0)return[];if(t>e&&i<0)return[];for(var s=[],r=e;r<=t;)s.push(r),r+=i;return s},Ae.neg=function(e){return e.map((function(e){return-e}))},Ae.min=function(e){return a.fold(e,(function(e,t){return Math.min(e,t)}),1/0)},Ae.max=function(e){return a.fold(e,(function(e,t){return Math.max(e,t)}),-1/0)},Ae.all=function(e){return a.fold(e,(function(e,t){return t&&e}),!0)},Ae.finite=function(e){return e.map((function(e){return isFinite(e)}))},Ae.onRay=function(e,t,i){return Ae.add(e,Ae.mul(i,t))},Ae.lerp=function(e,t,i){return Ae.add(Ae.mul(e,t),Ae.mul(1-e,i))},Ae.normalized=function(e){return Ae.div(e,Ae.norm(e))},Ae.cross=function(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]},Ae.dist=function(e,t){return Ae.norm(Ae.sub(e,t))},Ae.distSquared=function(e,t){return Ae.normSquared(Ae.sub(e,t))},Ae.sum=function(e){return a.fold(e,(function(e,t){return t+e}),0)},Ae.addAll=function(e){var t=nt(e)();if(!t.hasNext())return null;var i=t.next().length;return a.fold(e,(function(e,t){return Ae.add(t,e)}),Ae.rep(i,0))},Ae.addAllMutate=function(e){for(var t=e[0],i=1,s=e.length;iz.TOLERANCE)return!1}return!0},Ae.sortedSetUnion=function(e,t){for(var i=[],s=0,r=0;s=e.length)i.push(t[r]),r++;else if(r>=t.length)i.push(e[s]),s++;else{var n=e[s]-t[r];Math.abs(n)0?(i.push(t[r]),r++):(i.push(e[s]),s++)}return i},Ae.sortedSetSub=function(e,t){for(var i=[],s=0,r=0;s=t.length?(i.push(e[s]),s++):Math.abs(e[s]-t[r])z.EPSILON&&(i=new Re(r,0),t.push(i)),i.inc()}return t},Pe.isRationalSurfaceClosed=function(e,t){var i;null==t&&(t=!0);for(var s=0,r=(i=t?e.controlPoints:ge.transpose(e.controlPoints))[0].length;sh&&(A=d?[l+(A[0]-h),A[1]]:[h-z.EPSILON,A[1]]),A[1]u&&(A=_?[A[0],c+(A[0]-u)]:[A[0],u-z.EPSILON]),Ae.norm(Ae.mul(A[0]-r[0],i[1][0]))+Ae.norm(Ae.mul(A[1]-r[1],i[0][1]))x&&(A=b?v+(A-x):x),Ae.norm(Ae.mul(A-T,p[1]))(r=null!=s?s:Pe.rationalBezierCurveArcLength(e)))return V.last(e.knots);var n,o=e.knots[0],a=0,l=V.last(e.knots),h=r,c=0,u=0;for(n=null!=i?i:2*z.TOLERANCE;h-a>n;)c=(o+l)/2,(u=Pe.rationalBezierCurveArcLength(e,c))>t?(l=c,h=u):(o=c,a=u);return(o+l)/2},Pe.rationalCurveArcLength=function(e,t,i){null==i&&(i=16),null==t&&(t=V.last(e.knots));for(var s=Fe.decomposeCurveIntoBeziers(e),r=0,n=s[0],o=0;rz.EPSILON)return!1}i=V.last(e);for(var o=e.length-t-1,a=e.length;oz.EPSILON)return!1}return Ie.isNonDecreasing(e)},Ie.isNonDecreasing=function(e){for(var t=V.first(e),i=0,s=e.length;ir)return n;for(var o,a=t,l=0,h=a,c=0,u=0;l=t[l+1];)l++;o.push(l),n.push(De.basisFunctionsGivenKnotSpanIndex(l,a,e,t)),a+=r}return new q(o,n)},De.regularlySpacedDerivativeBasisFunctions=function(e,t,i){for(var s=t.length-e-2,r=(V.last(t)-t[0])/i,n=[],o=[],a=t[0],l=De.knotSpanGivenN(s,e,a,t),h=i+1,c=0;c=t[l+1];)l++;o.push(l),n.push(De.derivativeBasisFunctionsGivenNI(l,a,e,s,t)),a+=r}return new q(o,n)},De.surfacePointGivenBasesKnotSpans=function(e,t,i,s,r,n,o,a){for(var l,h=Ae.zeros1d(a),c=s-e,u=r-t,d=0,_=t+1;d<_;){var p=d++;l=Ae.zeros1d(a);for(var f=0,m=e+1;f=M&&(m[v][0]=m[g][0]/n[T+1][b],x=m[v][0]*n[b][T]);for(var O=b>=-1?1:-b,D=1+(P-1<=T?M-1:i-P);Os[e+1]-z.EPSILON)return e;if(i=s[o+1];)iz.EPSILON})),(function(e,t){var i=Ae.sub(e.min.uv0,t.min.uv0),s=Ae.dot(i,i),r=Ae.sub(e.max.uv0,t.max.uv0),n=Ae.dot(r,r),o=Ae.sub(e.min.uv0,t.max.uv0),a=Ae.dot(o,o),l=Ae.sub(e.max.uv0,t.min.uv0),h=Ae.dot(l,l);return s0&&(f.push(f[f.length-1].opp),u.push(f))}if(0==c.length&&r.length>0&&(_||d0;){var o=s.pop(),a=r.pop();if(!o.empty()&&!a.empty()&&o.boundingBox().intersects(a.boundingBox(),i)){var l=o.indivisible(i),h=a.indivisible(i);if(l&&h)n.push(new q(o.yield(),a.yield()));else if(!l||h)if(l||!h){var c=o.split(),u=a.split();s.push(c.item1),r.push(u.item1),s.push(c.item1),r.push(u.item0),s.push(c.item0),r.push(u.item1),s.push(c.item0),r.push(u.item0)}else{var d=o.split();s.push(d.item1),r.push(a),s.push(d.item0),r.push(a)}else{var _=a.split();s.push(o),r.push(_.item1),s.push(o),r.push(_.item0)}}}return n},we.curves=function(e,t,i){var s=we.boundingBoxTrees(new _e(e),new _e(t),0);return V.unique(s.map((function(s){return we.curvesWithEstimate(e,t,V.first(s.item0.knots),V.first(s.item1.knots),i)})).filter((function(e){return Ae.distSquared(e.point0,e.point1)h[_]+z.EPSILON||((null==c||vu.u)&&(u=new ne(v,Ae.onRay(e.origin,e.dir,v),Ae.onRay(n[_],o[_],g/h[_]))))}}return null==u||null==c?null:new Z(c,u)},we.mergeTriangleClipIntervals=function(e,t,i,s,r,n){if(t.min.u>e.max.u+z.EPSILON||e.min.u>t.max.u+z.EPSILON)return null;var o,a;o=e.min.u>t.min.u?new q(e.min,0):new q(t.min,1),a=e.max.uc&&(h=1,c=u),d>c&&(h=2,c=d),0==h?(n=t[1],o=t[2],a=s[1],l=s[2]):1==h?(n=t[0],o=t[2],a=s[0],l=s[2]):(n=t[0],o=t[1],a=s[0],l=s[1]);var _=-Ae.dot(e,t),p=-Ae.dot(i,s),f=n*l-o*a,m=(o*p-_*l)/f,g=(_*a-n*p)/f;return new X(0==h?[0,m,g]:1==h?[m,0,g]:[m,g,0],Ae.normalized(r))},we.threePlanes=function(e,t,i,s,r,n){var o=Ae.cross(i,r),a=Ae.dot(e,o);if(Math.abs(a)1)return null;var f=Ae.add(e,Ae.mul(p,c)),m=Ae.dot(a,l),g=Ae.dot(a,a),v=Ae.dot(l,l),x=Ae.sub(f,r),b=Ae.dot(x,a),T=Ae.dot(x,l),y=m*m-g*v;if(Math.abs(y)1+z.EPSILON||C>1+z.EPSILON||C<-z.EPSILON||S<-z.EPSILON||S+C>1+z.EPSILON?null:new re(f,S,C,p)},we.segmentAndPlane=function(e,t,i,s){var r=Ae.dot(s,Ae.sub(t,e));if(Math.abs(r)1+z.EPSILON||n<-z.EPSILON?null:{p:n}};var Ne=t.eval.Make=function(){};s["verb.eval.Make"]=Ne,Ne.__name__=["verb","eval","Make"],Ne.rationalTranslationalSurface=function(e,t){for(var i=De.rationalCurvePoint(t,V.first(t.knots)),s=V.first(t.knots),r=V.last(t.knots),n=2*t.controlPoints.length,o=(r-s)/(n-1),a=[],l=0;l=0&&(u-=n[o].mult),c=u>0?Fe.surfaceKnotRefine(e,Ae.rep(u,t),i):e;var d=De.knotSpan(r,t,s);return Math.abs(t-V.first(s))e.length-1&&(t=e.length-1);for(var s=e[0].knots,r=[],n=[],o=0,a=e[0].controlPoints.length;oz.EPSILON&&(E=Ae.mul(1/A,E),P=Ae.mul(1/A,P)),m[0][S]=o[S];var R=o[S];g[0][S]=a[S];for(var I=P,M=0,O=1,D=r+1;Ot?e:t},Fe.curveElevateDegree=function(e,t){if(t<=e.degree)return e;var i=e.knots.length-e.degree-2,s=e.degree,r=e.knots,n=e.controlPoints,o=t-e.degree,a=e.controlPoints[0].length,l=Ae.zeros2d(s+o+1,s+1),h=[],c=[],u=[],d=i+s+1,_=t,p=Math.floor(_/2),f=[],m=[];l[0][0]=1,l[_][s]=1;for(var g=1,v=p+1;g0?Math.floor((K+2)/2):1,X=D>0?Math.floor(_-(D+1)/2):_,D>0){for(var $=j-B,q=[],Z=s;Z>Q;)q[Z-Q-1]=$/(r[w+Z]-B),Z--;for(var J=1,ee=D+1;J=se;)h[re]=Ae.add(Ae.mul(q[re-se],h[re]),Ae.mul(1-q[re-se],h[re-1])),re--;u[ie]=h[s]}}for(var ne=H,oe=_+1;ne1)for(var de=O-2,_e=O,pe=j-B,fe=(j-m[O-1])/pe,me=1;mege;){if(ve=H){if(xe-ge<=O-_+K){var ye=(j-m[xe-ge])/pe;c[be]=Ae.lerp(ye,c[be],c[be+1])}}else c[be]=Ae.lerp(fe,c[be],c[be+1]);ve+=1,xe-=1,be-=1}de-=1,_e+=1}if(w!=s)for(var Se=0,Ce=_-K;Se=0;){for(;t[A]<=r[C]&&C>l;)c[E-i-1]=s[C-i-1],u[E]=r[C],E-=1,C-=1;c[E-i-1]=c[E-i];for(var P=1,R=i+1;Ps||!Ee.threePointsAreFlat(n,l,o,s)){var u=t+.5*(i-t),d=Be.rationalCurveAdaptiveSampleRange(e,t,u,s,r),_=Be.rationalCurveAdaptiveSampleRange(e,u,i,s,r);return d.slice(0,-1).concat(_)}return r?[[t].concat(n),[i].concat(o)]:[n,o]},Be.rationalSurfaceNaive=function(e,t,i){t<1&&(t=1),i<1&&(i=1),e.degreeU,e.degreeV,e.controlPoints;for(var s=e.knotsU,r=e.knotsV,n=(V.last(s)-s[0])/t,o=(V.last(r)-r[0])/i,a=[],l=[],h=[],c=0,u=t+1;cr?t.minDivsU=t.minDivsU:t.minDivsU=r,s=t.minDivsV>n?t.minDivsV=t.minDivsV:t.minDivsV=n;for(var o=V.last(e.knotsU),a=e.knotsU[0],l=V.last(e.knotsV),h=e.knotsV[0],c=(o-a)/i,u=(l-h)/s,d=[],_=[],p=0,f=s+1;pn.corners[0].uv[0]+r&&e.uv[0]n.corners[0].uv[1]+r&&e.uv[1]=e.maxDepth)return!1;if(this.hasBadNormals())return this.fixNormals(),!1;if(this.splitVert=Ae.normSquared(Ae.sub(this.corners[0].normal,this.corners[1].normal))>e.normTol||Ae.normSquared(Ae.sub(this.corners[2].normal,this.corners[3].normal))>e.normTol,this.splitHoriz=Ae.normSquared(Ae.sub(this.corners[1].normal,this.corners[2].normal))>e.normTol||Ae.normSquared(Ae.sub(this.corners[3].normal,this.corners[0].normal))>e.normTol,this.splitVert||this.splitHoriz)return!0;var i=this.center();return Ae.normSquared(Ae.sub(i.normal,this.corners[0].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[1].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[2].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[3].normal))>e.normTol},divide:function(e){null==e&&(e=new Le),null==e.normTol&&(e.normTol=.085),null==e.minDepth&&(e.minDepth=0),null==e.maxDepth&&(e.maxDepth=10),this._divide(e,0,!0)},_divide:function(e,t,i){if(this.evalCorners(),this.shouldDivide(e,t)){if(t++,this.splitVert&&!this.splitHoriz?i=!1:!this.splitVert&&this.splitHoriz&&(i=!0),this.horizontal=i,this.horizontal){var s=[this.corners[0],this.corners[1],this.midpoint(1),this.midpoint(3)],r=[this.midpoint(3),this.midpoint(1),this.corners[2],this.corners[3]];this.children=[new ke(this.srf,s),new ke(this.srf,r)],this.children[0].neighbors=[this.neighbors[0],this.neighbors[1],this.children[1],this.neighbors[3]],this.children[1].neighbors=[this.children[0],this.neighbors[1],this.neighbors[2],this.neighbors[3]]}else{var n=[this.corners[0],this.midpoint(0),this.midpoint(2),this.corners[3]],o=[this.midpoint(0),this.corners[1],this.corners[2],this.midpoint(2)];this.children=[new ke(this.srf,n),new ke(this.srf,o)],this.children[0].neighbors=[this.neighbors[0],this.children[1],this.neighbors[2],this.neighbors[3]],this.children[1].neighbors=[this.neighbors[0],this.neighbors[1],this.neighbors[2],this.children[0]]}for(var a=0,l=this.children;a0&&this._pool.length>0;){var i=this._queue.shift(),s=[i.id],r=[this._pool.shift()];this._working.h[s[0]]=r[0],r[0].onmessage=function(i,s){return function(r){t._working.remove(s[0]),t._pool.push(i[0]);try{t._callbacks.h.hasOwnProperty(s[0])&&(t._callbacks.h[s[0]](r.data.result),t._callbacks.remove(s[0]))}catch(t){t instanceof A&&(t=t.val),e.log(t)}t.processQueue()}}(r,s),r[0].postMessage(i)}},__class__:Ue};var Ge=function(e,t,i){this.className=e,this.methodName=t,this.args=i,this.id=Ge.uuid++};s["verb.exe._WorkerPool.Work"]=Ge,Ge.__name__=["verb","exe","_WorkerPool","Work"],Ge.prototype={__class__:Ge};var ze=function(){};s["verb.geom.ICurve"]=ze,ze.__name__=["verb","geom","ICurve"],ze.__interfaces__=[Se],ze.prototype={__class__:ze};var We=t.geom.NurbsCurve=function(e){this._data=Ie.isValidNurbsCurveData(e)};s["verb.geom.NurbsCurve"]=We,We.__name__=["verb","geom","NurbsCurve"],We.__interfaces__=[ze],We.byKnotsControlPointsWeights=function(e,t,i,s){return new We(new Y(e,t.slice(),De.homogenize1d(i,s)))},We.byPoints=function(e,t){return null==t&&(t=3),new We(Ne.rationalInterpCurve(e,t))},We.__super__=W,We.prototype=n(W.prototype,{degree:function(){return this._data.degree},knots:function(){return this._data.knots.slice(0)},controlPoints:function(){return De.dehomogenize1d(this._data.controlPoints)},weights:function(){return De.weight1d(this._data.controlPoints)},asNurbs:function(){return new Y(this.degree(),this.knots(),De.homogenize1d(this.controlPoints(),this.weights()))},clone:function(){return new We(this._data)},domain:function(){return new Z(V.first(this._data.knots),V.last(this._data.knots))},transform:function(e){return new We(Fe.rationalCurveTransform(this._data,e))},transformAsync:function(e){return Ve.dispatchMethod(Fe,"rationalCurveTransform",[this._data,e]).then((function(e){return new We(e)}))},point:function(e){return De.rationalCurvePoint(this._data,e)},pointAsync:function(e){return Ve.dispatchMethod(De,"rationalCurvePoint",[this._data,e])},tangent:function(e){return De.rationalCurveTangent(this._data,e)},tangentAsync:function(e){return Ve.dispatchMethod(De,"rationalCurveTangent",[this._data,e])},derivatives:function(e,t){return null==t&&(t=1),De.rationalCurveDerivatives(this._data,e,t)},derivativesAsync:function(e,t){return null==t&&(t=1),Ve.dispatchMethod(De,"rationalCurveDerivatives",[this._data,e,t])},closestPoint:function(e){return Pe.rationalCurveClosestPoint(this._data,e)},closestPointAsync:function(e){return Ve.dispatchMethod(Pe,"rationalCurveClosestPoint",[this._data,e])},closestParam:function(e){return Pe.rationalCurveClosestParam(this._data,e)},closestParamAsync:function(e){return Ve.dispatchMethod(Pe,"rationalCurveClosestParam",[this._data,e])},length:function(){return Pe.rationalCurveArcLength(this._data)},lengthAsync:function(){return Ve.dispatchMethod(Pe,"rationalCurveArcLength",[this._data])},lengthAtParam:function(e){return Pe.rationalCurveArcLength(this._data,e)},lengthAtParamAsync:function(){return Ve.dispatchMethod(Pe,"rationalCurveArcLength",[this._data])},paramAtLength:function(e,t){return Pe.rationalCurveParamAtArcLength(this._data,e,t)},paramAtLengthAsync:function(e,t){return Ve.dispatchMethod(Pe,"rationalCurveParamAtArcLength",[this._data,e,t])},divideByEqualArcLength:function(e){return Me.rationalCurveByEqualArcLength(this._data,e)},divideByEqualArcLengthAsync:function(e){return Ve.dispatchMethod(Me,"rationalCurveByEqualArcLength",[this._data,e])},divideByArcLength:function(e){return Me.rationalCurveByArcLength(this._data,e)},divideByArcLengthAsync:function(e){return Ve.dispatchMethod(Me,"rationalCurveByArcLength",[this._data,e])},split:function(e){return Me.curveSplit(this._data,e).map((function(e){return new We(e)}))},splitAsync:function(e){return Ve.dispatchMethod(Me,"curveSplit",[this._data,e]).then((function(e){return e.map((function(e){return new We(e)}))}))},reverse:function(){return new We(Fe.curveReverse(this._data))},reverseAsync:function(){return Ve.dispatchMethod(Fe,"curveReverse",[this._data]).then((function(e){return new We(e)}))},tessellate:function(e){return Be.rationalCurveAdaptiveSample(this._data,e,!1)},tessellateAsync:function(e){return Ve.dispatchMethod(Be,"rationalCurveAdaptiveSample",[this._data,e,!1])},__class__:We});var He=t.geom.Arc=function(e,t,i,s,r,n){We.call(this,Ne.arc(e,t,i,s,r,n)),this._center=e,this._xaxis=t,this._yaxis=i,this._radius=s,this._minAngle=r,this._maxAngle=n};s["verb.geom.Arc"]=He,He.__name__=["verb","geom","Arc"],He.__super__=We,He.prototype=n(We.prototype,{center:function(){return this._center},xaxis:function(){return this._xaxis},yaxis:function(){return this._yaxis},radius:function(){return this._radius},minAngle:function(){return this._minAngle},maxAngle:function(){return this._maxAngle},__class__:He});var Xe=t.geom.BezierCurve=function(e,t){We.call(this,Ne.rationalBezierCurve(e,t))};s["verb.geom.BezierCurve"]=Xe,Xe.__name__=["verb","geom","BezierCurve"],Xe.__super__=We,Xe.prototype=n(We.prototype,{__class__:Xe});var Ye=t.geom.Circle=function(e,t,i,s){He.call(this,e,t,i,s,0,2*Math.PI)};s["verb.geom.Circle"]=Ye,Ye.__name__=["verb","geom","Circle"],Ye.__super__=He,Ye.prototype=n(He.prototype,{__class__:Ye});var Qe=function(){};s["verb.geom.ISurface"]=Qe,Qe.__name__=["verb","geom","ISurface"],Qe.__interfaces__=[Se],Qe.prototype={__class__:Qe};var je=t.geom.NurbsSurface=function(e){this._data=Ie.isValidNurbsSurfaceData(e)};s["verb.geom.NurbsSurface"]=je,je.__name__=["verb","geom","NurbsSurface"],je.__interfaces__=[Qe],je.byKnotsControlPointsWeights=function(e,t,i,s,r,n){return new je(new Q(e,t,i,s,De.homogenize2d(r,n)))},je.byCorners=function(e,t,i,s){return new je(Ne.fourPointSurface(e,t,i,s))},je.byLoftingCurves=function(e,t){return new je(Ne.loftedSurface(function(t){for(var i=[],s=0;s{},439:()=>{},699:()=>{}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};return(()=>{"use strict";i.r(s),i.d(s,{cleanJSCADCache:()=>vX,cleanOCCTCache:()=>gX,executeScript:()=>fX,fontsEnum:()=>eX,resetRunnerContext:()=>mX,run:()=>_X});var e={};i.r(e),i.d(e,{AbstractActionManager:()=>z,AbstractAssetTask:()=>OP,AbstractMesh:()=>Sn,AbstractScene:()=>G,AcquireNativeObjectAsync:()=>K_,Action:()=>Pe,ActionEvent:()=>Re,ActionManager:()=>Ye,AddBlock:()=>cb,AddressMode:()=>up,AdvancedTimer:()=>Ig,AlignBlock:()=>IS,AlphaState:()=>Ci,AmmoJSPlugin:()=>bv,AnaglyphArcRotateCamera:()=>kh,AnaglyphFreeCamera:()=>Vh,AnaglyphGamepadCamera:()=>Uh,AnaglyphPostProcess:()=>Bh,AnaglyphUniversalCamera:()=>Gh,Analyser:()=>Ao,AndOrNotEvaluator:()=>xt,Angle:()=>vr,Animatable:()=>fr,AnimatedInputBlockTypes:()=>Aa,Animation:()=>Nt,AnimationAssetTask:()=>FP,AnimationEvent:()=>Br,AnimationGroup:()=>kr,AnimationGroupMask:()=>Ur,AnimationGroupMaskMode:()=>ur,AnimationKeyInterpolation:()=>Ke,AnimationPropertiesOverride:()=>mr,AnimationRange:()=>$e,AnisotropyBlock:()=>qb,ApplyPostProcess:()=>c_,Arc2:()=>xr,ArcFollowCamera:()=>Ph,ArcRotateCamera:()=>Th,ArcRotateCameraGamepadInput:()=>Zl,ArcRotateCameraInputsManager:()=>ih,ArcRotateCameraKeyboardMoveInput:()=>Jl,ArcRotateCameraMouseWheelInput:()=>eh,ArcRotateCameraPointersInput:()=>th,ArcRotateCameraVRDeviceOrientationInput:()=>sh,ArcTan2Block:()=>wb,AssetContainer:()=>Eo,AssetTaskState:()=>MP,AssetsManager:()=>WP,AssetsProgressEvent:()=>DP,AsyncLoop:()=>us,AttachToBoxBehavior:()=>$o,AudioEngine:()=>Po,AudioSceneComponent:()=>Mo,AutoLayoutMode:()=>yp,AutoReleaseWorkerPool:()=>Jm,AutoRotationBehavior:()=>Yo,AxesViewer:()=>gu,Axis:()=>_r,AxisDragGizmo:()=>mu,AxisScaleGizmo:()=>Jf,BRDFTextureTools:()=>Cm,BabylonFileLoaderConfiguration:()=>Rv,BackEase:()=>Er,BackgroundMaterial:()=>vm,BakedVertexAnimationManager:()=>Do,BallAndSocketConstraint:()=>PE,BaseCameraMouseWheelInput:()=>Vl,BaseCameraPointersInput:()=>Ul,BaseError:()=>Xt,BaseParticleSystem:()=>rl,BaseSixDofDragBehavior:()=>na,BaseTexture:()=>No,BasisFileInfo:()=>ux,BasisTools:()=>Sx,BasisToolsOptions:()=>px,BasisTranscodeConfiguration:()=>dx,BezierCurve:()=>gr,BezierCurveEase:()=>Fr,BiPlanarBlock:()=>vT,BinaryFileAssetTask:()=>LP,BindBonesParameters:()=>Wn,BindFogParameters:()=>Nn,BindLight:()=>Xn,BindLightProperties:()=>Hn,BindLights:()=>Yn,BindLogDepth:()=>wn,BindMorphTargetParameters:()=>kn,BindSceneUniformBuffer:()=>Vn,BindTextureMatrix:()=>Gn,BlackAndWhitePostProcess:()=>tA,BlendFactor:()=>Pp,BlendOperation:()=>Rp,BloomEffect:()=>nA,BloomMergePostProcess:()=>rA,BlurPostProcess:()=>pm,Bone:()=>pr,BoneAxesViewer:()=>vu,BoneIKController:()=>Fl,BoneLookController:()=>Bl,BonesBlock:()=>Fx,BooleanGeometryBlock:()=>jS,BooleanGeometryOperations:()=>Py,BounceEase:()=>Ar,BouncingBehavior:()=>Qo,BoundingBlock:()=>QS,BoundingBox:()=>qr,BoundingBoxGizmo:()=>em,BoundingBoxRenderer:()=>QA,BoundingInfo:()=>rn,BoundingSphere:()=>Zr,BoxBlock:()=>Qy,BoxBuilder:()=>Su,BoxParticleEmitter:()=>mC,Buffer:()=>Ts,BufferBindingType:()=>mp,BufferMapState:()=>sp,BufferUsage:()=>rp,CSG:()=>ay,Camera:()=>Kr,CameraGizmo:()=>_m,CameraInputTypes:()=>Ql,CameraInputsManager:()=>jl,CannonJSPlugin:()=>vv,CanvasAlphaMode:()=>kp,CapsuleBlock:()=>sS,CapsuleBuilder:()=>Iu,CascadedShadowGenerator:()=>rv,ChromaticAberrationPostProcess:()=>oA,CircleEase:()=>Cr,CircleOfConfusionPostProcess:()=>aA,ClampBlock:()=>db,ClearCoatBlock:()=>Jb,ClipPlanesBlock:()=>ob,ClipboardEventTypes:()=>qf,ClipboardInfo:()=>Zf,CloudBlock:()=>pT,CloudPoint:()=>JC,Collider:()=>Zc,Color3:()=>Ce,Color3Gradient:()=>MC,Color4:()=>Ee,ColorCorrectionPostProcess:()=>lA,ColorCurves:()=>ms,ColorGradient:()=>IC,ColorGradingTexture:()=>Hv,ColorMergerBlock:()=>gb,ColorSplitterBlock:()=>nl,ColorWrite:()=>Ap,CombineAction:()=>Ge,CompareFunction:()=>pp,CompatibilityOptions:()=>dn,CompilationMessageType:()=>bp,CompleteGreasedLineColorTable:()=>Gy,CompleteGreasedLineWidthTable:()=>Uy,ComputeBindingType:()=>tu,ComputeEffect:()=>eu,ComputeNormalsBlock:()=>xS,ComputePassTimestampLocation:()=>wp,ComputeShader:()=>su,ComputeShaderParticleSystem:()=>RC,Condition:()=>Ie,ConditionBlock:()=>_S,ConditionBlockTests:()=>Sy,ConditionalBlock:()=>_T,ConditionalBlockConditions:()=>aT,ConeParticleEmitter:()=>gC,Constants:()=>Yd,ContainerAssetTask:()=>wP,ConversionMode:()=>pP,ConvolutionPostProcess:()=>hA,Coordinate:()=>hr,CopyTextureToTexture:()=>fP,CopyTools:()=>ko,CreateBox:()=>yu,CreateBoxVertexData:()=>bu,CreateCapsule:()=>Ru,CreateCapsuleVertexData:()=>Pu,CreateCylinder:()=>lu,CreateCylinderVertexData:()=>au,CreateDashedLines:()=>Ju,CreateDashedLinesVertexData:()=>$u,CreateDecal:()=>Pd,CreateDisc:()=>Nu,CreateDiscVertexData:()=>wu,CreateEnvTextureAsync:()=>A_,CreateGeodesic:()=>wd,CreateGoldberg:()=>Bd,CreateGoldbergVertexData:()=>Fd,CreateGreasedLine:()=>Vy,CreateGreasedLineMaterial:()=>ky,CreateGround:()=>Uc,CreateGroundFromHeightMap:()=>zc,CreateGroundFromHeightMapVertexData:()=>Vc,CreateGroundVertexData:()=>Lc,CreateHemisphere:()=>hm,CreateIcoSphere:()=>Sl,CreateIcoSphereVertexData:()=>yl,CreateImageDataArrayBufferViews:()=>R_,CreateLathe:()=>_d,CreateLineSystem:()=>qu,CreateLineSystemVertexData:()=>Ku,CreateLines:()=>Zu,CreatePlane:()=>ta,CreatePlaneVertexData:()=>ea,CreatePolygon:()=>od,CreatePolygonVertexData:()=>nd,CreatePolyhedron:()=>vd,CreatePolyhedronVertexData:()=>gd,CreateResizedCopy:()=>h_,CreateRibbon:()=>Ou,CreateRibbonVertexData:()=>Mu,CreateScreenshot:()=>dR,CreateScreenshotAsync:()=>_R,CreateScreenshotUsingRenderTarget:()=>fR,CreateScreenshotUsingRenderTargetAsync:()=>mR,CreateScreenshotWithResizeAsync:()=>pR,CreateSegmentedBoxVertexData:()=>Tu,CreateSphere:()=>Eu,CreateSphereVertexData:()=>Cu,CreateText:()=>Ud,CreateTextShapePaths:()=>Vd,CreateTiledBox:()=>Uu,CreateTiledBoxVertexData:()=>Vu,CreateTiledGround:()=>Gc,CreateTiledGroundVertexData:()=>kc,CreateTiledPlane:()=>Lu,CreateTiledPlaneVertexData:()=>Bu,CreateTorus:()=>Xc,CreateTorusKnot:()=>Wu,CreateTorusKnotVertexData:()=>zu,CreateTorusVertexData:()=>Hc,CreateTube:()=>fd,CrossBlock:()=>_b,CubeMapToSphericalPolynomialTools:()=>b_,CubeTexture:()=>mm,CubeTextureAssetTask:()=>UP,CubicEase:()=>Pr,CullMode:()=>Ep,CurrentScreenBlock:()=>Ha,Curve3:()=>yr,CurveBlock:()=>yT,CurveBlockTypes:()=>hT,CustomBlock:()=>pb,CustomOptimization:()=>eR,CustomParticleEmitter:()=>CC,CustomProceduralTexture:()=>Rx,CylinderBlock:()=>iS,CylinderBuilder:()=>hu,CylinderDirectedParticleEmitter:()=>xC,CylinderParticleEmitter:()=>vC,DDSTools:()=>jm,DataBuffer:()=>Oi,DataReader:()=>TR,DataStorage:()=>yR,Database:()=>fC,DebugBlock:()=>VS,DebugLayer:()=>xu,DebugLayerTab:()=>pu,DecalBuilder:()=>Rd,DecalMapConfiguration:()=>PT,DecalMapDefines:()=>AT,Decode:()=>$t,DecodeBase64ToBinary:()=>Jt,DecodeBase64ToString:()=>Zt,DecodeBase64UrlToBinary:()=>es,DecodeBase64UrlToString:()=>ts,DeepCopier:()=>Xe,DefaultCollisionCoordinator:()=>Jc,DefaultKTX2DecoderOptions:()=>ng,DefaultLoadingScreen:()=>av,DefaultRenderingPipeline:()=>MA,Deferred:()=>HP,DepthCullingState:()=>yi,DepthOfFieldBlurPostProcess:()=>cA,DepthOfFieldEffect:()=>_A,DepthOfFieldEffectBlurLevel:()=>dA,DepthOfFieldMergePostProcess:()=>uA,DepthPeelingRenderer:()=>$A,DepthPeelingSceneComponent:()=>qA,DepthReducer:()=>Zg,DepthRenderer:()=>$g,DepthRendererSceneComponent:()=>jA,DepthSortedParticle:()=>$C,DerivativeBlock:()=>Hx,DesaturateBlock:()=>Kb,DetailMapConfiguration:()=>xc,DeviceInputEventType:()=>Hs,DeviceLostReason:()=>Vp,DeviceOrientationCamera:()=>yh,DeviceSource:()=>$s,DeviceSourceManager:()=>Zs,DeviceType:()=>Ls,DirectionalLight:()=>lm,DirectionalLightFrustumViewer:()=>Xd,DiscBlock:()=>rS,DiscBuilder:()=>Fu,DiscardBlock:()=>zx,DisplayPassPostProcess:()=>pA,DistanceBlock:()=>Rb,DistanceConstraint:()=>RE,DistanceJoint:()=>_a,DivideBlock:()=>bb,DoNothingAction:()=>Ue,DomManagement:()=>Gt,DotBlock:()=>fb,DracoCompression:()=>ey,DrawWrapper:()=>Fi,DualSenseInput:()=>Gs,DualShockButton:()=>Xl,DualShockDpad:()=>Yl,DualShockInput:()=>Us,DualShockPad:()=>Ih,DumpTools:()=>_l,DynamicFloat32Array:()=>OR,DynamicTexture:()=>Sc,EasingFunction:()=>Sr,EdgesRenderer:()=>JA,Effect:()=>Ti,EffectFallbacks:()=>ja,EffectLayer:()=>Vg,EffectLayerSceneComponent:()=>Ug,EffectRenderer:()=>al,EffectWrapper:()=>ll,ElasticEase:()=>Rr,ElbowBlock:()=>mT,EncodeArrayBufferToBase64:()=>qt,EndsWith:()=>jt,Engine:()=>gn,EngineFactory:()=>$f,EngineFormat:()=>ig,EngineInstrumentation:()=>Lg,EngineStore:()=>se,EngineView:()=>Zd,EnvironmentHelper:()=>xm,EnvironmentTextureTools:()=>N_,Epsilon:()=>K,EquiRectangularCubeTexture:()=>Xv,EquiRectangularCubeTextureAssetTask:()=>zP,ErrorCodes:()=>Yt,ErrorFilter:()=>Up,EventConstants:()=>Xs,EventState:()=>W,ExecuteCodeAction:()=>ze,ExponentialEase:()=>Ir,ExternalTexture:()=>xf,ExtractHighlightsPostProcess:()=>sA,ExtrudePolygon:()=>ad,ExtrudeShape:()=>hd,ExtrudeShapeCustom:()=>cd,FactorGradient:()=>OC,FadeInOutBehavior:()=>qo,FeatureName:()=>ip,FileTools:()=>is,FileToolsOptions:()=>Hi,FilesInput:()=>YP,FilesInputStore:()=>Wt,FilterMode:()=>dp,FilterPostProcess:()=>fA,FlowGraph:()=>aM,FlowGraphAbsBlock:()=>_O,FlowGraphAcosBlock:()=>HO,FlowGraphAcoshBlock:()=>qO,FlowGraphAddBlock:()=>iO,FlowGraphAsinBlock:()=>WO,FlowGraphAsinhBlock:()=>$O,FlowGraphAtan2Block:()=>YO,FlowGraphAtanBlock:()=>XO,FlowGraphAtanhBlock:()=>ZO,FlowGraphBitwiseAndBlock:()=>mD,FlowGraphBitwiseLeftShiftBlock:()=>xD,FlowGraphBitwiseNotBlock:()=>fD,FlowGraphBitwiseOrBlock:()=>gD,FlowGraphBitwiseRightShiftBlock:()=>bD,FlowGraphBitwiseXorBlock:()=>vD,FlowGraphBlock:()=>ZI,FlowGraphBranchBlock:()=>gM,FlowGraphCeilBlock:()=>gO,FlowGraphClampBlock:()=>AO,FlowGraphConditionalDataBlock:()=>wM,FlowGraphConnection:()=>OI,FlowGraphConnectionType:()=>MI,FlowGraphConsoleLogBlock:()=>uM,FlowGraphConstantBlock:()=>BM,FlowGraphContext:()=>sM,FlowGraphContextLogger:()=>hM,FlowGraphCoordinateTransformBlock:()=>FM,FlowGraphCoordinator:()=>lM,FlowGraphCosBlock:()=>GO,FlowGraphCoshBlock:()=>jO,FlowGraphCountLeadingZerosBlock:()=>TD,FlowGraphCountOneBitsBlock:()=>SD,FlowGraphCountTrailingZerosBlock:()=>yD,FlowGraphCounterBlock:()=>EM,FlowGraphCrossBlock:()=>lD,FlowGraphCubeRootBlock:()=>rD,FlowGraphDataConnection:()=>QI,FlowGraphDebounceBlock:()=>PM,FlowGraphDegToRadBlock:()=>kO,FlowGraphDeterminantBlock:()=>dD,FlowGraphDivideBlock:()=>nO,FlowGraphDoNBlock:()=>vM,FlowGraphDotBlock:()=>aO,FlowGraphEBlock:()=>lO,FlowGraphEqBlock:()=>MO,FlowGraphEventBlock:()=>iM,FlowGraphExecutionBlock:()=>eM,FlowGraphExpBlock:()=>JO,FlowGraphFlipFlopBlock:()=>RM,FlowGraphFloorBlock:()=>mO,FlowGraphForLoopBlock:()=>xM,FlowGraphFractBlock:()=>vO,FlowGraphGetPropertyBlock:()=>LM,FlowGraphGetVariableBlock:()=>NM,FlowGraphGreaterThanBlock:()=>NO,FlowGraphGreaterThanOrEqualBlock:()=>FO,FlowGraphInfBlock:()=>cO,FlowGraphInterpolateBlock:()=>IO,FlowGraphInvertMatrixBlock:()=>_D,FlowGraphIsInfBlock:()=>LO,FlowGraphIsNanBlock:()=>BO,FlowGraphLengthBlock:()=>oD,FlowGraphLessThanBlock:()=>DO,FlowGraphLessThanOrEqualBlock:()=>wO,FlowGraphLog10Block:()=>iD,FlowGraphLog2Block:()=>tD,FlowGraphLogBlock:()=>eD,FlowGraphLogicAndBlock:()=>QM,FlowGraphLogicNotBlock:()=>KM,FlowGraphLogicOrBlock:()=>jM,FlowGraphMatMulBlock:()=>pD,FlowGraphMaxBlock:()=>SO,FlowGraphMeshPickEventBlock:()=>nM,FlowGraphMinBlock:()=>yO,FlowGraphMultiGateBlock:()=>yM,FlowGraphMultiplyBlock:()=>rO,FlowGraphNaNBlock:()=>uO,FlowGraphNegBlock:()=>xO,FlowGraphNormalizeBlock:()=>aD,FlowGraphPauseAnimationBlock:()=>DM,FlowGraphPiBlock:()=>hO,FlowGraphPlayAnimationBlock:()=>MM,FlowGraphPowBlock:()=>nD,FlowGraphRadToDegBlock:()=>VO,FlowGraphRandomBlock:()=>oO,FlowGraphReceiveCustomEventBlock:()=>ED,FlowGraphRemainderBlock:()=>TO,FlowGraphRotate2DBlock:()=>hD,FlowGraphRotate3DBlock:()=>cD,FlowGraphSaturateBlock:()=>RO,FlowGraphSceneReadyEventBlock:()=>CD,FlowGraphSceneTickEventBlock:()=>AD,FlowGraphSendCustomEventBlock:()=>mM,FlowGraphSequenceBlock:()=>IM,FlowGraphSetPropertyBlock:()=>fM,FlowGraphSetVariableBlock:()=>dM,FlowGraphSignBlock:()=>pO,FlowGraphSignalConnection:()=>JI,FlowGraphSinBlock:()=>UO,FlowGraphSinhBlock:()=>QO,FlowGraphSqrtBlock:()=>sD,FlowGraphState:()=>oM,FlowGraphStopAnimationBlock:()=>OM,FlowGraphSubtractBlock:()=>sO,FlowGraphSwitchBlock:()=>SM,FlowGraphTanBlock:()=>zO,FlowGraphTanhBlock:()=>KO,FlowGraphThrottleBlock:()=>bM,FlowGraphTimerBlock:()=>TM,FlowGraphTransposeBlock:()=>uD,FlowGraphTruncBlock:()=>fO,FlowGraphWaitAllBlock:()=>CM,FlowGraphWhileLoopBlock:()=>AM,FluidRenderer:()=>bP,FluidRendererSceneComponent:()=>xP,FluidRenderingDebug:()=>uP,FluidRenderingObject:()=>lP,FluidRenderingObjectCustomParticles:()=>_P,FluidRenderingObjectParticleSystem:()=>hP,FluidRenderingTargetRenderer:()=>dP,FlyCamera:()=>Ch,FlyCameraInputsManager:()=>Sh,FlyCameraKeyboardInput:()=>rh,FlyCameraMouseInput:()=>nh,FogBlock:()=>Jx,FollowBehavior:()=>la,FollowCamera:()=>Ah,FollowCameraInputsManager:()=>Eh,FollowCameraKeyboardMoveInput:()=>oh,FollowCameraMouseWheelInput:()=>ah,FollowCameraPointersInput:()=>lh,FragCoordBlock:()=>Xx,FragDepthBlock:()=>$x,FragmentOutputBlock:()=>La,FramingBehavior:()=>jo,FreeCamera:()=>xh,FreeCameraDeviceOrientationInput:()=>ph,FreeCameraGamepadInput:()=>fh,FreeCameraInputsManager:()=>_h,FreeCameraKeyboardMoveInput:()=>hh,FreeCameraMouseInput:()=>ch,FreeCameraMouseWheelInput:()=>uh,FreeCameraTouchInput:()=>dh,FreeCameraVirtualJoystickInput:()=>gh,FresnelBlock:()=>Eb,FresnelParameters:()=>kv,FromHalfFloat:()=>p_,FrontFace:()=>Cp,FrontFacingBlock:()=>Wx,Frustum:()=>sr,FxaaPostProcess:()=>mA,GIRSM:()=>CP,GIRSMManager:()=>EP,GIRSMRenderPluginMaterial:()=>PP,GPUParticleSystem:()=>XC,GUID:()=>os,Gamepad:()=>$l,GamepadCamera:()=>wh,GamepadManager:()=>Mh,GamepadSystemSceneComponent:()=>Oh,GaussianSplattingMaterial:()=>XT,GaussianSplattingMesh:()=>dC,GenerateBase64StringFromPixelData:()=>Fo,GenerateBase64StringFromTexture:()=>Bo,GenerateBase64StringFromTextureAsync:()=>Lo,GenericPad:()=>ql,GeodesicData:()=>Dd,Geometry:()=>_n,GeometryArcTan2Block:()=>KS,GeometryBufferRenderer:()=>TA,GeometryBufferRendererSceneComponent:()=>SA,GeometryClampBlock:()=>iC,GeometryCollectionBlock:()=>gS,GeometryCrossBlock:()=>sC,GeometryCurveBlock:()=>rC,GeometryCurveBlockTypes:()=>Ry,GeometryDesaturateBlock:()=>nC,GeometryDistanceBlock:()=>lC,GeometryDotBlock:()=>hC,GeometryElbowBlock:()=>vS,GeometryInfoBlock:()=>US,GeometryInputBlock:()=>Yy,GeometryLengthBlock:()=>cC,GeometryLerpBlock:()=>$S,GeometryModBlock:()=>eC,GeometryNLerpBlock:()=>qS,GeometryOptimizeBlock:()=>Ky,GeometryOutputBlock:()=>Hy,GeometryPosterizeBlock:()=>oC,GeometryPowBlock:()=>tC,GeometryReplaceColorBlock:()=>aC,GeometryRotate2dBlock:()=>uC,GeometrySmoothStepBlock:()=>JS,GeometryStepBlock:()=>ZS,GeometryTextureBlock:()=>XS,GeometryTextureFetchBlock:()=>YS,GeometryTransformBlock:()=>CS,GeometryTrigonometryBlock:()=>SS,GeometryTrigonometryBlockOperations:()=>Ey,GetClass:()=>te,GetDOMTextContent:()=>Ut,GetEnvInfo:()=>C_,GetEnvironmentBRDFTexture:()=>Sm,GetFogState:()=>$n,GetInternalFormatFromBasisFormat:()=>fx,GetTGAHeader:()=>nx,GetTextureDataAsync:()=>m_,Gizmo:()=>fu,GizmoAnchorPoint:()=>du,GizmoCoordinatesMode:()=>_u,GizmoManager:()=>om,GlowLayer:()=>Gg,GoldbergMesh:()=>Nd,GradientBlock:()=>Gb,GradientBlockColorStep:()=>Ub,GradientHelper:()=>DC,GrainPostProcess:()=>gA,GreasedLineBaseMesh:()=>Fy,GreasedLineMaterialDefaults:()=>FT,GreasedLineMesh:()=>By,GreasedLineMeshColorDistribution:()=>my,GreasedLineMeshColorDistributionType:()=>dT,GreasedLineMeshColorMode:()=>uT,GreasedLineMeshMaterialType:()=>cT,GreasedLineMeshWidthDistribution:()=>gy,GreasedLinePluginMaterial:()=>kT,GreasedLineRibbonAutoDirectionMode:()=>fy,GreasedLineRibbonFacesMode:()=>py,GreasedLineRibbonMesh:()=>Ly,GreasedLineRibbonPointsMode:()=>_y,GreasedLineSimpleMaterial:()=>VT,GreasedLineTools:()=>BT,GridBlock:()=>eS,GroundBuilder:()=>Wc,GroundMesh:()=>Bc,HDRCubeTexture:()=>uv,HDRCubeTextureAssetTask:()=>GP,HDRFiltering:()=>cv,HDRTools:()=>hv,Halton2DSequence:()=>jT,HandConstraintBehavior:()=>Nl,HandConstraintOrientation:()=>Dl,HandConstraintVisibility:()=>wl,HandConstraintZone:()=>Ol,HandPart:()=>El,HandleFallbacksForShadows:()=>Kn,HardwareScalingOptimization:()=>$P,HavokPlugin:()=>zE,HeightToNormalBlock:()=>Kx,HemisphereBuilder:()=>cm,HemisphericLight:()=>cu,HemisphericParticleEmitter:()=>bC,HighlightLayer:()=>Wg,HighlightsPostProcess:()=>vA,Hinge2Joint:()=>ma,HingeConstraint:()=>IE,HingeJoint:()=>fa,HtmlElementTexture:()=>Yv,IWebXRControllerPhysicsOptions:()=>YR,IcoSphereBlock:()=>Zy,IcoSphereBuilder:()=>Cl,ImageAssetTask:()=>kP,ImageProcessingBlock:()=>Vx,ImageProcessingConfiguration:()=>xs,ImageProcessingPostProcess:()=>xA,ImageSourceBlock:()=>tb,IncrementValueAction:()=>Le,IndexFormat:()=>Mp,InputBlock:()=>Wa,InspectableType:()=>xR,InstancedLinesMesh:()=>ju,InstancedMesh:()=>To,InstancesBlock:()=>Bx,InstantiateBlock:()=>FS,InstantiateLinearBlock:()=>BS,InstantiateOnFacesBlock:()=>DS,InstantiateOnVerticesBlock:()=>OS,InstantiateOnVolumeBlock:()=>wS,InstantiateRadialBlock:()=>LS,InstantiatedEntries:()=>Co,IntFloatConverterBlock:()=>kS,InternalTexture:()=>Pi,InternalTextureSource:()=>Ai,InterpolateValueAction:()=>Ft,IntersectionInfo:()=>$r,IsBase64DataUrl:()=>Zi,IsDocumentAvailable:()=>Vt,IsFileURL:()=>qi,IsNavigatorAvailable:()=>kt,IsWindowObjectExist:()=>Lt,JoystickAxis:()=>zl,KeepAssets:()=>So,KeyboardEventTypes:()=>Ns,KeyboardInfo:()=>Fs,KeyboardInfoPre:()=>Bs,KhronosTextureContainer:()=>qm,KhronosTextureContainer2:()=>og,LatheBuilder:()=>pd,Layer:()=>Xg,LayerSceneComponent:()=>Hg,LengthBlock:()=>Ib,LensFlare:()=>Yg,LensFlareSystem:()=>Qg,LensFlareSystemSceneComponent:()=>jg,LensFlaresOptimization:()=>JP,LensRenderingPipeline:()=>OA,LerpBlock:()=>xb,Light:()=>yo,LightBlock:()=>eb,LightGizmo:()=>dm,LightInformationBlock:()=>kx,LineEdgesRenderer:()=>eP,LinesBuilder:()=>ed,LinesMesh:()=>Qu,LoadFile:()=>Ki,LoadFileError:()=>Gi,LoadImage:()=>Qi,LoadOp:()=>Fp,LoadTextureFromTranscodeResult:()=>yx,LockConstraint:()=>OE,Logger:()=>we,MapMode:()=>np,MapRangeBlock:()=>dS,MappingBlock:()=>GS,MappingTypes:()=>Ay,Material:()=>uo,MaterialAnisotropicDefines:()=>Om,MaterialClearCoatDefines:()=>Pm,MaterialDefines:()=>Oa,MaterialDetailMapDefines:()=>vc,MaterialFlags:()=>lc,MaterialGreasedLineDefines:()=>LT,MaterialHelper:()=>Vv,MaterialIridescenceDefines:()=>Im,MaterialPluginBase:()=>gc,MaterialPluginEvent:()=>En,MaterialPluginManager:()=>cc,MaterialSheenDefines:()=>wm,MaterialSubSurfaceDefines:()=>Fm,MathBlock:()=>uS,MathBlockOperations:()=>yy,Matrix:()=>fe,MatrixBuilderBlock:()=>oT,MatrixComposeBlock:()=>zS,MatrixDeterminantBlock:()=>xT,MatrixTransposeBlock:()=>bT,MaxBlock:()=>Ab,MergeGeometryBlock:()=>mS,MergeMeshesOptimization:()=>sR,Mesh:()=>bo,MeshAssetTask:()=>NP,MeshAttributeExistsBlock:()=>TT,MeshAttributeExistsBlockTypes:()=>lT,MeshBlock:()=>qy,MeshBuilder:()=>Gd,MeshDebugMode:()=>GT,MeshDebugPluginMaterial:()=>WT,MeshExploder:()=>XP,MeshLODLevel:()=>po,MeshParticleEmitter:()=>EC,MeshUVSpaceRenderer:()=>ly,MeshoptCompression:()=>ty,MinBlock:()=>Pb,MinMaxReducer:()=>qg,MipmapFilterMode:()=>_p,MirrorTexture:()=>fm,ModBlock:()=>nT,ModelShape:()=>KC,MorphTarget:()=>dv,MorphTargetManager:()=>pv,MorphTargetsBlock:()=>Lx,MotionBlurPostProcess:()=>CA,MotorEnabledJoint:()=>pa,MultiMaterial:()=>_o,MultiObserver:()=>QP,MultiPointerScaleBehavior:()=>ra,MultiRenderTarget:()=>Ex,MultiplyBlock:()=>tl,NLerpBlock:()=>zb,NativeDataStream:()=>i_,NativeEngine:()=>J_,NativePointerInput:()=>Vs,NativeXRFrame:()=>II,NativeXRLayerRenderTargetTextureProvider:()=>Oc,NativeXRLayerWrapper:()=>Mc,NativeXRRenderTarget:()=>Dc,NegateBlock:()=>Mb,Node:()=>Ct,NodeGeometry:()=>jy,NodeGeometryBlock:()=>Wy,NodeGeometryBlockConnectionPointTypes:()=>vy,NodeGeometryBuildState:()=>Xy,NodeGeometryConnectionPoint:()=>zy,NodeGeometryConnectionPointCompatibilityStates:()=>xy,NodeGeometryConnectionPointDirection:()=>by,NodeGeometryContextualSources:()=>Ty,NodeMaterial:()=>Tl,NodeMaterialBlock:()=>wa,NodeMaterialBlockConnectionPointMode:()=>Ca,NodeMaterialBlockConnectionPointTypes:()=>xa,NodeMaterialBlockTargets:()=>ba,NodeMaterialConnectionPoint:()=>Da,NodeMaterialConnectionPointCompatibilityStates:()=>Ta,NodeMaterialConnectionPointCustomObject:()=>Nx,NodeMaterialConnectionPointDirection:()=>ya,NodeMaterialDefines:()=>bl,NodeMaterialModes:()=>il,NodeMaterialOptimizer:()=>ST,NodeMaterialSystemValues:()=>Ea,NodeMaterialTeleportInBlock:()=>lb,NodeMaterialTeleportOutBlock:()=>hb,NoiseBlock:()=>fS,NoiseProceduralTexture:()=>Ix,NormalBlendBlock:()=>Xb,NormalizeBlock:()=>mb,NormalizeVectorBlock:()=>TS,NullBlock:()=>nS,NullEngine:()=>jd,NullEngineOptions:()=>Qd,Observable:()=>X,Observer:()=>H,OcclusionMaterial:()=>Uv,Octree:()=>nu,OctreeBlock:()=>ru,OctreeSceneComponent:()=>ou,OimoJSPlugin:()=>xv,OnAfterEnteringVRObservableEvent:()=>Kc,OneMinusBlock:()=>Sb,Orientation:()=>cr,OutlineRenderer:()=>aP,PBRAnisotropicConfiguration:()=>Dm,PBRBaseMaterial:()=>Vm,PBRBaseSimpleMaterial:()=>Gv,PBRClearCoatConfiguration:()=>Rm,PBRIridescenceConfiguration:()=>Mm,PBRMaterial:()=>Um,PBRMaterialDefines:()=>km,PBRMetallicRoughnessBlock:()=>rT,PBRMetallicRoughnessMaterial:()=>zv,PBRSheenConfiguration:()=>Nm,PBRSpecularGlossinessMaterial:()=>Wv,PBRSubSurfaceConfiguration:()=>Bm,PHI:()=>j,PadNumber:()=>ei,PanoramaToCubeMapTools:()=>lv,Particle:()=>wC,ParticleBlendMultiplyBlock:()=>Qa,ParticleHelper:()=>QC,ParticleRampGradientBlock:()=>Ya,ParticleSystem:()=>HC,ParticleSystemSet:()=>YC,ParticleTextureBlock:()=>Xa,ParticlesOptimization:()=>tR,PassCubePostProcess:()=>Fh,PassPostProcess:()=>Nh,Path2:()=>br,Path3D:()=>Tr,PathCursor:()=>Vr,PerfCollectionStrategy:()=>kR,PerfCounter:()=>tr,PerformanceConfigurator:()=>ie,PerformanceMonitor:()=>pn,PerformanceViewerCollector:()=>BR,PerturbNormalBlock:()=>Gx,PhotoDome:()=>Tm,Physics6DoFConstraint:()=>AE,Physics6DoFLimit:()=>EE,PhysicsActivationControl:()=>hE,PhysicsAggregate:()=>NE,PhysicsBody:()=>fE,PhysicsConstraint:()=>CE,PhysicsConstraintAxis:()=>sE,PhysicsConstraintAxisLimitMode:()=>iE,PhysicsConstraintMotorType:()=>oE,PhysicsConstraintType:()=>rE,PhysicsEngine:()=>gv,PhysicsEngineV2:()=>pE,PhysicsEventType:()=>aE,PhysicsHelper:()=>XE,PhysicsImpostor:()=>ga,PhysicsJoint:()=>da,PhysicsMaterialCombineMode:()=>cE,PhysicsMotionType:()=>lE,PhysicsRadialExplosionEventOptions:()=>$E,PhysicsRadialImpulseFalloff:()=>uE,PhysicsRaycastResult:()=>mv,PhysicsShape:()=>mE,PhysicsShapeBox:()=>bE,PhysicsShapeCapsule:()=>vE,PhysicsShapeContainer:()=>SE,PhysicsShapeConvexHull:()=>TE,PhysicsShapeCylinder:()=>xE,PhysicsShapeMesh:()=>yE,PhysicsShapeSphere:()=>gE,PhysicsShapeType:()=>nE,PhysicsUpdraftEventOptions:()=>qE,PhysicsUpdraftMode:()=>dE,PhysicsViewer:()=>zd,PhysicsVortexEventOptions:()=>ZE,PickingInfo:()=>Ss,PipelineErrorReason:()=>Tp,PivotTools:()=>Jo,Plane:()=>ir,PlaneBlock:()=>$y,PlaneBuilder:()=>ia,PlaneDragGizmo:()=>sm,PlaneRotationGizmo:()=>tm,PlayAnimationAction:()=>ke,PlaySoundAction:()=>Qe,PointColor:()=>tE,PointLight:()=>ov,PointParticleEmitter:()=>TC,PointerDragBehavior:()=>sa,PointerEventTypes:()=>Ms,PointerInfo:()=>ws,PointerInfoBase:()=>Os,PointerInfoPre:()=>Ds,PointerInput:()=>ks,PointsCloudSystem:()=>_E,PointsGroup:()=>eE,Polar:()=>YT,Polygon:()=>sd,PolygonBuilder:()=>ld,PolygonMeshBuilder:()=>rd,PolyhedronBuilder:()=>xd,PolyhedronData:()=>Od,PositionGizmo:()=>rm,PositionNormalTextureVertex:()=>Va,PositionNormalVertex:()=>ka,PostProcess:()=>qa,PostProcessManager:()=>Cs,PostProcessRenderEffect:()=>iA,PostProcessRenderPipeline:()=>PA,PostProcessRenderPipelineManager:()=>RA,PostProcessRenderPipelineManagerSceneComponent:()=>IA,PostProcessesOptimization:()=>ZP,PosterizeBlock:()=>Lb,PowBlock:()=>Ob,PowerEase:()=>Mr,PowerPreference:()=>tp,PrePassOutputBlock:()=>Zx,PrePassRenderer:()=>iP,PrePassRendererSceneComponent:()=>sP,PrePassTextureBlock:()=>ab,PrecisionDate:()=>zt,PredicateCondition:()=>Oe,PrepareAttributesForBakedVertexAnimation:()=>zn,PrepareAttributesForBones:()=>Qn,PrepareAttributesForInstances:()=>jn,PrepareAttributesForMorphTargets:()=>Bn,PrepareAttributesForMorphTargetsInfluencers:()=>Fn,PrepareDefinesForAttributes:()=>ro,PrepareDefinesForBakedVertexAnimation:()=>so,PrepareDefinesForBones:()=>to,PrepareDefinesForCamera:()=>lo,PrepareDefinesForFrameBoundValues:()=>eo,PrepareDefinesForLight:()=>Jn,PrepareDefinesForLights:()=>Zn,PrepareDefinesForMergedUV:()=>Un,PrepareDefinesForMisc:()=>qn,PrepareDefinesForMorphTargets:()=>io,PrepareDefinesForMultiview:()=>no,PrepareDefinesForOIT:()=>oo,PrepareDefinesForPrePass:()=>ao,PrepareUniformsAndSamplersForLight:()=>ho,PrepareUniformsAndSamplersList:()=>co,PressureObserverWrapper:()=>MR,PrimitiveTopology:()=>Sp,PrismaticConstraint:()=>DE,ProceduralTexture:()=>ml,ProceduralTextureSceneComponent:()=>fl,PropertyTypeForEdition:()=>Sa,ProximityCastResult:()=>JE,PushAttributesForInstances:()=>Ln,PushMaterial:()=>Ra,QuadraticEase:()=>Or,QuadraticErrorSimplification:()=>wy,QuarticEase:()=>Dr,Quaternion:()=>pe,QueryType:()=>Lp,QuinticEase:()=>wr,RGBDTextureTools:()=>v_,RSMCreatePluginMaterial:()=>SP,Ragdoll:()=>BE,RagdollBoneProperties:()=>FE,RandomBlock:()=>pS,RandomBlockLocks:()=>Cy,RandomGUID:()=>ns,RandomNumberBlock:()=>Db,RawCubeTexture:()=>Mx,RawTexture:()=>Wo,RawTexture2DArray:()=>_v,RawTexture3D:()=>Ox,Ray:()=>Zo,RayHelper:()=>Wd,ReadFile:()=>ji,ReadFileError:()=>Wi,RecastJSCrowd:()=>pC,RecastJSPlugin:()=>_C,ReciprocalBlock:()=>Fb,ReflectBlock:()=>Qb,ReflectionBlock:()=>Zb,ReflectionProbe:()=>Tv,ReflectionTextureBaseBlock:()=>sb,ReflectionTextureBlock:()=>rb,ReflectiveShadowMap:()=>TP,Reflector:()=>IR,RefractBlock:()=>jb,RefractionBlock:()=>tT,RefractionPostProcess:()=>EA,RefractionTexture:()=>Dx,RegisterClass:()=>ee,RegisterMaterialPlugin:()=>pc,RegisterNativeTypeAsync:()=>$_,RemapBlock:()=>Ja,RenderPassTimestampLocation:()=>Np,RenderTargetTexture:()=>pl,RenderTargetWrapper:()=>Ka,RenderTargetsOptimization:()=>iR,RenderingGroup:()=>Es,RenderingGroupInfo:()=>As,RenderingManager:()=>Ps,ReplaceColorBlock:()=>Bb,RequestFile:()=>$i,RequestFileError:()=>zi,RetryStrategy:()=>Ht,RibbonBuilder:()=>Du,RichType:()=>wI,RichTypeAny:()=>NI,RichTypeBoolean:()=>LI,RichTypeColor3:()=>zI,RichTypeColor4:()=>WI,RichTypeFlowGraphInteger:()=>XI,RichTypeMatrix:()=>GI,RichTypeNumber:()=>BI,RichTypeQuaternion:()=>HI,RichTypeString:()=>FI,RichTypeVector2:()=>kI,RichTypeVector3:()=>VI,RichTypeVector4:()=>UI,RollingAverage:()=>fn,Rotate2dBlock:()=>Yb,RotationGizmo:()=>im,RotationXBlock:()=>ES,RotationYBlock:()=>AS,RotationZBlock:()=>PS,RuntimeAnimation:()=>Bt,RuntimeError:()=>Qt,SSAO2RenderingPipeline:()=>wA,SSAORenderingPipeline:()=>NA,SSRRenderingPipeline:()=>GA,SamplerBindingType:()=>gp,Scalar:()=>xe,ScaleBlock:()=>ub,ScaleGizmo:()=>nm,ScalingBlock:()=>RS,Scene:()=>dr,SceneComponentConstants:()=>Rs,SceneDepthBlock:()=>nb,SceneInstrumentation:()=>kg,SceneLoader:()=>Pa,SceneLoaderAnimationGroupLoadingMode:()=>va,SceneLoaderFlags:()=>un,SceneOptimization:()=>jP,SceneOptimizer:()=>nR,SceneOptimizerOptions:()=>rR,ScenePerformancePriority:()=>ar,SceneRecorder:()=>SR,SceneSerializer:()=>hR,ScreenSizeBlock:()=>Yx,ScreenSpaceBlock:()=>Qx,ScreenSpaceCurvaturePostProcess:()=>YA,ScreenSpaceReflectionPostProcess:()=>BA,ScreenshotTools:()=>vR,SerializationHelper:()=>yt,SetBasisTranscoderWorker:()=>xx,SetColorsBlock:()=>hS,SetCorsBehavior:()=>Yi,SetMaterialIDBlock:()=>yS,SetNormalsBlock:()=>aS,SetParentAction:()=>We,SetPositionsBlock:()=>oS,SetStateAction:()=>Fe,SetTangentsBlock:()=>cS,SetUVsBlock:()=>lS,SetValueAction:()=>Be,ShaderCodeInliner:()=>U_,ShaderLanguage:()=>ui,ShaderMaterial:()=>Yu,ShaderStage:()=>fp,ShaderStore:()=>bi,ShadowDepthWrapper:()=>ET,ShadowGenerator:()=>Kg,ShadowGeneratorSceneComponent:()=>nv,ShadowLight:()=>am,ShadowMapBlock:()=>qx,ShadowsOptimization:()=>qP,ShapeBuilder:()=>dd,ShapeCastResult:()=>eA,SharpenPostProcess:()=>AA,SheenBlock:()=>$b,SimplexPerlin3DBlock:()=>Hb,SimplicationQueueSceneComponent:()=>Ny,SimplificationQueue:()=>uy,SimplificationSettings:()=>cy,SimplificationType:()=>dy,SineEase:()=>Nr,SixDofDragBehavior:()=>oa,Size:()=>Et,Skeleton:()=>Ho,SkeletonViewer:()=>Hd,SliderConstraint:()=>ME,SmartArray:()=>ds,SmartArrayNoDuplicate:()=>_s,SmoothStepBlock:()=>Nb,SolidParticle:()=>jC,SolidParticleSystem:()=>ZC,SolidParticleVertex:()=>qC,Sound:()=>Ro,SoundTrack:()=>Io,SourceTextureFormat:()=>eg,Space:()=>lr,SphereBlock:()=>Jy,SphereBuilder:()=>Au,SphereDirectedParticleEmitter:()=>SC,SphereParticleEmitter:()=>yC,Spherical:()=>QT,SphericalHarmonics:()=>a_,SphericalPolynomial:()=>l_,SpotLight:()=>um,SpringConstraint:()=>wE,Sprite:()=>Sv,SpriteManager:()=>Av,SpriteMap:()=>RP,SpritePackedManager:()=>IP,SpriteSceneComponent:()=>Cv,Stage:()=>Is,StandardMaterial:()=>yc,StandardMaterialDefines:()=>Tc,StandardRenderingPipeline:()=>LA,StartsWith:()=>Kt,StateCondition:()=>De,StencilOperation:()=>Ip,StencilState:()=>Si,StencilStateComposer:()=>Bi,StepBlock:()=>yb,StereoscopicArcRotateCamera:()=>Xh,StereoscopicFreeCamera:()=>Yh,StereoscopicGamepadCamera:()=>Qh,StereoscopicInterlacePostProcess:()=>Wh,StereoscopicInterlacePostProcessI:()=>zh,StereoscopicScreenUniversalCamera:()=>Kh,StereoscopicUniversalCamera:()=>jh,StickValues:()=>Kl,StopAnimationAction:()=>Ve,StopSoundAction:()=>je,StorageBuffer:()=>Ll,StorageTextureAccess:()=>xp,StoreOp:()=>Bp,StringDictionary:()=>ps,StringTools:()=>ti,SubEmitter:()=>BC,SubEmitterType:()=>FC,SubMesh:()=>ln,SubSurfaceBlock:()=>iT,SubSurfaceSceneComponent:()=>oP,SubtractBlock:()=>Tb,SurfaceMagnetismBehavior:()=>aa,SwitchBooleanAction:()=>Ne,SwitchInput:()=>Ws,TAARenderingPipeline:()=>zA,TBNBlock:()=>Ux,TGATools:()=>ax,Tags:()=>bt,TargetCamera:()=>vh,TargetedAnimation:()=>Lr,TeleportInBlock:()=>WS,TeleportOutBlock:()=>HS,TestBase64DataUrl:()=>Ji,TextFileAssetTask:()=>BP,Texture:()=>Vo,TextureAspect:()=>hp,TextureAssetTask:()=>VP,TextureBlock:()=>ib,TextureDimension:()=>op,TextureFormat:()=>cp,TextureOptimization:()=>KP,TexturePacker:()=>Px,TexturePackerFrame:()=>Ax,TextureSampleType:()=>vp,TextureSampler:()=>Ei,TextureTools:()=>g_,TextureUsage:()=>ap,TextureViewDimension:()=>lp,ThinEngine:()=>ki,ThinRenderTargetTexture:()=>wx,ThinTexture:()=>wo,TiledBoxBuilder:()=>Gu,TiledPlaneBuilder:()=>ku,TimerState:()=>Sg,TmpColors:()=>Ae,TmpVectors:()=>ge,ToGammaSpace:()=>Y,ToHalfFloat:()=>__,ToLinearSpace:()=>Q,TonemapPostProcess:()=>HA,TonemappingOperator:()=>WA,Tools:()=>hs,TorusBlock:()=>tS,TorusBuilder:()=>Yc,TorusKnotBuilder:()=>Hu,TouchCamera:()=>bh,TrailMesh:()=>hy,Trajectory:()=>CR,TrajectoryClassifier:()=>RR,TranscodeAsync:()=>bx,TranscodeTarget:()=>tg,TransformBlock:()=>Na,TransformNode:()=>xn,TranslationBlock:()=>MS,TriPlanarBlock:()=>gT,TrigonometryBlock:()=>vl,TrigonometryBlockOperations:()=>gl,TubeBuilder:()=>md,TwirlBlock:()=>jx,UniformBuffer:()=>bs,UniversalCamera:()=>Dh,UnregisterAllMaterialPlugins:()=>mc,UnregisterMaterialPlugin:()=>fc,UploadContent:()=>ox,UploadEnvLevelsAsync:()=>I_,UploadEnvSpherical:()=>D_,UploadLevelsAsync:()=>O_,UtilityLayerRenderer:()=>uu,VRCameraMetrics:()=>qh,VRDeviceOrientationArcRotateCamera:()=>rc,VRDeviceOrientationFreeCamera:()=>nc,VRDeviceOrientationGamepadCamera:()=>oc,VRDistortionCorrectionPostProcess:()=>Zh,VRExperienceHelper:()=>$c,VRMultiviewToSingleviewPostProcess:()=>ic,ValidatedNativeDataStream:()=>ep,ValueCondition:()=>Me,Vector2:()=>ue,Vector2ToFixed:()=>KT,Vector3:()=>de,Vector3ToFixed:()=>$T,Vector4:()=>_e,Vector4ToFixed:()=>qT,VectorConverterBlock:()=>bS,VectorMergerBlock:()=>Za,VectorSplitterBlock:()=>vb,VertexAnimationBaker:()=>Xo,VertexBuffer:()=>ys,VertexData:()=>cn,VertexDataMaterialInfo:()=>hn,VertexFormat:()=>Op,VertexOutputBlock:()=>Fa,VertexStepMode:()=>Dp,VideoDome:()=>Bg,VideoRecorder:()=>cR,VideoTexture:()=>Fg,ViewDirectionBlock:()=>Cb,Viewport:()=>jr,VirtualJoystick:()=>mh,VirtualJoysticksCamera:()=>$h,VolumetricLightScatteringPostProcess:()=>XA,VoronoiNoiseBlock:()=>fT,WaveBlock:()=>Vb,WaveBlockKind:()=>kb,WebGL2ParticleSystem:()=>PC,WebGL2ShaderProcessor:()=>Mi,WebGLDataBuffer:()=>Di,WebGLHardwareTexture:()=>Ni,WebGLPipelineContext:()=>wi,WebGPUCacheBindGroups:()=>Sf,WebGPUCacheRenderPipeline:()=>pf,WebGPUCacheRenderPipelineTree:()=>mf,WebGPUCacheSampler:()=>hf,WebGPUDataBuffer:()=>rf,WebGPUDrawContext:()=>Tf,WebGPUEngine:()=>Wf,WebGPURenderTargetWrapper:()=>Kf,WebGPUTintWASM:()=>Lf,WebRequest:()=>At,WebXRAbstractFeature:()=>ua,WebXRAbstractMotionController:()=>ug,WebXRAnchorSystem:()=>zR,WebXRBackgroundRemover:()=>XR,WebXRCamera:()=>lg,WebXRControllerComponent:()=>cg,WebXRControllerMovement:()=>tI,WebXRControllerPhysics:()=>QR,WebXRControllerPointerSelection:()=>bg,WebXRDefaultExperience:()=>Dg,WebXRDefaultExperienceOptions:()=>Og,WebXRDepthSensing:()=>mI,WebXRDomOverlay:()=>eI,WebXREnterExitUI:()=>Pg,WebXREnterExitUIButton:()=>Eg,WebXREnterExitUIOptions:()=>Ag,WebXRExperienceHelper:()=>hg,WebXREyeTracking:()=>sI,WebXRFeatureName:()=>ha,WebXRFeaturePointSystem:()=>KR,WebXRFeaturesManager:()=>ca,WebXRGenericHandController:()=>TI,WebXRGenericTriggerMotionController:()=>dg,WebXRHTCViveMotionController:()=>PI,WebXRHand:()=>Il,WebXRHandJoint:()=>Al,WebXRHandTracking:()=>Ml,WebXRHitTest:()=>jR,WebXRHitTestLegacy:()=>UR,WebXRImageTracking:()=>JR,WebXRInput:()=>xg,WebXRInputSource:()=>vg,WebXRLayerRenderTargetTextureProvider:()=>Ec,WebXRLayers:()=>fI,WebXRLightEstimation:()=>iI,WebXRManagedOutputCanvas:()=>Ic,WebXRManagedOutputCanvasOptions:()=>Rc,WebXRMeshDetector:()=>qR,WebXRMicrosoftMixedRealityController:()=>SI,WebXRMotionControllerManager:()=>mg,WebXRMotionControllerTeleportation:()=>Mg,WebXRNearControllerMode:()=>yg,WebXRNearInteraction:()=>Cg,WebXROculusTouchMotionController:()=>EI,WebXRPlaneDetector:()=>HR,WebXRProfiledMotionController:()=>pg,WebXRRawCameraAccess:()=>bI,WebXRSessionManager:()=>wc,WebXRSpaceWarp:()=>xI,WebXRSpaceWarpRenderTargetTextureProvider:()=>vI,WebXRState:()=>Nc,WebXRTrackingState:()=>Fc,WebXRWalkingLocomotion:()=>lI,WeightedSound:()=>Oo,WorkerPool:()=>Zm,WorleyNoise3DBlock:()=>Wb,XRSpaceWarpRenderTarget:()=>gI,Xbox360Button:()=>Wl,Xbox360Dpad:()=>Hl,Xbox360Pad:()=>Rh,XboxInput:()=>zs,_BabylonLoaderRegistered:()=>Pv,_BasisTextureLoader:()=>Cx,_CreationDataStorage:()=>fo,_DDSTextureLoader:()=>Km,_ENVTextureLoader:()=>$m,_HDRTextureLoader:()=>hx,_InstancesBatch:()=>go,_KTXTextureLoader:()=>ag,_MeshCollisionData:()=>bn,_OcclusionDataStorage:()=>$d,_PrimaryIsoTriangle:()=>Md,_TGATextureLoader:()=>lx,_TimeToken:()=>Kd,_UpdateRGBDAsync:()=>w_,_forceSceneHelpersToBundle:()=>wg,_forceTransformFeedbackToBundle:()=>qd,_injectLTSFileTools:()=>ss,_staticOffsetValueColor3:()=>Ot,_staticOffsetValueColor4:()=>Dt,_staticOffsetValueQuaternion:()=>Pt,_staticOffsetValueSize:()=>Mt,_staticOffsetValueVector2:()=>It,_staticOffsetValueVector3:()=>Rt,addClipPlaneUniforms:()=>An,allocateAndCopyTypedBuffer:()=>mn,bindClipPlane:()=>In,captureEquirectangularFromScene:()=>VR,className:()=>cs,createDetailMapPlugin:()=>NT,createPBRAnisotropicPlugin:()=>RT,createPBRBRDFPlugin:()=>IT,createPBRClearCoatPlugin:()=>MT,createPBRIridescencePlugin:()=>OT,createPBRSheenPlugin:()=>DT,createPBRSubSurfacePlugin:()=>wT,createYieldingScheduler:()=>zr,editableInPropertyPage:()=>Ba,expandToProperty:()=>it,extractMinAndMax:()=>an,extractMinAndMaxIndexed:()=>on,getRichTypeFromValue:()=>YI,inlineScheduler:()=>Gr,makeAsyncFunction:()=>Qr,makeSyncFunction:()=>Yr,nativeOverride:()=>mt,normalizeEnvInfo:()=>E_,prepareDefinesForClipPlanes:()=>Rn,prepareStringDefinesForClipPlanes:()=>Pn,runCoroutine:()=>Wr,runCoroutineAsync:()=>Xr,runCoroutineSync:()=>Hr,serialize:()=>st,serializeAsCameraReference:()=>ft,serializeAsColor3:()=>nt,serializeAsColor4:()=>ut,serializeAsColorCurves:()=>ct,serializeAsFresnelParameters:()=>ot,serializeAsImageProcessingConfiguration:()=>dt,serializeAsMatrix:()=>pt,serializeAsMeshReference:()=>ht,serializeAsQuaternion:()=>_t,serializeAsTexture:()=>rt,serializeAsVector2:()=>at,serializeAsVector3:()=>lt,setAndStartTimer:()=>Rg,setStereoscopicAnaglyphRigMode:()=>Lh,setStereoscopicRigMode:()=>Hh,setVRRigMode:()=>sc});var t={};i.r(t),i.d(t,{AbstractButton3D:()=>Ow,AdvancedDynamicTexture:()=>Cw,AdvancedDynamicTextureInstrumentation:()=>Ew,BaseGradient:()=>bw,BaseSlider:()=>sw,Button:()=>zD,Button3D:()=>Dw,Checkbox:()=>HD,CheckboxGroup:()=>ow,ColorPicker:()=>jD,Container:()=>LD,Container3D:()=>ww,Control:()=>BD,Control3D:()=>Iw,CornerHandle:()=>Jw,CylinderPanel:()=>Fw,DisplayGrid:()=>gw,Ellipse:()=>KD,FluentBackplateMaterial:()=>Gw,FluentButtonMaterial:()=>Xw,FluentMaterial:()=>Lw,FluentMaterialDefines:()=>Bw,FocusableButton:()=>$D,GUI3DManager:()=>SN,GizmoHandle:()=>qw,Grid:()=>QD,HandMenu:()=>Vw,HandleMaterial:()=>Kw,HandleState:()=>$w,HolographicBackplate:()=>zw,HolographicButton:()=>Ww,HolographicSlate:()=>tN,Image:()=>GD,ImageBasedSlider:()=>vw,ImageScrollBar:()=>dw,InputPassword:()=>ZD,InputText:()=>YD,InputTextArea:()=>qD,KeyPropertySet:()=>fw,Line:()=>JD,LinearGradient:()=>Tw,MRDLBackplateMaterial:()=>uN,MRDLSliderBarMaterial:()=>aN,MRDLSliderThumbMaterial:()=>hN,MathTools:()=>FD,Matrix2D:()=>ND,Measure:()=>DD,MeshButton3D:()=>iN,MultiLine:()=>tw,MultiLinePoint:()=>ew,NearMenu:()=>sN,PlanePanel:()=>rN,RadialGradient:()=>yw,RadioButton:()=>iw,RadioGroup:()=>aw,Rectangle:()=>kD,ScatterPanel:()=>nN,ScrollBar:()=>uw,ScrollViewer:()=>_w,SelectionPanel:()=>hw,SelectorGroup:()=>nw,SideHandle:()=>Zw,SlateGizmo:()=>eN,Slider:()=>rw,Slider3D:()=>dN,SliderGroup:()=>lw,SpherePanel:()=>_N,StackPanel:()=>WD,StackPanel3D:()=>pN,Style:()=>Sw,TextBlock:()=>UD,TextWrapper:()=>XD,TextWrapping:()=>VD,ToggleButton:()=>pw,TouchButton3D:()=>Yw,TouchHolographicButton:()=>Qw,TouchHolographicButtonV3:()=>yN,TouchHolographicMenu:()=>kw,TouchMeshButton3D:()=>fN,ValueAndUnit:()=>PD,Vector2WithInfo:()=>wD,Vector3WithInfo:()=>Rw,VirtualKeyboard:()=>mw,VolumeBasedPanel:()=>Nw,XmlLoader:()=>Pw,name:()=>xw});var r={};i.r(r),i.d(r,{LodDto:()=>YG,lodEnum:()=>kG});var n={};i.r(n),i.d(n,{Part:()=>QG});var o={};i.r(o),i.d(o,{SerenitySwirlData:()=>KG,SerenitySwirlDto:()=>jG});var a={};i.r(a),i.d(a,{ArabicArchwayData:()=>ZG,ArabicArchwayDrawingPart:()=>JG,ArabicArchwayDrawingPartShapes:()=>ez,ArabicArchwayDto:()=>qG,ArabicArchwayDtoBase:()=>$G});var l={};i.r(l),i.d(l,{ArabicArchway:()=>a,SerenitySwirl:()=>o});var h={};i.r(h),i.d(h,{EternalLoveData:()=>sz,EternalLoveDto:()=>iz,EternalLoveDtoBase:()=>tz});var c={};i.r(c),i.d(c,{EternalLove:()=>h});var u={};i.r(u),i.d(u,{CalmCupData:()=>oz,CalmCupDto:()=>nz,CalmCupDtoBase:()=>rz});var d={};i.r(d),i.d(d,{DragonCupData:()=>hz,DragonCupDto:()=>lz,DragonCupDtoBase:()=>az,DragonCupModelDto:()=>cz});var _={};i.r(_),i.d(_,{CalmCup:()=>u,DragonCup:()=>d});var p={};i.r(p),i.d(p,{PhoneNestData:()=>_z,PhoneNestDrawDto:()=>vz,PhoneNestDrawingPart:()=>pz,PhoneNestDrawingPartShapes:()=>fz,PhoneNestDto:()=>dz,PhoneNestDtoBase:()=>uz,PhoneNestMainPart:()=>mz,PhoneNestModelDto:()=>gz});var f={};i.r(f),i.d(f,{PhoneNest:()=>p});var m={};i.r(m),i.d(m,{SpicyBoxData:()=>Tz,SpicyBoxDto:()=>bz,SpicyBoxDtoBase:()=>xz,SpicyBoxModelDto:()=>yz});var g={};i.r(g),i.d(g,{SpicyBox:()=>m});var v={};i.r(v),i.d(v,{Boxes:()=>g,Cups:()=>_,Desktop:()=>f,Medals:()=>c,Vases:()=>l});var x={};i.r(x),i.d(x,{ZenHideoutData:()=>Ez,ZenHideoutDrawingPart:()=>Az,ZenHideoutDrawingPartShapes:()=>Pz,ZenHideoutDto:()=>Cz,ZenHideoutDtoBase:()=>Sz});var b={};i.r(b),i.d(b,{ZenHideout:()=>x});var T={};i.r(T),i.d(T,{BeamPart:()=>kz,CeilingPart:()=>Qz,ColumnPart:()=>Lz,CornerEntranceDto:()=>Kz,CornerEntrancePart:()=>Hz,CornerPart:()=>Bz,CornerStairDto:()=>zz,CornerStairPart:()=>Wz,FloorPart:()=>jz,Houses:()=>b,RoofBeamsPart:()=>Uz,RoofCoverOneSidedDto:()=>Xz,RoofCoverPart:()=>Yz,RoofPanelPart:()=>Gz,RoofPart:()=>Vz,SandwitchPanelDto:()=>Dz,SandwitchPanelFlexDto:()=>wz,SandwitchPart:()=>Nz,SandwitchPartFlex:()=>Fz,WindowCornerDto:()=>Rz,WindowCornerPart:()=>Oz,WindowRectangularDto:()=>Iz,WindowRectangularPart:()=>Mz});var y={};i.r(y),i.d(y,{WingtipVillaData:()=>qz,WingtipVillaDto:()=>$z});var S={};i.r(S),i.d(S,{ChirpyChaletData:()=>Jz,ChirpyChaletDto:()=>Zz});var C={};i.r(C),i.d(C,{ChirpyChalet:()=>S,WingtipVilla:()=>y});var E={};i.r(E),i.d(E,{BirdHouses:()=>C});var A={};i.r(A),i.d(A,{SnakeChairData:()=>iW,SnakeChairDrawDto:()=>aW,SnakeChairDrawingPart:()=>sW,SnakeChairDrawingPartShapes:()=>rW,SnakeChairDto:()=>tW,SnakeChairDtoBase:()=>eW,SnakeChairMainPart:()=>nW,SnakeChairModelDto:()=>oW});var P={};i.r(P),i.d(P,{SnakeChair:()=>A});var R={};i.r(R),i.d(R,{ElegantTableData:()=>cW,ElegantTableDrawDto:()=>gW,ElegantTableDrawingPart:()=>uW,ElegantTableDrawingPartShapes:()=>dW,ElegantTableDto:()=>hW,ElegantTableDtoBase:()=>lW,ElegantTableLegByIndexDto:()=>fW,ElegantTableLegPart:()=>_W,ElegantTableModelDto:()=>mW,ElegantTableTopPart:()=>pW});var I={};i.r(I),i.d(I,{GoodCoffeeTableData:()=>bW,GoodCoffeeTableDrawDto:()=>RW,GoodCoffeeTableDrawingPart:()=>TW,GoodCoffeeTableDrawingPartShapes:()=>yW,GoodCoffeeTableDto:()=>xW,GoodCoffeeTableDtoBase:()=>vW,GoodCoffeeTableLegByIndexDto:()=>AW,GoodCoffeeTableLegPart:()=>SW,GoodCoffeeTableModelDto:()=>PW,GoodCoffeeTableShelfPart:()=>CW,GoodCoffeeTableTopPart:()=>EW});var M={};i.r(M),i.d(M,{SnakeTableData:()=>OW,SnakeTableDrawDto:()=>BW,SnakeTableDrawingPart:()=>DW,SnakeTableDrawingPartShapes:()=>wW,SnakeTableDto:()=>MW,SnakeTableDtoBase:()=>IW,SnakeTableMainPart:()=>NW,SnakeTableModelDto:()=>FW});var O={};i.r(O),i.d(O,{ElegantTable:()=>R,GoodCoffeeTable:()=>I,SnakeTable:()=>M});var D={};i.r(D),i.d(D,{Chairs:()=>P,Tables:()=>O});var w={};i.r(w),i.d(w,{Architecture:()=>T,Enums:()=>r,Furniture:()=>D,KidsCorner:()=>E,Shared:()=>n,ThreeDPrinting:()=>v});var N={};i.r(N),i.d(N,{FontDefinition:()=>zW,Text3DData:()=>UW,Text3DDto:()=>kW,Text3DFaceDefinitionDto:()=>HW,Text3DFaceDto:()=>VW,Text3DLetterByIndexDto:()=>GW,Text3DModelDto:()=>WW,Texts3DFaceDto:()=>XW,faceTextVarEnum:()=>GG,faceTypeEnum:()=>zG,fontVariantsEnum:()=>UG,fontsEnum:()=>VG,fontsModel:()=>LW,recAlignmentEnum:()=>WG});var F={};i.r(F),i.d(F,{PyramidSimpeByIndexDto:()=>KW,PyramidSimpleAffectorsDto:()=>QW,PyramidSimpleCellPart:()=>rH,PyramidSimpleData:()=>jW,PyramidSimpleDto:()=>YW,PyramidSimpleFacePart:()=>nH,PyramidSimpleModelCellDto:()=>JW,PyramidSimpleModelCellsDto:()=>qW,PyramidSimpleModelCellsIndexDto:()=>ZW,PyramidSimpleModelDto:()=>$W,PyramidSimpleModelFaceCellIndexDto:()=>tH,PyramidSimpleModelFaceCellsUIndexDto:()=>iH,PyramidSimpleModelFaceCellsVIndexDto:()=>sH,PyramidSimpleModelFaceIndexDto:()=>eH});var B={};i.r(B),i.d(B,{PyramidSimple:()=>F});var L={};i.r(L),i.d(L,{FacePatterns:()=>B});var k={};i.r(k),i.d(k,{outputShapeEnum:()=>oH});var V={};i.r(V),i.d(V,{Enums:()=>k,Patterns:()=>L,Text3D:()=>N});var U={};i.r(U),i.d(U,{Asset:()=>oV,BabylonCamera:()=>aV,BabylonIO:()=>lV,BabylonMaterial:()=>hV,BabylonMesh:()=>cV,BabylonMeshBuilder:()=>_V,BabylonNode:()=>CV,BabylonPick:()=>uV,BabylonRay:()=>dV,BabylonScene:()=>RV,BabylonTexture:()=>pV,BabylonWebXR:()=>fV,Base:()=>PV,Color:()=>mV,Draw:()=>gV,JSCAD:()=>vV,JSON:()=>xV,Line:()=>bV,Lists:()=>TV,Logic:()=>yV,Math:()=>SV,OCCT:()=>rk,Point:()=>EV,Polyline:()=>AV,Tag:()=>IV,Text:()=>MV,Time:()=>OV,Transforms:()=>DV,Vector:()=>wV,Verb:()=>NV});class G{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}G._BabylonFileParsers={},G._IndividualBabylonFileParsers={};class z{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in z.Triggers)if(Object.prototype.hasOwnProperty.call(z.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in z.Triggers)if(Object.prototype.hasOwnProperty.call(z.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in z.Triggers)if(Object.prototype.hasOwnProperty.call(z.Triggers,t)&&parseInt(t)===e)return!0;return!1}}z.Triggers={};class W{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class H{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class X{static FromPromise(e,t){const i=new X;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new W(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new H(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{this._remove(e)}),0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new X;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const Y=1/2.2,Q=2.2,j=(1+Math.sqrt(5))/2,K=.001;class ${static BuildArray(e,t){const i=[];for(let s=0;sfunction(e,t,i){const s=e[t];if("function"!=typeof s)return null;const r=function(){const s=e.length,n=r.previous.apply(e,arguments);return i(t,s),n};return s.next=r,r.previous=s,e[t]=r,()=>{const i=r.previous;if(!i)return;const s=r.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}const J={};function ee(e,t){J[e]=t}function te(e){return J[e]}class ie{static SetMatrixPrecision(e){if(ie.MatrixTrackPrecisionChange=!1,e&&!ie.MatrixUse64Bits&&ie.MatrixTrackedMatrices)for(let e=0;eparseInt(e.toString().replace(/\W/g,""));class ue{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=ce(this.x);return e=397*e^ce(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return ue.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new this.constructor(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new this.constructor(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.copyFromFloats(this.x-e,this.y-t)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new this.constructor(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=K){return e&&re(this.x,e.x,t)&&re(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new ue(0,0)}static One(){return new ue(1,1)}static Random(e=0,t=1){return new ue(ne(e,t),ne(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ne(e,t),ne(e,t))}static get ZeroReadOnly(){return ue._ZeroReadOnly}static FromArray(e,t=0){return new ue(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new e.constructor(a,l)}static ClampToRef(e,t,i,s){return s.x=ae(e.x,t.x,i.x),s.y=ae(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=ae(e.x,t.x,i.x),r=ae(e.y,t.y,i.y);return new e.constructor(s,r)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.x*a+i.x*l+t.x*h+s.x*c,d=e.y*a+i.y*l+t.y*h+s.y*c;return new e.constructor(u,d)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n.x=6*(o-r)*e.x+(3*o-4*r+1)*t.x+6*(-o+r)*i.x+(3*o-2*r)*s.x,n.y=6*(o-r)*e.y+(3*o-4*r+1)*t.y+6*(-o+r)*i.y+(3*o-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new e.constructor(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){const t=new e.constructor;return ue.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new e.constructor(i,s)}static Transform(e,t){const i=new e.constructor;return ue.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&a>0&&o+a<2*r*n}static Distance(e,t){return Math.sqrt(ue.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){const i=new e.constructor;return ue.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=ue.DistanceSquared(t,i);if(0===s)return ue.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,ue.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return ue.Distance(e,o)}}ue._ZeroReadOnly=ue.Zero(),Object.defineProperties(ue.prototype,{dimension:{value:[2]},rank:{value:1}});class de{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=ce(this._x);return e=397*e^ce(this._y),e=397*e^ce(this._z),e}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return de.FromArrayToRef(e,t,this),this}toQuaternion(){return pe.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,a=e._z,l=e._w,h=2*(o*r-a*s),c=2*(a*i-n*r),u=2*(n*s-o*i);return t._x=i+l*h+o*u-a*c,t._y=s+l*c+a*h-n*u,t._z=r+l*u+n*c-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){const i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=me.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=de.Dot(n,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const e=-(de.Dot(t,s)+r)/o,a=n.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=K){return e&&re(this._x,e._x,t)&&re(this._y,e._y,t)&&re(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new this.constructor(this._x*e,this._y*t,this._z*i)}divide(e){return new this.constructor(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!re(t,i,e))return!0;const s=Math.abs(this._z);return!re(t,s,e)||!re(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new this.constructor(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if("xyz"===(e=e.toLowerCase()))return this;const t=me.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(me.Matrix[0]),de.TransformCoordinatesToRef(this,me.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,me.Vector3[0]),me.Vector3[0].rotateByQuaternionToRef(e,me.Vector3[0]),t.addToRef(me.Vector3[0],i),i}cross(e){const t=new this.constructor;return de.CrossToRef(this,e,t)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=de.Dot(e,i);return(r-s)/(r-de.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(me.Vector3[1]),r=t.normalizeToRef(me.Vector3[2]);let n=de.Dot(s,r);n=ae(n,-1,1);const o=Math.acos(n),a=me.Vector3[3];return de.CrossToRef(s,r,a),de.Dot(a,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){me.Vector3[0].copyFrom(e);const s=me.Vector3[0];me.Vector3[1].copyFrom(t);const r=me.Vector3[1];me.Vector3[2].copyFrom(i);const n=me.Vector3[2],o=me.Vector3[3],a=me.Vector3[4];return s.normalize(),r.normalize(),n.normalize(),de.CrossToRef(n,s,o),de.CrossToRef(o,n,a),le(Math.atan2(de.Dot(r,o),de.Dot(r,a)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=ge.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=de.Zero();return de.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=ae(i,0,1);const r=me.Vector3[0],n=me.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const a=n.length();n.normalizeFromLength(a);const l=de.Dot(r,n);let h,c;if(l<1-K){const e=Math.acos(l),t=1/Math.sin(e);h=Math.sin((1-i)*e)*t,c=Math.sin(i*e)*t}else h=1-i,c=i;return r.scaleInPlace(h),n.scaleInPlace(c),s.copyFrom(r).addInPlace(n),s.scaleInPlace(oe(o,a,i)),s}static SmoothToRef(e,t,i,s,r){return de.SlerpToRef(e,t,0===s?1:i/s,r),r}static FromArray(e,t=0){return new de(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return de.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return de.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new de(0,0,0)}static One(){return new de(1,1,1)}static Up(){return new de(0,1,0)}static get UpReadOnly(){return de._UpReadOnly}static get DownReadOnly(){return de._DownReadOnly}static get RightReadOnly(){return de._RightReadOnly}static get LeftReadOnly(){return de._LeftReadOnly}static get LeftHandedForwardReadOnly(){return de._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return de._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return de._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return de._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return de._ZeroReadOnly}static get OneReadOnly(){return de._OneReadOnly}static Down(){return new de(0,-1,0)}static Forward(e=!1){return new de(0,0,e?-1:1)}static Backward(e=!1){return new de(0,0,e?1:-1)}static Right(){return new de(1,0,0)}static Left(){return new de(-1,0,0)}static Random(e=0,t=1){return new de(ne(e,t),ne(e,t),ne(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ne(e,t),ne(e,t),ne(e,t))}static TransformCoordinates(e,t){const i=de.Zero();return de.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return de.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*h,r._y=a*h,r._z=l*h,r._isDirty=!0,r}static TransformNormal(e,t){const i=de.Zero();return de.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),h=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new e.constructor(a,l,h)}static Clamp(e,t,i){const s=new e.constructor;return de.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:o,o=o0&&E<0?(P.copyFrom(n),R=t,I=i):E>0&&A<0?(P.copyFrom(a),R=i,I=s):(P.copyFrom(o).scaleInPlace(-1),R=s,I=t);const M=me.Vector3[9],O=me.Vector3[4];if(R.subtractToRef(g,T),I.subtractToRef(g,M),de.CrossToRef(T,M,O),!(de.Dot(O,l)<0))return r.copyFrom(g),Math.abs(p*f);const D=me.Vector3[5];de.CrossToRef(P,O,D),D.normalize();const w=me.Vector3[9];w.copyFrom(R).subtractInPlace(g);const N=w.length();if(Nthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}toVector3(){return new de(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new _e(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return _e.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new _e(0,0,0,0)}static One(){return new _e(1,1,1,1)}static Random(e=0,t=1){return new _e(ne(e,t),ne(e,t),ne(e,t),ne(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ne(e,t),ne(e,t),ne(e,t),ne(e,t))}static Clamp(e,t,i){const s=new e.constructor;return _e.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(ae(e.x,t.x,i.x),ae(e.y,t.y,i.y),ae(e.z,t.z,i.z),ae(e.w,t.w,i.w))}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return _e._ZeroReadOnly}static Normalize(e){const t=_e.Zero();return _e.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(_e.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return _e.CenterToRef(e,t,_e.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}static TransformCoordinates(e,t){const i=_e.Zero();return _e.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return _e.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=a,r.z=l,r.w=h,r}static TransformNormal(e,t){const i=new e.constructor;return _e.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new _e(e._x,e._y,e._z,t)}static Dot(e,t){return e.dot(t)}}_e._ZeroReadOnly=_e.Zero(),Object.defineProperties(_e.prototype,{dimension:{value:[4]},rank:{value:1}});class pe{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=ce(this._x);return e=397*e^ce(this._y),e=397*e^ce(this._z),e=397*e^ce(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return pe.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=K){return e&&re(this._x,e._x,t)&&re(this._y,e._y,t)&&re(this._z,e._z,t)&&re(this._w,e._w,t)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new this.constructor)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new this.constructor)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=de.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=r*r,a=t*t,l=i*i,h=s*s;e._z=Math.atan2(2*(i*s+t*r),-a-l+h+o),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),a-l-h+o),e._isDirty=!0}return e}toRotationMatrix(e){return fe.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return pe.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new pe;return pe.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=s+a+u;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(c-l)*_,t._y=(n-h)*_,t._z=(o-r)*_,t._isDirty=!0):s>a&&s>u?(_=2*Math.sqrt(1+s-a-u),t._w=(c-l)/_,t._x=.25*_,t._y=(r+o)/_,t._z=(n+h)/_,t._isDirty=!0):a>u?(_=2*Math.sqrt(1+a-s-u),t._w=(n-h)/_,t._x=(r+o)/_,t._y=.25*_,t._z=(l+c)/_,t._isDirty=!0):(_=2*Math.sqrt(1+u-s-a),t._w=(o-r)/_,t._x=(n+h)/_,t._y=(l+c)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=pe.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=0===s?1:i/s;return n=ae(n,0,1),pe.SlerpToRef(e,t,n,r),r}static Zero(){return new pe(0,0,0,0)}static Inverse(e){return new e.constructor(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new pe(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return pe.RotationAxisToRef(e,t,new pe)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new pe(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new pe;return pe.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return pe.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new pe;return pe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return pe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=K){const r=de.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(de.CrossToRef(e,t,ge.Vector3[0]),i.set(ge.Vector3[0].x,ge.Vector3[0].y,ge.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new pe;return pe.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=.5*i,n=.5*t,o=.5*e,a=Math.sin(r),l=Math.cos(r),h=Math.sin(n),c=Math.cos(n),u=Math.sin(o),d=Math.cos(o);return s._x=d*h*l+u*c*a,s._y=u*c*l-d*h*a,s._z=d*c*a-u*h*l,s._w=d*c*l+u*h*a,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new pe;return pe.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=.5*(i+e),n=.5*(i-e),o=.5*t;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new pe(0,0,0,0);return pe.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=me.Matrix[0];return fe.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),pe.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new pe;return pe.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=me.Matrix[0];return fe.LookDirectionLHToRef(e,t,s),pe.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new pe;return pe.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=me.Matrix[0];return fe.LookDirectionRHToRef(e,t,s),pe.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=pe.Identity();return pe.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)n=1-i,r=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,r=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e._x*a+i._x*l+t._x*h+s._x*c,d=e._y*a+i._y*l+t._y*h+s._y*c,_=e._z*a+i._z*l+t._z*h+s._z*c,p=e._w*a+i._w*l+t._w*h+s._w*c;return new e.constructor(u,d,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=6*(o-r)*e._x+(3*o-4*r+1)*t._x+6*(-o+r)*i._x+(3*o-2*r)*s._x,n._y=6*(o-r)*e._y+(3*o-4*r+1)*t._y+6*(-o+r)*i._y+(3*o-2*r)*s._y,n._z=6*(o-r)*e._z+(3*o-4*r+1)*t._z+6*(-o+r)*i._z+(3*o-2*r)*s._z,n._w=6*(o-r)*e._w+(3*o-4*r+1)*t._w+6*(-o+r)*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=pe.Zero();return pe.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new e.constructor;return pe.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(ae(e.x,t.x,i.x),ae(e.y,t.y,i.y),ae(e.z,t.z,i.z),ae(e.w,t.w,i.w))}static Random(e=0,t=1){return new pe(ne(e,t),ne(e,t),ne(e,t),ne(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ne(e,t),ne(e,t),ne(e,t),ne(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(pe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return pe.CenterToRef(e,t,pe.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(pe.prototype,{dimension:{value:[4]},rank:{value:1}});class fe{static get Use64Bits(){return ie.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=fe._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,ie.MatrixTrackPrecisionChange&&ie.MatrixTrackedMatrices.push(this),this._m=new ie.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],_=e[12],p=e[13],f=e[14],m=e[15],g=u*m-f*d,v=c*m-p*d,x=c*f-p*u,b=h*m-_*d,T=h*f-u*_,y=h*p-_*c;return t*+(o*g-a*v+l*x)+i*-(n*g-a*b+l*T)+s*+(n*v-o*b+l*y)+r*-(n*x-o*T+a*y)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return fe.FromArrayToRef(e,t,this)}copyFromFloats(...e){return fe.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return fe.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new this.constructor;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let e=0;e<16;e++)s[e]=i[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new this.constructor)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return fe.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],_=t[11],p=t[12],f=t[13],m=t[14],g=t[15],v=d*g-m*_,x=u*g-f*_,b=u*m-f*d,T=c*g-p*_,y=c*m-d*p,S=c*f-p*u,C=+(a*v-l*x+h*b),E=-(o*v-l*T+h*y),A=+(o*x-a*T+h*S),P=-(o*b-a*y+l*S),R=i*C+s*E+r*A+n*P;if(0===R)return e.copyFrom(this),e;const I=1/R,M=l*g-m*h,O=a*g-f*h,D=a*m-f*l,w=o*g-p*h,N=o*m-p*l,F=o*f-p*a,B=l*_-d*h,L=a*_-u*h,k=a*d-u*l,V=o*_-c*h,U=o*d-c*l,G=o*u-c*a,z=-(s*v-r*x+n*b),W=+(i*v-r*T+n*y),H=-(i*x-s*T+n*S),X=+(i*b-s*y+r*S),Y=+(s*M-r*O+n*D),Q=-(i*M-r*w+n*N),j=+(i*O-s*w+n*F),K=-(i*D-s*N+r*F),$=-(s*B-r*L+n*k),q=+(i*B-r*V+n*U),Z=-(i*L-s*V+n*G),J=+(i*k-s*U+r*G);return fe.FromValuesToRef(C*I,z*I,Y*I,$*I,E*I,W*I,Q*I,q*I,A*I,H*I,j*I,Z*I,P*I,X*I,K*I,J*I,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new de(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return fe.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]*r[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],o=s[1],a=s[2],l=s[3],h=s[4],c=s[5],u=s[6],d=s[7],_=s[8],p=s[9],f=s[10],m=s[11],g=s[12],v=s[13],x=s[14],b=s[15],T=r[0],y=r[1],S=r[2],C=r[3],E=r[4],A=r[5],P=r[6],R=r[7],I=r[8],M=r[9],O=r[10],D=r[11],w=r[12],N=r[13],F=r[14],B=r[15];return t[i]=n*T+o*E+a*I+l*w,t[i+1]=n*y+o*A+a*M+l*N,t[i+2]=n*S+o*P+a*O+l*F,t[i+3]=n*C+o*R+a*D+l*B,t[i+4]=h*T+c*E+u*I+d*w,t[i+5]=h*y+c*A+u*M+d*N,t[i+6]=h*S+c*P+u*O+d*F,t[i+7]=h*C+c*R+u*D+d*B,t[i+8]=_*T+p*E+f*I+m*w,t[i+9]=_*y+p*A+f*M+m*N,t[i+10]=_*S+p*P+f*O+m*F,t[i+11]=_*C+p*R+f*D+m*B,t[i+12]=g*T+v*E+x*I+b*w,t[i+13]=g*y+v*A+x*M+b*N,t[i+14]=g*S+v*P+x*O+b*F,t[i+15]=g*C+v*R+x*D+b*B,this}divide(e){return this.divideToRef(e,new this.constructor)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new this.constructor)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let e=0;e<16;e++)if(!re(i[e],s[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new this.constructor)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new this.constructor)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=ce(this._m[0]);for(let t=1;t<16;t++)e=397*e^ce(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new pe,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||me.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const t=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,n=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,s=1/e._y,r=1/e._z;fe.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*s,n[5]*s,n[6]*s,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,me.Matrix[0]),pe.FromRotationMatrixToRef(me.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new _e(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new this.constructor;return fe.TransposeToRef(this,e),e}transposeToRef(e){return fe.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new this.constructor;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=me.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return fe.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=me.Vector3[0];if(!this.decompose(t))return fe.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return fe.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new fe;return fe.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return fe._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f){const m=new fe,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated(),m}static Compose(e,t,i){const s=new fe;return fe.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,a=t._z,l=t._w,h=n+n,c=o+o,u=a+a,d=n*h,_=n*c,p=n*u,f=o*c,m=o*u,g=a*u,v=l*h,x=l*c,b=l*u,T=e._x,y=e._y,S=e._z;return r[0]=(1-(f+g))*T,r[1]=(_+b)*T,r[2]=(p-x)*T,r[3]=0,r[4]=(_-b)*y,r[5]=(1-(d+g))*y,r[6]=(m+v)*y,r[7]=0,r[8]=(p+x)*S,r[9]=(m-v)*S,r[10]=(1-(d+f))*S,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=fe.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return fe.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=fe.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new fe;return fe.RotationXToRef(e,t),t}static Invert(e){const t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return fe.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new fe;return fe.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return fe.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new fe;return fe.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return fe.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new fe;return fe.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=de.Dot(t,e),n=i._m;if(r<-1+K)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const i=de.Cross(t,e),s=1/(1+r);n[0]=i._x*i._x*s+r,n[1]=i._y*i._x*s-i._z,n[2]=i._z*i._x*s+i._y,n[3]=0,n[4]=i._x*i._y*s+i._z,n[5]=i._y*i._y*s+r,n[6]=i._z*i._y*s-i._x,n[7]=0,n[8]=i._x*i._z*s-i._y,n[9]=i._y*i._z*s+i._x,n[10]=i._z*i._z*s+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new fe;return fe.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return pe.RotationYawPitchRollToRef(e,t,i,me.Quaternion[0]),me.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new fe;return fe.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return fe.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new fe;return fe.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return fe.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new e.constructor;return fe.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-i)+o[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new e.constructor;return fe.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=me.Vector3[0],n=me.Quaternion[0],o=me.Vector3[1];e.decompose(r,n,o);const a=me.Vector3[2],l=me.Quaternion[1],h=me.Vector3[3];t.decompose(a,l,h);const c=me.Vector3[4];de.LerpToRef(r,a,i,c);const u=me.Quaternion[2];pe.SlerpToRef(n,l,i,u);const d=me.Vector3[5];return de.LerpToRef(o,h,i,d),fe.ComposeToRef(c,u,d,s),s}static LookAtLH(e,t,i){const s=new fe;return fe.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=me.Vector3[0],n=me.Vector3[1],o=me.Vector3[2];t.subtractToRef(e,o),o.normalize(),de.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),de.CrossToRef(o,r,n),n.normalize();const l=-de.Dot(r,e),h=-de.Dot(n,e),c=-de.Dot(o,e);return fe.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookAtRH(e,t,i){const s=new fe;return fe.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=me.Vector3[0],n=me.Vector3[1],o=me.Vector3[2];e.subtractToRef(t,o),o.normalize(),de.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),de.CrossToRef(o,r,n),n.normalize();const l=-de.Dot(r,e),h=-de.Dot(n,e),c=-de.Dot(o,e);return fe.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookDirectionLH(e,t){const i=new fe;return fe.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=me.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=me.Vector3[1];return de.CrossToRef(t,s,r),fe.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new fe;return fe.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=me.Vector3[2];return de.CrossToRef(t,e,s),fe.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new fe;return fe.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=2/e,a=2/t,l=2/(s-i),h=-(s+i)/(s-i);return fe.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,r),n&&r.multiplyToRef(ve,r),r._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const a=new fe;return fe.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a){const l=2/(t-e),h=2/(s-i),c=2/(n-r),u=-(n+r)/(n-r),d=(e+t)/(e-t),_=(s+i)/(i-s);return fe.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,_,u,1,o),a&&o.multiplyToRef(ve,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=-o*Math.cos(a),d=-o*Math.sin(a);return fe.TranslationToRef(0,0,-l,me.Matrix[1]),fe.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,me.Matrix[0]),me.Matrix[1].multiplyToRef(me.Matrix[0],me.Matrix[0]),fe.TranslationToRef(0,0,l,me.Matrix[1]),me.Matrix[0].multiplyToRef(me.Matrix[1],me.Matrix[0]),fe.OrthoOffCenterLHToRef(e,t,i,s,r,n,h,c),me.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,s,r,n,o){const a=new fe;return fe.OrthoOffCenterRHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,a){return fe.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=o*Math.cos(a),d=o*Math.sin(a);return fe.TranslationToRef(0,0,l,me.Matrix[1]),fe.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,me.Matrix[0]),me.Matrix[1].multiplyToRef(me.Matrix[0],me.Matrix[0]),fe.TranslationToRef(0,0,-l,me.Matrix[1]),me.Matrix[0].multiplyToRef(me.Matrix[1],me.Matrix[0]),fe.OrthoOffCenterRHToRef(e,t,i,s,r,n,h,c),me.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,s,r,n=0){const o=new fe,a=2*i/e,l=2*i/t,h=(s+i)/(s-i),c=-2*s*i/(s-i),u=Math.tan(n);return fe.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),r&&o.multiplyToRef(ve,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const a=new fe;return fe.PerspectiveFovLHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=l&&0===h?-1:0!==c?(c+h)/(c-h):1,f=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return fe.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,1,0,0,f,0,r),o&&r.multiplyToRef(ve,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return fe.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(ve,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const a=new fe;return fe.PerspectiveFovRHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,f=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return fe.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,-1,0,0,f,0,r),o&&r.multiplyToRef(ve,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return fe.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(ve,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,a=e.height,l=e.x,h=e.y,c=fe.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,n-r,0,l+o/2,a/2+h,r,1),u=new t.constructor;return t.multiplyToRef(i,u),u.multiplyToRef(s,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return ie.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return ie.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return fe.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[12],a=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],_=i[10],p=i[14],f=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=s,x[1]=r,x[2]=n,x[3]=o,x[4]=a,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=_,x[11]=p,x[12]=f,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new fe;return fe.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,a=-2*r;return fe.FromValuesToRef(n*i+1,o*i,a*i,0,n*s,o*s+1,a*s,0,n*r,o*r,a*r+1,0,n*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return fe.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}fe._UpdateFlagSeed=0,fe._IdentityReadOnly=fe.Identity(),Object.defineProperties(fe.prototype,{dimension:{value:[4,4]},rank:{value:2}});class me{}me.Vector3=$.BuildTuple(11,de.Zero),me.Matrix=$.BuildTuple(2,fe.Identity),me.Quaternion=$.BuildTuple(3,pe.Zero);class ge{}ge.Vector2=$.BuildTuple(3,ue.Zero),ge.Vector3=$.BuildTuple(13,de.Zero),ge.Vector4=$.BuildTuple(3,_e.Zero),ge.Quaternion=$.BuildTuple(2,pe.Zero),ge.Matrix=$.BuildTuple(8,fe.Identity),ee("BABYLON.Vector2",ue),ee("BABYLON.Vector3",de),ee("BABYLON.Vector4",_e),ee("BABYLON.Matrix",fe);const ve=fe.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class xe{static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=xe.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=xe.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=xe.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+xe.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=xe.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*ae(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?ae((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n;return e*(2*o-3*n+1)+i*(-2*o+3*n)+t*(o-2*n+r)+s*(o-n)}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:xe.HCF(t,i)}}function be(e){return Math.pow(e,Q)}function Te(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function ye(e){return Math.pow(e,Y)}function Se(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}xe.TwoPi=2*Math.PI,xe.WithinEpsilon=re,xe.ToHex=he,xe.Clamp=ae,xe.Lerp=oe,xe.RandomRange=ne,xe.NormalizeRadians=le;class Ce{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Ce.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ee(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new this.constructor(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new this.constructor(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=K){return xe.WithinEpsilon(this.r,e.r,t)&&xe.WithinEpsilon(this.g,e.g,t)&&xe.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new this.constructor(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=ae(this.r,e,t),i.g=ae(this.g,e,t),i.b=ae(this.b,e,t),i}add(e){return new this.constructor(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new this.constructor(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new this.constructor(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this.r-e,this.g-t,this.b-i)}clone(){return new this.constructor(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+he(e)+he(t)+he(i)}toHSV(){const e=new this.constructor;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,a=0;const l=r,h=r-n;0!==r&&(a=h/r),r!=n&&(r==t?(o=(i-s)/h,i=0&&n<=1?(a=r,l=o):n>=1&&n<=2?(a=o,l=r):n>=2&&n<=3?(l=r,h=o):n>=3&&n<=4?(l=o,h=r):n>=4&&n<=5?(a=o,h=r):n>=5&&n<=6&&(a=r,h=o);const c=i-r;s.set(a+c,l+c,h+c)}static FromHSV(e,t,i){const s=new Ce(0,0,0);return Ce.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new Ce(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return Ce.FromInts(t,i,s)}static FromArray(e,t=0){return new Ce(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Ce(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Ce(0,0,0);return Ce.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,_=e.b*a+i.b*l+t.b*h+s.b*c;return new Ce(u,d,_)}static Hermite1stDerivative(e,t,i,s,r){const n=Ce.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b}static Red(){return new Ce(1,0,0)}static Green(){return new Ce(0,1,0)}static Blue(){return new Ce(0,0,1)}static Black(){return new Ce(0,0,0)}static get BlackReadOnly(){return Ce._BlackReadOnly}static White(){return new Ce(1,1,1)}static Purple(){return new Ce(.5,0,.5)}static Magenta(){return new Ce(1,0,1)}static Yellow(){return new Ce(1,1,0)}static Gray(){return new Ce(.5,.5,.5)}static Teal(){return new Ce(0,1,1)}static Random(){return new Ce(Math.random(),Math.random(),Math.random())}}Ce._BlackReadOnly=Ce.Black(),Object.defineProperties(Ce.prototype,{dimension:{value:[3]},rank:{value:1}});class Ee{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new this.constructor(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new this.constructor(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new this.constructor(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new this.constructor(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=ae(this.r,e,t),i.g=ae(this.g,e,t),i.b=ae(this.b,e,t),i.a=ae(this.a,e,t),i}multiply(e){return new this.constructor(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new this.constructor(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=K){return xe.WithinEpsilon(this.r,e.r,t)&&xe.WithinEpsilon(this.g,e.g,t)&&xe.WithinEpsilon(this.b,e.b,t)&&xe.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new this.constructor).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+he(t)+he(i)+he(s);const r=Math.round(255*this.a);return"#"+he(t)+he(i)+he(s)+he(r)}toLinearSpace(e=!1){const t=new Ee;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Te(this.r),e.g=Te(this.g),e.b=Te(this.b)):(e.r=be(this.r),e.g=be(this.g),e.b=be(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ee;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=Se(this.r),e.g=Se(this.g),e.b=Se(this.b)):(e.r=ye(this.r),e.g=ye(this.g),e.b=ye(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new Ee(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return Ee.FromInts(t,i,s,r)}static Lerp(e,t,i){const s=new Ee(0,0,0,0);return Ee.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,_=e.b*a+i.b*l+t.b*h+s.b*c,p=e.a*a+i.a*l+t.a*h+s.a*c;return new Ee(u,d,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new Ee;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b,n.a=6*(o-r)*e.a+(3*o-4*r+1)*t.a+6*(-o+r)*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new Ee(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ee(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new Ee(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew Ee(0,0,0,0))),ee("BABYLON.Color3",Ce),ee("BABYLON.Color4",Ee);class Pe{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new X,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}Pe._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof ue?e.x+", "+e.y:e instanceof de?e.x+", "+e.y+", "+e.z:e instanceof Ce?e.r+", "+e.g+", "+e.b:e instanceof Ee?e.r+", "+e.g+", "+e.b+", "+e.a:e,Pe._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),ee("BABYLON.Action",Pe);class Re{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new Re(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Re(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Re(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Re(e,t.x,t.y,null,i,s)}}class Ie{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class Me extends Ie{static get IsEqual(){return Me._IsEqual}static get IsDifferent(){return Me._IsDifferent}static get IsGreater(){return Me._IsGreater}static get IsLesser(){return Me._IsLesser}constructor(e,t,i,s,r=Me.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case Me.IsGreater:return this._effectiveTarget[this._property]>this.value;case Me.IsLesser:return this._effectiveTarget[this._property]e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(void 0!==i&&!we._CheckLimit(s,i))return;const r=we._FormatMessage(s),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const a=`
${r}

`;we._AddLogEntry(a),we._GenerateLimitMessage(s,e)}static get LogCache(){return we._LogCache}static ClearLogCache(){we._LogCache="",we._LogLimitOutputs={},we.errorsCount=0}static set LogLevels(e){we.Log=we._LogDisabled,we.Warn=we._LogDisabled,we.Error=we._LogDisabled,[we.MessageLogLevel,we.WarningLogLevel,we.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];we[e.name]=we._LogEnabled.bind(we,t)}}))}}we.NoneLogLevel=0,we.MessageLogLevel=1,we.WarningLogLevel=2,we.ErrorLogLevel=4,we.AllLogLevel=7,we.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",we._LogCache="",we._LogLimitOutputs={},we._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],we.errorsCount=0,we.Log=we._LogEnabled.bind(we,we.MessageLogLevel),we.Warn=we._LogEnabled.bind(we,we.WarningLogLevel),we.Error=we._LogEnabled.bind(we,we.ErrorLogLevel);class Ne extends Pe{constructor(e,t,i,s){super(e,s),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Pe._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class Fe extends Pe{constructor(e,t,i,s){super(e,s),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Pe._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class Be extends Pe{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Pe._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Pe._SerializeValueAsString(this.value)}]},e)}}class Le extends Pe{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&we.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Pe._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Pe._SerializeValueAsString(this.value)}]},e)}}class ke extends Pe{constructor(e,t,i,s,r,n){super(e,n),this.from=i,this.to=s,this.loop=r,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Pe._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Pe._SerializeValueAsString(this.loop)||!1}]},e)}}class Ve extends Pe{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Pe._GetTargetProperty(this._target)]},e)}}class Ue extends Pe{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class Ge extends Pe{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;ee?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class Xe{static DeepCopy(e,t,i,s,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const o of n){if("_"===o[0]&&(!s||-1===s.indexOf(o)))continue;if(o.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(o))continue;const n=e[o],a=typeof n;if("function"!==a)try{if("object"===a)if(n instanceof Uint8Array)t[o]=Uint8Array.from(n);else if(n instanceof Array){if(t[o]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter((e=>e.actionManager===this));for(const e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=Ye.OnPickTrigger&&t.trigger<=Ye.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=Ye.OnPickTrigger&&t.trigger<=Ye.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===Ye.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(we.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,Ye.Triggers[e.trigger]?Ye.Triggers[e.trigger]++:Ye.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),Ye.Triggers[e.trigger]-=1,0===Ye.Triggers[e.trigger]&&delete Ye.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===s){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const r=s.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;const h=[];let c=null,u=null;const d=e.combine&&e.combine.length>0;if(2===e.type?h.push(s):h.push(t),d){const t=[];for(let i=0;i{const i=te("BABYLON."+e);return i&&new i(...t)})(e.name,h);if(_ instanceof Ie&&null!==o){const e=new Ue(t,o);a?a.then(e):s.registerAction(e),a=e}null===l?_ instanceof Ie?(o=_,_=a):(o=null,a?a.then(_):s.registerAction(_)):l.push(_);for(let i=0;i0){const e=r.properties[0].value,t=null===r.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),s={trigger:Ye[r.name],parameter:t}}else s=Ye[r.name];for(let e=0;e=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}Object.create,Object.create;const Ze={},Je={};function et(e){const t=e.getClassName();if(Ze[t])return Ze[t];Ze[t]={};const i=Ze[t];let s=e,r=t;for(;r;){const e=Je[r];for(const t in e)i[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==r)break;s=t}while(t);if(n)break;r=t.getClassName(),s=t}return i}function tt(e,t){return(i,s)=>{const r=function(e){const t=e.getClassName();return Je[t]||(Je[t]={}),Je[t]}(i);r[s]||(r[s]={type:e,sourceName:t})}}function it(e,t=null){return function(e,t=null){return(i,s)=>{const r=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function st(e){return tt(0,e)}function rt(e){return tt(1,e)}function nt(e){return tt(2,e)}function ot(e){return tt(3,e)}function at(e){return tt(4,e)}function lt(e){return tt(5,e)}function ht(e){return tt(6,e)}function ct(e){return tt(7,e)}function ut(e){return tt(8,e)}function dt(e){return tt(9,e)}function _t(e){return tt(10,e)}function pt(e){return tt(12,e)}function ft(e){return tt(11,e)}function mt(e,t,i,s){const r=i.value;i.value=(...i)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=s?(...t)=>s(...t)?e(...t):r(...t):e}return e[t]=n,n(...i)}}mt.filter=function(e){return(t,i,s)=>mt(t,i,s,e)};const gt={};function vt(e,t=!1){if(!t||!gt[e])return gt[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class xt{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),xt._HandleParenthesisContent(e,t)))):xt._HandleParenthesisContent(e,t))||"false"!==e&&xt.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=xt._SimplifyNegation(s[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class bt{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>bt.HasTags(e),e.addTags=t=>bt.AddTagsTo(e,t),e.removeTags=t=>bt.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>bt.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){bt._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(bt.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!bt.HasTags(e))return;const i=t.split(" ");for(const t in i)bt._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?bt.HasTags(e):xt.Eval(t,(t=>bt.HasTags(e)&&e._tags[t])))}}const Tt=function(e,t,i,s={}){const r=e();bt&&bt.HasTags(t)&&bt.AddTagsTo(r,bt.GetTags(t,!0));const n=et(r),o={};for(const e in n){const a=n[e],l=t[e],h=a.type;if(null!=l&&("uniqueId"!==e||yt.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?r[e]=o[l.uniqueId]:(r[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?l:l.clone()}}return r};class yt{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw vt("ImageProcessingConfiguration")},yt._FresnelParametersParser=e=>{throw vt("FresnelParameters")},yt._ColorCurvesParser=e=>{throw vt("ColorCurves")},yt._TextureParser=(e,t,i)=>{throw vt("Texture")};class St{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new X,this._onClonedObservable=new X}}class Ct{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null){this._isDirty=!1,this._nodeDataStorage=new St,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new X,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=fe.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new X,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||se.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew Ct(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw vt("AnimationRange")},Ct._NodeConstructors={},qe([st()],Ct.prototype,"name",void 0),qe([st()],Ct.prototype,"id",void 0),qe([st()],Ct.prototype,"uniqueId",void 0),qe([st()],Ct.prototype,"state",void 0),qe([st()],Ct.prototype,"metadata",void 0);class Et{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new Et(this.width*e,this.height*t)}clone(){return new Et(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new Et(0,0)}add(e){return new Et(this.width+e.width,this.height+e.height)}subtract(e){return new Et(this.width-e.width,this.height-e.height)}scale(e){return new Et(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new Et(s,r)}}class At{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(At.CustomRequestHeaders).length>0||At.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in At.CustomRequestHeaders){const t=At.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return At.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){At.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of At.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}At.CustomRequestHeaders={},At.CustomRequestModifiers=new Array,At.SkipRequestModificationForBabylonCDN=!0;const Pt=Object.freeze(new pe(0,0,0,0)),Rt=Object.freeze(de.Zero()),It=Object.freeze(ue.Zero()),Mt=Object.freeze(Et.Zero()),Ot=Object.freeze(Ce.Black()),Dt=Object.freeze(new Ee(0,0,0,0)),wt={key:0,repeatCount:0,loopMode:2};class Nt{static _PrepareAnimation(e,t,i,s,r,n,o,a){let l;if(!isNaN(parseFloat(r))&&isFinite(r)?l=Nt.ANIMATIONTYPE_FLOAT:r instanceof pe?l=Nt.ANIMATIONTYPE_QUATERNION:r instanceof de?l=Nt.ANIMATIONTYPE_VECTOR3:r instanceof ue?l=Nt.ANIMATIONTYPE_VECTOR2:r instanceof Ce?l=Nt.ANIMATIONTYPE_COLOR3:r instanceof Ee?l=Nt.ANIMATIONTYPE_COLOR4:r instanceof Et&&(l=Nt.ANIMATIONTYPE_SIZE),null==l)return null;const h=new Nt(e,t,i,l,o),c=[{frame:0,value:r},{frame:s,value:n}];return h.setKeys(c),void 0!==a&&h.setEasingFunction(a),h}static CreateAnimation(e,t,i,s){const r=new Nt(e+"Animation",e,i,t,Nt.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Nt._PrepareAnimation(e,i,s,r,n,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Nt._PrepareAnimation(e,s,r,n,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,n,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,a,l,h){const c=Nt._PrepareAnimation(e,i,s,r,n,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let o=e;if(n.cloneOriginalAnimation&&(o=e.clone(),o.name=n.clonedAnimationName||o.name),!o._keys.length)return o;const a=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let l=0;const h=o._keys[0];let c=o._keys.length-1;const u=o._keys[c],d={referenceValue:h.value,referencePosition:ge.Vector3[0],referenceQuaternion:ge.Quaternion[0],referenceScaling:ge.Vector3[1],keyPosition:ge.Vector3[2],keyQuaternion:ge.Quaternion[1],keyScaling:ge.Vector3[3]};let _=h.frame,p=u.frame;if(n.range){const e=o.getRange(n.range);e&&(_=e.from,p=e.to)}else _=n.fromFrame??_,p=n.toFrame??p;if(_!==h.frame&&(l=o.createKeyForFrame(_)),p!==u.frame&&(c=o.createKeyForFrame(p)),1===o._keys.length){const e=o._getKeyValue(o._keys[0]);d.referenceValue=e.clone?e.clone():e}else if(a<=h.frame){const e=o._getKeyValue(h.value);d.referenceValue=e.clone?e.clone():e}else if(a>=u.frame){const e=o._getKeyValue(u.value);d.referenceValue=e.clone?e.clone():e}else{wt.key=0;const e=o._interpolate(a,wt);d.referenceValue=e.clone?e.clone():e}o.dataType===Nt.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():o.dataType===Nt.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let f=Number.MAX_VALUE;const m=n.clipKeys?[]:null;for(let e=l;e<=c;e++){let t=o._keys[e];if(m&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},f===Number.MAX_VALUE&&(f=t.frame),t.frame-=f,m.push(t)),!e||o.dataType===Nt.ANIMATIONTYPE_FLOAT||t.value!==h.value)switch(o.dataType){case Nt.ANIMATIONTYPE_MATRIX:t.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),fe.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,t.value);break;case Nt.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(t.value,t.value);break;case Nt.ANIMATIONTYPE_VECTOR2:case Nt.ANIMATIONTYPE_VECTOR3:case Nt.ANIMATIONTYPE_COLOR3:case Nt.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(d.referenceValue,t.value);break;case Nt.ANIMATIONTYPE_SIZE:t.value.width-=d.referenceValue.width,t.value.height-=d.referenceValue.height;break;default:t.value-=d.referenceValue}}return m&&o.setKeys(m,!0),o}static TransitionTo(e,t,i,s,r,n,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=s.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===r?Nt.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Nt._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],a=s[n+1];if(i&&(e===o.frame||e===a.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(a.value);if(o.interpolation===Ke.STEP)return a.frame>e?l:h;const c=void 0!==o.outTangent&&void 0!==a.inTangent,u=a.frame-o.frame;let d=(e-o.frame)/u;const _=o.easingFunction||this.getEasingFunction();switch(null!==_&&(d=_.ease(d)),this.dataType){case Nt.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,o.outTangent*u,h,a.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case Nt.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||Pt).scale(t.repeatCount))}return e}case Nt.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Rt).scale(t.repeatCount))}break}case Nt.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||It).scale(t.repeatCount))}break}case Nt.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,d).add((t.offsetValue||Mt).scale(t.repeatCount))}break;case Nt.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ot).scale(t.repeatCount))}break}case Nt.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Dt).scale(t.repeatCount))}break}case Nt.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return Nt.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,d,t.workValue):l;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return Nt.AllowMatrixDecomposeForInterpolation?s?(fe.DecomposeLerpToRef(e,t,i,s),s):fe.DecomposeLerp(e,t,i):s?(fe.LerpToRef(e,t,i,s),s):fe.Lerp(e,t,i)}clone(){const e=new Nt(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){wt.key=0;const t=this._interpolate(e,wt,!0);if(!t)return this._keys[wt.key].frame===e?wt.key:wt.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(wt.key+1,0,i),wt.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(o=t.values[1]),t.values.length>=3&&(a=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Nt.ANIMATIONTYPE_QUATERNION:if(r=pe.FromArray(t.values),t.values.length>=8){const e=pe.FromArray(t.values.slice(4,8));e.equals(pe.Zero())||(o=e)}if(t.values.length>=12){const e=pe.FromArray(t.values.slice(8,12));e.equals(pe.Zero())||(a=e)}t.values.length>=13&&(l=t.values[12]);break;case Nt.ANIMATIONTYPE_MATRIX:r=fe.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Nt.ANIMATIONTYPE_COLOR3:r=Ce.FromArray(t.values),t.values[3]&&(o=Ce.FromArray(t.values[3])),t.values[4]&&(a=Ce.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Nt.ANIMATIONTYPE_COLOR4:r=Ee.FromArray(t.values),t.values[4]&&(o=Ee.FromArray(t.values[4])),t.values[5]&&(a=Ee.FromArray(t.values[5])),t.values[6]&&(l=Ee.FromArray(t.values[6]));break;case Nt.ANIMATIONTYPE_VECTOR3:default:r=de.FromArray(t.values),t.values[3]&&(o=de.FromArray(t.values[3])),t.values[4]&&(a=de.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=r,null!=o&&(h.inTangent=o),null!=a&&(h.outTangent=a),null!=l&&(h.interpolation=l),s.push(h)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new At;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new At;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),r=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const s=JSON.parse(i.animation),r=this.Parse(s);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}Nt._UniqueIdGenerator=0,Nt.AllowMatricesInterpolation=!1,Nt.AllowMatrixDecomposeForInterpolation=!0,Nt.SnippetUrl="https://snippet.babylonjs.com",Nt.ANIMATIONTYPE_FLOAT=0,Nt.ANIMATIONTYPE_VECTOR3=1,Nt.ANIMATIONTYPE_QUATERNION=2,Nt.ANIMATIONTYPE_MATRIX=3,Nt.ANIMATIONTYPE_COLOR3=4,Nt.ANIMATIONTYPE_COLOR4=7,Nt.ANIMATIONTYPE_VECTOR2=5,Nt.ANIMATIONTYPE_SIZE=6,Nt.ANIMATIONLOOPMODE_RELATIVE=0,Nt.ANIMATIONLOOPMODE_CYCLE=1,Nt.ANIMATIONLOOPMODE_CONSTANT=2,Nt.ANIMATIONLOOPMODE_YOYO=4,Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,Nt.CreateFromSnippetAsync=Nt.ParseFromSnippetAsync,ee("BABYLON.Animation",Nt),Ct._AnimationRangeFactory=(e,t,i)=>new $e(e,t,i);class Ft extends Pe{constructor(e,t,i,s,r=1e3,n,o,a){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new X,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=o,this.onInterpolationDone=a,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if("number"==typeof this.value)i=Nt.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Ce)i=Nt.ANIMATIONTYPE_COLOR3;else if(this.value instanceof de)i=Nt.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof fe)i=Nt.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof pe))return void we.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=Nt.ANIMATIONTYPE_QUATERNION}const s=new Nt("InterpolateValueAction",this._property,1e3/this.duration*100,i,Nt.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget),e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Pe._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Pe._SerializeValueAsString(this.value)},{name:"duration",value:Pe._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Pe._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}ee("BABYLON.InterpolateValueAction",Ft);class Bt{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,s){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Nt.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=fe.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let s=e;for(let e=0;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,u,d=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,_=0;if(s&&this._animationState.loopMode===Nt.ANIMATIONLOOPMODE_YOYO){const e=(d-t)/h;d=Math.abs(Math.sin(e*Math.PI))*h+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!s&&i>=t&&(d>=h&&r>0||d<=0&&r<0))l=!1,_=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&(d<=h&&r<0||d>=0&&r>0))l=!1,_=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Nt.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Nt.ANIMATIONLOOPMODE_CYCLE;const s=o._interpolate(t,this._animationState),r=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case Nt.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-s;break;case Nt.ANIMATIONTYPE_QUATERNION:case Nt.ANIMATIONTYPE_VECTOR3:case Nt.ANIMATIONTYPE_VECTOR2:case Nt.ANIMATIONTYPE_SIZE:case Nt.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(s)}this._highLimitsCache[e]=r}_=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case Nt.ANIMATIONTYPE_FLOAT:c=0;break;case Nt.ANIMATIONTYPE_QUATERNION:c=Pt;break;case Nt.ANIMATIONTYPE_VECTOR3:c=Rt;break;case Nt.ANIMATIONTYPE_VECTOR2:c=It;break;case Nt.ANIMATIONTYPE_SIZE:c=Mt;break;case Nt.ANIMATIONTYPE_COLOR3:c=Ot;break;case Nt.ANIMATIONTYPE_COLOR4:c=Dt}if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;u=t+h*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else u=d>0&&t>i||d<0&&t0&&this.currentFrame>u||r<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=u,this._animationState.repeatCount=0===h?0:d/h|0,this._animationState.highLimitValue=_,this._animationState.offsetValue=c;const f=o._interpolate(u,this._animationState);if(this.setValue(f,n),p.length)for(let e=0;e=0&&u>=p[e].frame&&p[e].frame>=t||h<0&&u<=p[e].frame&&p[e].frame<=t){const t=p[e];t.isDone||(t.onlyOnce&&(p.splice(e,1),e--),t.isDone=!0,t.action(u))}return l||(this._stopped=!0),l}}function Lt(){return"undefined"!=typeof window}function kt(){return"undefined"!=typeof navigator}function Vt(){return"undefined"!=typeof document}function Ut(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}const Gt={IsWindowObjectExist:Lt,IsNavigatorAvailable:kt,IsDocumentAvailable:Vt,GetDOMTextContent:Ut};class zt{static get Now(){return Lt()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class Wt{}Wt.FilesToLoad={};class Ht{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>0!==s.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}class Xt extends Error{}Xt._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const Yt={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Qt extends Xt{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Xt._setPrototypeOf(this,Qt.prototype)}}const jt=(e,t)=>e.endsWith(t),Kt=(e,t)=>!!e&&e.startsWith(t),$t=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,r,n,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|s>>4,a=(15&s)<<2|r>>6,l=63&r,isNaN(s)?a=l=64:isNaN(r)&&(l=64),h+=t.charAt(n)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},Zt=e=>atob(e),Jt=e=>{const t=Zt(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;e{let i=String(e);for(;i.length{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class si{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{h=h.trim(),""!==h&&(i.push(h),h="")},n=e=>{soi._Stack[s],a=()=>-1===s?"!!INVALID EXPRESSION!!":oi._Stack[s--];let l=0,h="";for(;l1){for(r();-1!==s&&oi._OperatorPriority[o()]>=oi._OperatorPriority[c];)i.push(a());n(c),l++}else h+=t;l++}for(r();-1!==s;)"("===o()?a():i.push(a());return oi._InfixToPostfixCache.size>=oi.InfixToPostfixCacheLimitSize&&oi.ClearCache(),oi._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(oi._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r}return i}}var ui;!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(ui||(ui={}));const di=/defined\s*?\((.+?)\)/g,_i=/defined\s*?\[(.+?)\]/g,pi=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,fi=/__decl__/,mi=/light\{X\}.(\w*)/g,gi=/\{X\}/g,vi=[];class xi{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=this._ProcessShaderConversion(e,t,s);i(r,e)}))}static PreProcess(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=this._ApplyPreProcessing(e,t,s);i(r,e)}))}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new ai(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=e.indexOf(s),r>-1)break;if(-1===r)return new ai(e);const n=e.substring(0,r).trim(),o=e.substring(r+s.length).trim();return new ci(n,s,o)}static _BuildSubExpression(e){e=e.replace(di,"defined[$1]");const t=oi.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const r="&&"==e?new hi:new li;"string"==typeof t&&(t=t.replace(_i,"defined($1)")),"string"==typeof s&&(s=s.replace(_i,"defined($1)")),r.leftOperand="string"==typeof s?this._ExtractOperation(s):s,r.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(r)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(_i,"defined($1)")),"string"==typeof s?this._ExtractOperation(s):s}static _BuildExpression(e,t){const i=new ni,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===s?new ai(r):"#ifndef"===s?new ai(r,!0):this._BuildSubExpression(r),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if("#else"===r){const i=new ii;return t.children.push(i),void this._MoveCursor(e,i)}if("#elif"===r){const e=this._BuildExpression(s,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=xi._MoveCursorRegex.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new ri;t.children.push(s);const r=this._BuildExpression(i,6);s.children.push(r),this._MoveCursorWithinIf(e,s,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new ri;t.children.push(s);const r=this._BuildExpression(i,7);s.children.push(r),this._MoveCursorWithinIf(e,s,r);break}case"#if":{const s=new ri,r=this._BuildExpression(i,3);t.children.push(s),s.children.push(r),this._MoveCursorWithinIf(e,s,r);break}}continue}}const s=new ii;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){const s=new ii,r=new si;return r.lineIndex=-1,r.lines=e.split("\n"),this._MoveCursor(r,s),s.process(t,i)}static _PreparePreProcessors(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return e.processor?.shaderLanguage===ui.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let s=this._ProcessPrecision(e,t);if(!t.processor)return s;if(t.processor.shaderLanguage===ui.GLSL&&-1!==s.indexOf("#version 3")&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const r=t.defines,n=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,r,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,n,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ApplyPreProcessing(e,t,i){let s=e;const r=t.defines,n=this._PreparePreProcessors(t,i);return t.processor?.preProcessor&&(s=t.processor.preProcessor(s,r,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,n,t),t.processor?.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ProcessIncludes(e,t,i){let s;for(vi.length=0;null!==(s=pi.exec(e));)vi.push(s);let r=String(e),n=[e],o=!1;for(const e of vi){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(fi,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void xi._FileToolsLoadFile(e,(e=>{t.includesShadersStore[s]=e,this._ProcessIncludes(n.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=o.replace(gi,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(mi,((e,t)=>t+"{X}"))),i=i.replace(gi,s)}const r=[];for(const t of n){const s=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}vi.length=0,r=n.join(""),o?this._ProcessIncludes(r.toString(),t,i):i(r)}static _FileToolsLoadFile(e,t,i,s,r,n){throw vt("FileTools")}}xi._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;class bi{static GetShadersRepository(e=ui.GLSL){return e===ui.GLSL?bi.ShadersRepository:bi.ShadersRepositoryWGSL}static GetShadersStore(e=ui.GLSL){return e===ui.GLSL?bi.ShadersStore:bi.ShadersStoreWGSL}static GetIncludesShadersStore(e=ui.GLSL){return e===ui.GLSL?bi.IncludesShadersStore:bi.IncludesShadersStoreWGSL}}bi.ShadersRepository="src/Shaders/",bi.ShadersStore={},bi.IncludesShadersStore={},bi.ShadersRepositoryWGSL="src/ShadersWGSL/",bi.ShadersStoreWGSL={},bi.IncludesShadersStoreWGSL={};class Ti{static get ShadersRepository(){return bi.ShadersRepository}static set ShadersRepository(e){bi.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new X),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,o=null,a=null,l=null,h,c="",u=ui.GLSL){if(this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new X,this.onErrorObservable=new X,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c,t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??ui.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(a[0]&&a[1]){o.isFragment=!0;const[e,i]=a;xi.Process(i,o,((i,s)=>{this._fragmentSourceCodeBeforeMigration=s,this._processFinalCode&&(i=this._processFinalCode("fragment",i));const n=xi.Finalize(e,i,o);o=null,this._useFinalCode(n.vertexCode,n.fragmentCode,r,t)}),this._engine)}};this._loadShader(i,"Vertex","",(e=>{xi.Initialize(o),xi.Process(e,o,((t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,this._processFinalCode&&(t=this._processFinalCode("vertex",t)),a[0]=t,l()}),this._engine)})),this._loadShader(s,"Fragment","Pixel",(e=>{this._rawFragmentSourceCode=e,a[1]=e,l()}))}_useFinalCode(e,t,i,s=!1){if(i){const s=i.vertexElement||i.vertex||i.spectorName||i,r=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===ui.WGSL?"//":"")+"#define SHADER_NAME vertex:"+s+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===ui.WGSL?"//":"")+"#define SHADER_NAME fragment:"+r+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(s)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Ut(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));const r=bi.GetShadersStore(this._shaderLanguage);if(r[e+t+"Shader"])return void s(r[e+t+"Shader"]);if(i&&r[e+i+"Shader"])return void s(r[e+i+"Shader"]);let n;n="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:bi.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",s)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,s);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?r._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,n,null,this._transformFeedbackVaryings,this._key):r._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,n,i,this._transformFeedbackVaryings,this._key),r._executeWhenRenderingStateIsCompiled(this._pipelineContext,(()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,t,this._attributes),t)for(let e=0;e=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(we.Error("Unable to compile effect:"),we.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),we.Error("Attributes: "+i.map((function(e){return" "+e}))),we.Error("Defines:\n"+this.defines),Ti.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(we.Error("Vertex code:"),we.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(we.Error("Fragment code:"),we.Error(i))),e&&we.Error(e),t&&we.Error(t)}we.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,we.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case Ai.Temp:break;case Ai.Url:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case Ai.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case Ai.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case Ai.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case Ai.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case Ai.Cube:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case Ai.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case Ai.CubeRawRGBD:return;case Ai.CubePrefiltered:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial);case Ai.DepthStencil:case Ai.Depth:}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}Pi._Counter=0;class Ri{constructor(){this.shaderLanguage=ui.GLSL}postProcessor(e,t,i,s,r){if(!r.getCaps().drawBuffersExtension){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const Ii=/(flat\s)?\s*varying\s*.*/;class Mi{constructor(){this.shaderLanguage=ui.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Ii.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Oi{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=Oi._Counter++}}Oi._Counter=0;class Di extends Oi{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class wi{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}class Ni{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Fi{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}class Bi{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class Li{}class ki{static get NpmPackage(){return"babylonjs@7.2.1"}static get Version(){return"7.2.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return Ti.ShadersRepository}static set ShadersRepository(e){Ti.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?518:515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return ki._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,s){this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new X,this._frameId=0,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new X,this.onContextRestoredObservable=new X,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new yi,this._stencilStateComposer=new Bi,this._stencilState=new Si,this._alphaState=new Ci,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=new Array,this._renderTargetWrapperCache=new Array,this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._currentRenderTarget=null,this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._boundRenderFunction=()=>this._renderLoop(),this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._frameHandler=0,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=new Array,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new X,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=zt.Now;let r=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=s??!1,this._stencilStateComposer.stencilGlobal=this._stencilState,ie.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=t??i.antialias,i.deterministicLockstep=i.deterministicLockstep??!1,i.lockstepMaxSteps=i.lockstepMaxSteps??4,i.timeStep=i.timeStep??1/60,i.audioEngine=i.audioEngine??!0,i.stencil=i.stencil??!0,this._audioContext=i.audioEngineOptions?.audioContext??null,this._audioDestination=i.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=i.premultipliedAlpha??!0,this.useExactSrgbConversions=i.useExactSrgbConversions??!1,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,s=s||i.adaptToDeviceRatio||!1;const n=Lt()&&window.devicePixelRatio||1,o=i.limitDeviceRatio||n;if(this._hardwareScalingLevel=s?1/Math.min(o,n):1,this._lastDevicePixelRatio=n,!e)return;if(e.getContext){if(r=e,this._renderingCanvas=r,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of ki.ExceptionList){const s=t.key,r=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=s)continue}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,we.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new Mi:new Ri,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const a=`Babylon.js v${ki.Version}`;we.Log(a+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",a)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&Vt()&&"ontouchend"in document},this._checkForMobile(),Lt()&&window.addEventListener("resize",this._checkForMobile))}_clearEmptyResources(){this._dummyFramebuffer=null,this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){we.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,this._flagContextRestored()}),0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}Ti.ResetCache()}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}_rebuildTextures(){}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,Lt()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==s&&(a.type=s,l=!0),a.normalized!==r&&(a.normalized=r,l=!0),a.stride!==n&&(a.stride=n,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=s,a.normalized=r,a.stride=n,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const t=s[r];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let o=0;o=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,s,n)),n+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",a=this._compileShader(t,"vertex",s,o),l=this._compileShader(i,"fragment",s,o);return this._createShaderProgram(e,a,l,r,n)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new wi;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");return s.attachShader(n,t),s.attachShader(n,i),s.linkProgram(n),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,s=e.fragmentShader,r=e.program;if(!t.getProgramParameter(r,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){const t=this._gl.getShaderInfoLog(i);if(t)throw e.vertexCompilationError=t,new Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(s,this._gl.COMPILE_STATUS)){const t=this._gl.getShaderInfoLog(s);if(t)throw e.fragmentCompilationError=t,new Error("FRAGMENT SHADER "+t)}const n=t.getProgramInfoLog(r);if(n)throw e.programLinkError=n,new Error(n)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS))){const i=t.getProgramInfoLog(r);if(i)throw e.programValidationError=i,new Error(i)}t.deleteShader(i),t.deleteShader(s),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,s,r,n,o,a,l,h){const c=e;c.program=s?this.createRawShaderProgram(c,t,i,void 0,l):this.createShaderProgram(c,t,i,a,void 0,l),c.program.__SPECTOR_rebuildProgram=o}_isRenderingStateCompiled(e){const t=e;return!(this._isDisposed||t._isDisposed||!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)||(this._finalizePipelineContext(t),0))}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!i.isParallelCompiled)return void t();const s=i.onCompiled;i.onCompiled=s?()=>{s(),t()}:t}getUniforms(e,t){const i=new Array,s=e;for(let e=0;e1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,we.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,d=new Pi(this,s),_=e.width||e,p=e.height||e,f=e.depth||0,m=e.layers||0,g=this._getSamplingParameters(a,n),v=0!==m?u.TEXTURE_2D_ARRAY:0!==f?u.TEXTURE_3D:u.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(o,l,h),b=this._getInternalFormat(l),T=this._getWebGLTextureType(o);return this._bindTextureDirectly(v,d),0!==m?(d.is2DArray=!0,u.texImage3D(v,0,x,_,p,m,0,b,T,null)):0!==f?(d.is3D=!0,u.texImage3D(v,0,x,_,p,f,0,b,T,null)):u.texImage2D(v,0,x,_,p,0,b,T,null),u.texParameteri(v,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(v,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(v,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(v,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),d._useSRGBBuffer=h,d.baseWidth=_,d.baseHeight=p,d.width=_,d.height=p,d.depth=m,d.isReady=!0,d.samples=c,d.generateMipMaps=n,d.samplingMode=a,d.type=o,d.format=l,d.label=r,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,n=null,o=null,a,l,h=null,c=null,u=null,d=null,_,p,f){const m="data:"===(e=e||"").substr(0,5),g="blob:"===e.substr(0,5),v=m&&-1!==e.indexOf(";base64,"),x=c||new Pi(this,Ai.Url);x!==c&&(x.label=e.substring(0,60));const b=e;!this._transformTextureUrl||v||c||h||(e=this._transformTextureUrl(e)),b!==e&&(x._originalUrl=b);const T=e.lastIndexOf(".");let y=d||(T>-1?e.substring(T).toLowerCase():""),S=null;y.indexOf("?")>-1&&(y=y.split("?")[0]);for(const e of ki._TextureLoaders)if(e.canLoad(y,_)){S=e;break}s&&s.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=r,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!f,t),this._doNotHandleContextLost||(x._buffer=h);let C=null;n&&!c&&(C=x.onLoadedObservable.add(n)),c||this._internalTexturesCache.push(x);const E=(i,c)=>{s&&s.removePendingData(x),e===b?(C&&x.onLoadedObservable.remove(C),se.UseFallbackTexture&&e!==se.FallbackTexture&&this._createTextureBase(se.FallbackTexture,t,x.invertY,s,r,null,o,a,l,h,x),i=(i||"Unknown error")+(se.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:i,exception:c}),o&&o(i,c)):(we.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,x.invertY,s,r,n,o,a,l,h,x,u,d,_,p,f))};if(S){const t=e=>{S.loadData(e,x,((e,t,i,n,o,l)=>{l?E("TextureLoader failed to load data"):a(x,y,s,{width:e,height:t},x.invertY,!i,n,(()=>(o(),!1)),r)}),p)};h?h instanceof ArrayBuffer?t(new Uint8Array(h)):ArrayBuffer.isView(h)?t(h):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,s?s.offlineProvider:void 0,!0,((e,t)=>{E("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{g&&!this._doNotHandleContextLost&&(x._buffer=e),a(x,y,s,e,x.invertY,t,!1,l,r)};!m||v?h&&("string"==typeof h.decoding||h.close)?i(h):ki._FileToolsLoadImage(e,i,E,s?s.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?ki._FileToolsLoadImage(h,i,E,s?s.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return x}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,s,r,n,o,this._prepareWebGLTexture.bind(this),((e,t,i,r,n,o)=>{const a=this._gl,l=i.width===e&&i.height===t;n._creationFlags=_??0;const c=this._getTexImageParametersForCreateTexture(h,r,n._useSRGBBuffer);if(l)return a.texImage2D(a.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),!1;const u=this._caps.maxTextureSize;if(i.width>u||i.height>u||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,c.internalFormat,c.format,c.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new Pi(this,Ai.Temp);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),this._rescaleTexture(e,n,s,c.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,n,!0),o()}))}return!0}),a,l,h,c,u,d,p)}_getTexImageParametersForCreateTexture(e,t,i){let s,r;return null==e&&(e=".jpg"!==t||i?5:4),1===this.webGLVersion?(s=this._getInternalFormat(e,i),r=s):(s=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,i)),{internalFormat:r,format:s,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,i,s,r,n){throw vt("FileTools")}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){throw vt("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,o,a=null){throw vt("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,o,a,l=null,h=0){throw vt("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,o,a,l=null,h=0){throw vt("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(u-s,0)),p=n?e.height:Math.pow(2,Math.max(d-s,0));o.texImage2D(c,s,h,_,p,0,l,a,t)}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,_=h.TEXTURE_2D;e.isCube&&(_=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(_,a,i,s,r,n,u,c,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),i||s||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,o,a,l=3){const h=this.getCaps().maxTextureSize,c=Math.min(h,this.needPOTTextures?ki.GetExponentOfTwo(s.width,h):s.width),u=Math.min(h,this.needPOTTextures?ki.GetExponentOfTwo(s.height,h):s.height),d=this._gl;d&&(e._hardwareTexture?(this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=c,e.height=u,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:".jpg"!==t||e._useSRGBBuffer?5:4,a(c,u,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,o,l)}))||this._prepareWebGLTextureContinuation(e,i,n,o,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture?.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw we.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const a=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(a,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(a,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),this.releaseComputeEffects?.(),this.unbindAllAttributes(),this._boundUniforms={},Lt()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,Ti.ResetCache();for(const e of this._activeRequests)e.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext()}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_loadFile(e,t,i,s,r,n){const o=ki._FileToolsLoadFile(e,t,i,s,r,n);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}static _FileToolsLoadFile(e,t,i,s,r,n){throw vt("FileTools")}readPixels(e,t,i,s,r=!0,n=!0){const o=r?4:3,a=r?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=this._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=this._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){const t=ki.CeilingPOT(e),i=ki.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=ki.FloorPOT(e);break;case 2:s=ki.NearestPOT(e);break;default:s=ki.CeilingPOT(e)}return Math.min(s,t)}static QueueNewFrame(e,t){if(Lt()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:Vt()?document:null}}ki._TempClearColorUint32=new Uint32Array(4),ki._TempClearColorInt32=new Int32Array(4),ki.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],ki._TextureLoaders=[],ki.CollisionsEpsilon=.001,ki._IsSupported=null,ki._HasMajorPerformanceCaveat=null;class Vi{static SetImmediate(e){Lt()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const Ui=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class Gi extends Qt{constructor(e,t){super(e,Yt.LoadFileError),this.name="LoadFileError",Xt._setPrototypeOf(this,Gi.prototype),t instanceof At?this.request=t:this.file=t}}class zi extends Qt{constructor(e,t){super(e,Yt.RequestFileError),this.request=t,this.name="RequestFileError",Xt._setPrototypeOf(this,zi.prototype)}}class Wi extends Qt{constructor(e,t){super(e,Yt.ReadFileError),this.file=t,this.name="ReadFileError",Xt._setPrototypeOf(this,Wi.prototype)}}const Hi={DefaultRetryStrategy:Ht.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e},Xi=e=>e.replace(/#/gm,"%23"),Yi=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&Hi.CorsBehavior)if("string"==typeof Hi.CorsBehavior||Hi.CorsBehavior instanceof String)t.crossOrigin=Hi.CorsBehavior;else{const i=Hi.CorsBehavior(e);i&&(t.crossOrigin=i)}},Qi=(e,t,i,s,r="",n)=>{const o=se.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!o?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let a,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(a=URL.createObjectURL(new Blob([e],{type:r})),l=!0):a=`data:${r};base64,`+qt(e):e instanceof Blob?(a=URL.createObjectURL(e),l=!0):(a=Xi(e),a=Hi.PreprocessUrl(e));const h=t=>{if(i){const s=a||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(o?._features.forceBitmapOverHTMLImageElement)return Ki(a,(s=>{o.createImageBitmap(new Blob([s],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),l&&URL.revokeObjectURL(a)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{h(t)})),null;const c=new Image;Yi(a,c);const u=[],d=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),h(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);se.UseFallbackTexture=!1,h(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const _="blob:"===a.substring(0,5),p="data:"===a.substring(0,5),f=()=>{_||p||!At.IsCustomRequestAvailable?c.src=a:Ki(a,((e,t,i)=>{const s=new Blob([e],{type:!r&&i?i:r}),n=URL.createObjectURL(s);l=!0,c.src=n}),void 0,s||void 0,!0,((e,t)=>{h(t)}))};if(!_&&!p&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(a,c)}),f);else{if(-1!==a.indexOf("file:")){const e=decodeURIComponent(a.substring(5).toLowerCase());if(Wt.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(Wt.FilesToLoad[e])}catch(i){t=URL.createObjectURL(Wt.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}f()}return c},ji=(e,t,i,s,r)=>{const n=new FileReader,o={onCompleteObservable:new X,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),r&&(n.onerror=()=>{r(new Wi(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),s?n.readAsArrayBuffer(e):n.readAsText(e),o},Ki=(e,t,i,s,r,n,o)=>{if(e.name)return ji(e,t,i,r,n?e=>{n(void 0,e)}:void 0);const a=e;if(-1!==a.indexOf("file:")){let e=decodeURIComponent(a.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=Wt.FilesToLoad[e];if(s)return ji(s,t,i,r,n?e=>n(void 0,new Gi(e.message,e.file)):void 0)}const{match:l,type:h}=Ji(a);if(l){const e={onCompleteObservable:new X,abort:()=>()=>{}};try{const e=r?es(a):ts(a);t(e,void 0,h)}catch(e){n?n(void 0,e):we.Error(e.message||"Failed to parse the Data URL")}return Vi.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return $i(a,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,r,n?e=>{n(e.request,new Gi(e.message,e.request))}:void 0,o)},$i=(e,t,i,s,r,n,o)=>{e=Xi(e),e=Hi.PreprocessUrl(e);const a=Hi.BaseUrl+e;let l=!1;const h={onCompleteObservable:new X,abort:()=>l=!0},c=()=>{let e,s=new At,c=null;const u=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",d))};let d=()=>{u(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,d=null,n=void 0,o=void 0,t=void 0};h.abort=()=>{l=!0,d&&d(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const _=e=>{const t=e.message||"Unknown error";n&&s?n(new zi(t,s)):we.Error(t)},p=h=>{if(s){if(s.open("GET",a),o)try{o(s)}catch(e){return void _(e)}r&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),d&&s.addEventListener("loadend",d),e=()=>{if(!l&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!Lt()||qi())){try{t&&t(r?s.response:s.responseText,s)}catch(e){_(e)}return}const i=Hi.DefaultRetryStrategy;if(i){const e=i(a,s,h);if(-1!==e)return u(),s=new At,void(c=setTimeout((()=>p(h+1)),e))}const o=new zi("Error status: "+s.status+" "+s.statusText+" - Unable to load "+a,s);n&&n(o)}},s.addEventListener("readystatechange",e),s.send()}};p(0)};if(s&&s.enableSceneOffline){const o=e=>{e&&e.status>400?n&&n(e):c()},a=()=>{s&&s.loadFile(Hi.BaseUrl+e,(e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)}),i?e=>{!l&&i&&i(e)}:void 0,o,r)};s.open(a,o)}else c();return h},qi=()=>"undefined"!=typeof location&&"file:"===location.protocol,Zi=e=>Ui.test(e),Ji=e=>{const t=Ui.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function es(e){return Jt(e.split(",")[1])}const ts=e=>Zt(e.split(",")[1]);let is;ki._FileToolsLoadImage=Qi,ki._FileToolsLoadFile=Ki,xi._FileToolsLoadFile=Ki;const ss=(e,t,i,s,r,n,o,a,l,h)=>{is={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:r,LoadFile:n,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(is,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(is,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(is,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(is,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})};ss(es,ts,Hi,Zi,qi,Ki,Qi,ji,$i,Yi);class rs{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=te(e);if(t)return t;we.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}rs.RegisteredExternalClasses={};const os={RandomId:ns};function as(e){let t=1;do{t*=2}while(te.indexOf("/"))&&(e.indexOf("://"){Ki(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(hs.ScriptBaseUrl&&e.startsWith(hs._DefaultCdnUrl)){const t="/"===hs.ScriptBaseUrl[hs.ScriptBaseUrl.length-1]?hs.ScriptBaseUrl.substring(0,hs.ScriptBaseUrl.length-1):hs.ScriptBaseUrl;e=e.replace(hs._DefaultCdnUrl,t)}return e=hs.ScriptPreprocessUrl(e),t&&(e=hs.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=hs.GetBabylonScriptURL(e),hs.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=hs.GetBabylonScriptURL(e),hs.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!Lt())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new X,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return ji(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){Xe.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const s=atob(this.toDataURL(t,i).split(",")[1]),r=s.length,n=new Uint8Array(r);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}hs.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if("string"!=typeof s&&t){if(t){if(hs._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,r);t(s)}}else this.ToBlob(e,(function(e){e&&hs.DownloadBlob(e,s),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",(()=>{s.parentElement&&s.parentElement.removeChild(s)})),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,o){throw vt("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw vt("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u){throw vt("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){throw vt("ScreenshotTools")}static RandomId(){return ns()}static IsBase64(e){return Zi(e)}static DecodeBase64(e){return es(e)}static get errorsCount(){return we.errorsCount}static Log(e){we.Log(e)}static Warn(e){we.Warn(e)}static Error(e){we.Error(e)}static get LogCache(){return we.LogCache}static ClearLogCache(){we.ClearLogCache()}static set LogLevels(e){we.LogLevels=e}static set PerformanceLogLevel(e){return(e&hs.PerformanceUserMarkLogLevel)===hs.PerformanceUserMarkLogLevel?(hs.StartPerformanceCounter=hs._StartUserMark,void(hs.EndPerformanceCounter=hs._EndUserMark)):(e&hs.PerformanceConsoleLogLevel)===hs.PerformanceConsoleLogLevel?(hs.StartPerformanceCounter=hs._StartPerformanceConsole,void(hs.EndPerformanceCounter=hs._EndPerformanceConsole)):(hs.StartPerformanceCounter=hs._StartPerformanceCounterDisabled,void(hs.EndPerformanceCounter=hs._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!hs._Performance){if(!Lt())return;hs._Performance=window.performance}t&&hs._Performance.mark&&hs._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&hs._Performance.mark&&(hs._Performance.mark(e+"-End"),hs._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(hs._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(hs._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return zt.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!kt()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}function cs(e,t){return i=>{i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}hs.UseCustomRequestHeaders=!1,hs.CustomRequestHeaders=At.CustomRequestHeaders,hs.GetDOMTextContent=Ut,hs._DefaultCdnUrl="https://cdn.babylonjs.com",hs.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},hs.NoneLogLevel=we.NoneLogLevel,hs.MessageLogLevel=we.MessageLogLevel,hs.WarningLogLevel=we.WarningLogLevel,hs.ErrorLogLevel=we.ErrorLogLevel,hs.AllLogLevel=we.AllLogLevel,hs.IsWindowObjectExist=Lt,hs.PerformanceNoneLogLevel=0,hs.PerformanceUserMarkLogLevel=1,hs.PerformanceConsoleLogLevel=2,hs.StartPerformanceCounter=hs._StartPerformanceCounterDisabled,hs.EndPerformanceCounter=hs._EndPerformanceCounterDisabled;class us{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?s.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(o),r&&r()){s.breakLoop();break}}s.executeNext()}),n)}),s)}}hs.Mix=ls,hs.IsExponentOfTwo=as,se.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class ds{constructor(e){this.length=0,this.data=new Array(e),this._id=ds._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}ds._GlobalId=0;class _s extends ds{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return!(e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;tthis.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}function fs(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class ms{constructor(){this._dirty=!0,this._tempColor=new Ee(0,0,0,0),this._globalCurve=new Ee(0,0,0,0),this._highlightsCurve=new Ee(0,0,0,0),this._midtonesCurve=new Ee(0,0,0,0),this._shadowsCurve=new Ee(0,0,0,0),this._positiveCurve=new Ee(0,0,0,0),this._negativeCurve=new Ee(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){null!=e&&(e=ms._Clamp(e,0,360),t=ms._Clamp(t,-100,100),i=ms._Clamp(i,-100,100),s=ms._Clamp(s,-100,100),t=ms._ApplyColorGradingSliderNonlinear(t),t*=.5,s=ms._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),ms._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let r=ms._Clamp(e,0,360);const n=ms._Clamp(t/100,0,1),o=ms._Clamp(i/100,0,1);if(0===n)s.r=o,s.g=o,s.b=o;else{r/=60;const e=Math.floor(r),t=r-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:s.r=o,s.g=l,s.b=i;break;case 1:s.r=a,s.g=o,s.b=i;break;case 2:s.r=i,s.g=o,s.b=l;break;case 3:s.r=i,s.g=a,s.b=o;break;case 4:s.r=l,s.g=i,s.b=o;break;default:s.r=o,s.g=i,s.b=a}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return yt.Clone((()=>new ms),this)}serialize(){return yt.Serialize(this)}static Parse(e){return yt.Parse((()=>new ms),e,null,null)}}function gs(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&fs(e),t.DITHER&&e.push("ditherIntensity")}function vs(e,t){t.COLORGRADING&&e.push("txColorTransform")}ms.PrepareUniforms=fs,qe([st()],ms.prototype,"_globalHue",void 0),qe([st()],ms.prototype,"_globalDensity",void 0),qe([st()],ms.prototype,"_globalSaturation",void 0),qe([st()],ms.prototype,"_globalExposure",void 0),qe([st()],ms.prototype,"_highlightsHue",void 0),qe([st()],ms.prototype,"_highlightsDensity",void 0),qe([st()],ms.prototype,"_highlightsSaturation",void 0),qe([st()],ms.prototype,"_highlightsExposure",void 0),qe([st()],ms.prototype,"_midtonesHue",void 0),qe([st()],ms.prototype,"_midtonesDensity",void 0),qe([st()],ms.prototype,"_midtonesSaturation",void 0),qe([st()],ms.prototype,"_midtonesExposure",void 0),yt._ColorCurvesParser=ms.Parse;class xs{constructor(){this.colorCurves=new ms,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=xs.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ee(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=xs.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new X}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===xs._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===xs.TONEMAPPING_ACES?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&ms.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:s/i;let n=Math.tan(.5*this.vignetteCameraFov),o=n*r;const a=Math.sqrt(o*n);o=ls(o,a,this.vignetteStretch),n=ls(n,a,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return yt.Clone((()=>new xs),this)}serialize(){return yt.Serialize(this)}static Parse(e){const t=yt.Parse((()=>new xs),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}xs.TONEMAPPING_STANDARD=0,xs.TONEMAPPING_ACES=1,xs.PrepareUniforms=gs,xs.PrepareSamplers=vs,xs._VIGNETTEMODE_MULTIPLY=0,xs._VIGNETTEMODE_OPAQUE=1,qe([ct()],xs.prototype,"colorCurves",void 0),qe([st()],xs.prototype,"_colorCurvesEnabled",void 0),qe([rt("colorGradingTexture")],xs.prototype,"_colorGradingTexture",void 0),qe([st()],xs.prototype,"_colorGradingEnabled",void 0),qe([st()],xs.prototype,"_colorGradingWithGreenDepth",void 0),qe([st()],xs.prototype,"_colorGradingBGR",void 0),qe([st()],xs.prototype,"_exposure",void 0),qe([st()],xs.prototype,"_toneMappingEnabled",void 0),qe([st()],xs.prototype,"_toneMappingType",void 0),qe([st()],xs.prototype,"_contrast",void 0),qe([st()],xs.prototype,"vignetteStretch",void 0),qe([st()],xs.prototype,"vignetteCenterX",void 0),qe([st()],xs.prototype,"vignetteCenterY",void 0),qe([st()],xs.prototype,"vignetteWeight",void 0),qe([ut()],xs.prototype,"vignetteColor",void 0),qe([st()],xs.prototype,"vignetteCameraFov",void 0),qe([st()],xs.prototype,"_vignetteBlendMode",void 0),qe([st()],xs.prototype,"_vignetteEnabled",void 0),qe([st()],xs.prototype,"_ditheringEnabled",void 0),qe([st()],xs.prototype,"_ditheringIntensity",void 0),qe([st()],xs.prototype,"_skipFinalColorClamp",void 0),qe([st()],xs.prototype,"_applyByPostProcess",void 0),qe([st()],xs.prototype,"_isEnabled",void 0),yt._ImageProcessingConfigurationParser=xs.Parse,ki.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new Di(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},ki.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new Di(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},ki.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},ki.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},ki.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},ki.prototype.bindUniformBlock=function(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);4294967295!==r&&this._gl.uniformBlockBinding(s,r,i)};class bs{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,s=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(bs._UpdatedUbosInFrame[this._name]||(bs._UpdatedUbosInFrame[this._name]=0),bs._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer)return void we.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));we.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class ys{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,r,n,o,a,l,h,c=!1,u=!1,d=1,_=!1){this._isDisposed=!1;let p=!1;if(this.engine=e,"object"==typeof s&&null!==s?(p=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,o=s.instanced,a=s.offset,l=s.size,h=s.type,c=s.normalized??!1,u=s.useBytes??!1,d=s.divisor??1,_=s.takeBufferOwnership??!1,this._label=s.label):p=!!s,t instanceof Ts?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new Ts(e,t,p,n,r,o,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=ys._Counter++,this._kind=i,void 0===h){const e=this.getData();this.type=e?ys.GetDataType(e):ys.FLOAT}else this.type=h;const f=ys.GetTypeByteLength(this.type);u?(this._size=l||(n?n/f:ys.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*f,this.byteOffset=a||0):(this._size=l||n||ys.DeduceStride(i),this.byteStride=n?n*f:this._buffer.byteStride||this._size*f,this.byteOffset=(a||0)*f),this.normalized=c,this._instanced=void 0!==o&&o,this._instanceDivisor=o?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?ys.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/ys.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/ys.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*ys.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){ys.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case ys.UVKind:case ys.UV2Kind:case ys.UV3Kind:case ys.UV4Kind:case ys.UV5Kind:case ys.UV6Kind:return 2;case ys.NormalKind:case ys.PositionKind:return 3;case ys.ColorKind:case ys.ColorInstanceKind:case ys.MatricesIndicesKind:case ys.MatricesIndicesExtraKind:case ys.MatricesWeightsKind:case ys.MatricesWeightsExtraKind:case ys.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?ys.BYTE:e instanceof Uint8Array?ys.UNSIGNED_BYTE:e instanceof Int16Array?ys.SHORT:e instanceof Uint16Array?ys.UNSIGNED_SHORT:e instanceof Int32Array?ys.INT:e instanceof Uint32Array?ys.UNSIGNED_INT:ys.FLOAT}static GetTypeByteLength(e){switch(e){case ys.BYTE:case ys.UNSIGNED_BYTE:return 1;case ys.SHORT:case ys.UNSIGNED_SHORT:return 2;case ys.INT:case ys.UNSIGNED_INT:case ys.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,a){if(e instanceof Array){let r=t/4;const o=i/4;for(let t=0;to[t]=e)),o}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==h){if(e instanceof Array){const t=s/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,h);{let t=e.byteOffset+s;if(a){const i=new Float32Array(h),s=new Float32Array(e.buffer,t,h);return i.set(s),i}const i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return a?e.slice():e}}ys._Counter=0,ys.BYTE=5120,ys.UNSIGNED_BYTE=5121,ys.SHORT=5122,ys.UNSIGNED_SHORT=5123,ys.INT=5124,ys.UNSIGNED_INT=5125,ys.FLOAT=5126,ys.PositionKind="position",ys.NormalKind="normal",ys.TangentKind="tangent",ys.UVKind="uv",ys.UV2Kind="uv2",ys.UV3Kind="uv3",ys.UV4Kind="uv4",ys.UV5Kind="uv5",ys.UV6Kind="uv6",ys.ColorKind="color",ys.ColorInstanceKind="instanceColor",ys.MatricesIndicesKind="matricesIndices",ys.MatricesWeightsKind="matricesWeights",ys.MatricesIndicesExtraKind="matricesIndicesExtra",ys.MatricesWeightsExtraKind="matricesWeightsExtra";class Ss{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(ys.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(ys.NormalKind);let t=s?de.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?de.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?de.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),a=a.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new de(t.x+a.x+l.x,t.y+a.y+l.y,t.z+a.z+l.z)}else{const e=this.pickedMesh.getVerticesData(ys.PositionKind),t=s?de.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?de.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?de.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),h=t.subtract(a),c=l.subtract(a);i=de.Cross(h,c)}const a=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(ge.Matrix[0].copyFrom(i),i=ge.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(ge.Matrix[1]),i=ge.Matrix[1]),de.TransformNormalToRef(t,i,t)};if(e&&a(this.pickedMesh,i),this.ray){const t=ge.Vector3[0].copyFrom(i);e||a(this.pickedMesh,t),de.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=ys.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=ue.FromArray(i,2*t[3*this.faceId]),r=ue.FromArray(i,2*t[3*this.faceId+1]),n=ue.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new ue(s.x+r.x+n.x,s.y+r.y+n.y)}}class Cs{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[ys.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[ys.PositionKind]=new ys(this._scene.getEngine(),e,ys.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,s=0,r=0,n=!1){const o=this._scene.getEngine();for(let a=0;anull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let a=0,l=s.length;at._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=ks.LeftClick&&i<=ks.RightClick&&(a.type=1===s?"pointerdown":"pointerup",a.button=i-2),a}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=Xs.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case ks.MouseWheelX:o.deltaX=s;break;case ks.MouseWheelY:o.deltaY=s;break;case ks.MouseWheelZ:o.deltaZ=s}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),a=r.pollInput(e,t,ks.Horizontal),l=r.pollInput(e,t,ks.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,Vs.DeltaHorizontal),o.movementY=r.pollInput(e,t,Vs.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=a,o.clientY=l,o.x=a,o.y=l,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=Ls.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(Ls.Keyboard),s=i&&1===t.pollInput(Ls.Keyboard,0,18),r=i&&1===t.pollInput(Ls.Keyboard,0,17),n=i&&(1===t.pollInput(Ls.Keyboard,0,91)||1===t.pollInput(Ls.Keyboard,0,92)||1===t.pollInput(Ls.Keyboard,0,93)),o=i&&1===t.pollInput(Ls.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Qs{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,r)=>{const n=Ys.CreateDeviceEvent(e,t,s,r,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Ls.Mouse||e===Ls.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const js=Object.keys(ks).length/2;class Ks{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=hs.IsSafari(),this._usingMacOS=kt()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=kt()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=kt()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=hs.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${Ls[e]}`;e>=Ls.DualShock&&e<=Ls.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${Ls[e]} in slot ${t}`;return i===ks.Move&&hs.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ls.Keyboard,0,255));const t=this._inputs[Ls.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(Ls.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ls.Keyboard,0,255));const t=this._inputs[Ls.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=Ys.CreateDeviceEvent(Ls.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(Ls.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Ls.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[Ls.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===Ls.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Ls.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void hs.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=ks.Move,s[ks.Horizontal]=e.clientX,s[ks.Vertical]=e.clientY,t===Ls.Touch&&0===s[ks.LeftClick]&&(s[ks.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===Ls.Mouse?0:e.pointerId;if(t===Ls.Touch){const t=this._activeTouchIds.indexOf(-1);if(!(t>=0))return void hs.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===Ls.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[ks.Horizontal],n=s[ks.Vertical];if(t===Ls.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[ks.Horizontal]=e.clientX,s[ks.Vertical]=e.clientY,s[e.button+2]=1;const o=e;o.inputIndex=e.button+2,this._onInputChanged(t,i,o),r===e.clientX&&n===e.clientY||(o.inputIndex=ks.Move,this._onInputChanged(t,i,o))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===Ls.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Ls.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const r=s[ks.Horizontal],n=s[ks.Vertical];s[ks.Horizontal]=e.clientX,s[ks.Vertical]=e.clientY,s[e.button+2]=0;const o=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(o.inputIndex=ks.Move,this._onInputChanged(t,i,o)),o.inputIndex=e.button+2,t===Ls.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,o),t===Ls.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[Ls.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=ks.LeftClick;t<=ks.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Ys.CreateDeviceEvent(Ls.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ls.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[Ls.Touch][t][ks.LeftClick]=0;const i=Ys.CreateDeviceEvent(Ls.Touch,t,ks.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(Ls.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Ls.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(Ls.Mouse)){const e=this._inputs[Ls.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=ks.LeftClick;t<=ks.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Ys.CreateDeviceEvent(Ls.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ls.Mouse,0,i)}}if(this.isDeviceAvailable(Ls.Touch)){const e=this._inputs[Ls.Touch];for(let t=0;t{const t=Ls.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,js));const i=this._inputs[t][0];if(i){i[ks.MouseWheelX]=e.deltaX||0,i[ks.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[ks.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[ks.MouseWheelX]&&(s.inputIndex=ks.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[ks.MouseWheelY]&&(s.inputIndex=ks.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[ks.MouseWheelZ]&&(s.inputIndex=ks.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(Ls.Mouse)){const e=this._inputs[Ls.Mouse][0];e[ks.MouseWheelX]=0,e[ks.MouseWheelY]=0,e[ks.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Ls.DualSense:Ls.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?Ls.Xbox:-1!==e.indexOf("057e")?Ls.Switch:Ls.Generic}_getPointerType(e){let t=Ls.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Ls.Touch),t}}class $s{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new X,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class qs{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(Ls).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new $s(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new Qs(i,s,r):this._deviceInputSystem=new Ks(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Zs{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(Ls).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new qs(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new X((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new X,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Ls.Keyboard:case Ls.Mouse:this._firstDevice[e]=0;break;case Ls.Touch:case Ls.DualSense:case Ls.DualShock:case Ls.Xbox:case Ls.Switch:case Ls.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=ks.MouseWheelX&&t.inputIndex<=ks.MouseWheelZ?Ms.POINTERWHEEL:Ms.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(o=new ws(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new ws(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,fe.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new Ds(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=ks.Move,this._checkPrePointerObservable(e,i,Ms.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,Ms.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(5,Re.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(2,Re.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(4,Re.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(3,Re.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>er.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(8,Re.CreateNew(e.pickedMesh,t)))}),er.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=Ms.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new ws(r,t,e),this._setRayOnPointerInfo(e,t)):s=new ws(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=ks.Move;const r=new Js;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,Ms.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=Ms.POINTERPICK,r=new ws(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,Re.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,Re.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&s&&s.processTrigger(6,Re.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,Re.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new ws(Ms.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,Ms.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Ms.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=Ms.POINTERTAP:i.doubleClick&&(r=Ms.POINTERDOUBLETAP),r){const i=new ws(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Zs(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>er.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=Ms.POINTERTAP,s=new ws(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const r=new Js;this._currentPickResult=null;let n=null,o=e.hasSpecificMask(Ms.POINTERPICK)||t.hasSpecificMask(Ms.POINTERPICK)||e.hasSpecificMask(Ms.POINTERTAP)||t.hasSpecificMask(Ms.POINTERTAP)||e.hasSpecificMask(Ms.POINTERDOUBLETAP)||t.hasSpecificMask(Ms.POINTERDOUBLETAP);!o&&z&&(n=this._initActionManager(n,r),n&&(o=n.hasPickTriggers));let a=!1;if(o){const o=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let l=!er.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(Ms.POINTERDOUBLETAP)&&!t.hasSpecificMask(Ms.POINTERDOUBLETAP),l&&!z.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(l=!n.hasSpecificTrigger(6)))),l)(Date.now()-this._previousStartingPointerTime>er.DoubleClickDelay||o!==this._previousButtonPressed)&&(r.singleClick=!0,s(r,this._currentPickResult),a=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,o,r,s),er.DoubleClickDelay)};this._delayedClicks[o]=e}let h=e.hasSpecificMask(Ms.POINTERDOUBLETAP)||t.hasSpecificMask(Ms.POINTERDOUBLETAP);!h&&z.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(h=n.hasSpecificTrigger(6))),h&&(o===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>er.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>er.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=ks.MouseWheelX&&e.inputIndex<=ks.MouseWheelZ?Ms.POINTERWHEEL:Ms.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new Ss,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,er.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new Ss:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,Ms.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(Ms.POINTERTAP)&&this._checkPrePointerObservable(null,e,Ms.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(Ms.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,Ms.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(z&&z.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=Ns.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new Bs(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Fs(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,Re.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=Ns.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new Bs(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Fs(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,Re.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===Ls.Mouse?s.onInputChangedObservable.add((r=>{r.inputIndex===ks.LeftClick||r.inputIndex===ks.MiddleClick||r.inputIndex===ks.RightClick||r.inputIndex===ks.BrowserBack||r.inputIndex===ks.BrowserForward?t&&1===s.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===s.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===ks.Move?this._onPointerMove(r):r.inputIndex!==ks.MouseWheelX&&r.inputIndex!==ks.MouseWheelY&&r.inputIndex!==ks.MouseWheelZ||this._onPointerMove(r))})):s.deviceType===Ls.Touch?s.onInputChangedObservable.add((r=>{r.inputIndex===ks.LeftClick&&(t&&1===s.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===ks.Move&&this._onPointerMove(r)})):s.deviceType===Ls.Keyboard&&s.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,Re.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,Re.CreateNew(e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}er.DragMovementThreshold=10,er.LongPressDelay=500,er.DoubleClickDelay=300,er.ExclusiveDoubleClickMode=!1;class tr{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){tr.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){tr.Enabled&&(this._startMonitoringTime=zt.Now)}endMonitoring(e=!0){if(!tr.Enabled)return;e&&this.fetchNewFrame();const t=zt.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=zt.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}tr.Enabled=!0;class ir{constructor(e,t,i,s){this.normal=new de(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new ir(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=ir._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,a=s*i[0]+r*i[1]+n*i[2]+o*i[3],l=s*i[4]+r*i[5]+n*i[6]+o*i[7],h=s*i[8]+r*i[9]+n*i[10]+o*i[11],c=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new ir(a,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=r*l-n*a,c=n*o-s*l,u=s*a-r*o,d=Math.sqrt(h*h+c*c+u*u);let _;return _=0!==d?1/d:0,this.normal.x=h*_,this.normal.y=c*_,this.normal.z=u*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return de.Dot(this.normal,e)<=t}signedDistanceTo(e){return de.Dot(e,this.normal)+this.d}static FromArray(e){return new ir(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new ir(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new ir(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return de.Dot(i,t)+s}}ir._TmpMatrix=fe.Identity();class sr{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new ir(0,0,0,0));return sr.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){sr.GetNearPlaneToRef(e,t[0]),sr.GetFarPlaneToRef(e,t[1]),sr.GetLeftPlaneToRef(e,t[2]),sr.GetRightPlaneToRef(e,t[3]),sr.GetTopPlaneToRef(e,t[4]),sr.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class rr{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}rr._UniqueIdCounter=1;class nr{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}nr.FALLOFF_DEFAULT=0,nr.FALLOFF_PHYSICAL=1,nr.FALLOFF_GLTF=2,nr.FALLOFF_STANDARD=3,nr.LIGHTMAP_DEFAULT=0,nr.LIGHTMAP_SPECULAR=1,nr.LIGHTMAP_SHADOWSONLY=2,nr.INTENSITYMODE_AUTOMATIC=0,nr.INTENSITYMODE_LUMINOUSPOWER=1,nr.INTENSITYMODE_LUMINOUSINTENSITY=2,nr.INTENSITYMODE_ILLUMINANCE=3,nr.INTENSITYMODE_LUMINANCE=4,nr.LIGHTTYPEID_POINTLIGHT=0,nr.LIGHTTYPEID_DIRECTIONALLIGHT=1,nr.LIGHTTYPEID_SPOTLIGHT=2,nr.LIGHTTYPEID_HEMISPHERICLIGHT=3;class or{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var ar,lr,hr,cr,ur;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(ar||(ar={}));class dr extends G{static DefaultMaterialFactory(e){throw vt("StandardMaterial")}static CollisionCoordinatorFactory(){throw vt("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case ar.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case ar.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case ar.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return er.DragMovementThreshold}static set DragMovementThreshold(e){er.DragMovementThreshold=e}static get LongPressDelay(){return er.LongPressDelay}static set LongPressDelay(e){er.LongPressDelay=e}static get DoubleClickDelay(){return er.DoubleClickDelay}static set DoubleClickDelay(e){er.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return er.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){er.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return ge.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,ge.Vector4[0].x,ge.Vector4[0].y,ge.Vector4[0].z):e.setVector4(t,ge.Vector4[0])),ge.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=Z(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=dr.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=dr.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new er(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Ee(.2,.2,.3,1),this.ambientColor=new Ce(0,0,0),this.environmentIntensity=1,this._performancePriority=ar.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new X,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new X,this._onDisposeObserver=null,this.onBeforeRenderObservable=new X,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new X,this.onAfterRenderCameraObservable=new X,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new X,this.onAfterAnimationsObservable=new X,this.onBeforeDrawPhaseObservable=new X,this.onAfterDrawPhaseObservable=new X,this.onReadyObservable=new X,this.onBeforeCameraRenderObservable=new X,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new X,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new X,this.onAfterActiveMeshesEvaluationObservable=new X,this.onBeforeParticlesRenderingObservable=new X,this.onAfterParticlesRenderingObservable=new X,this.onDataLoadedObservable=new X,this.onNewCameraAddedObservable=new X,this.onCameraRemovedObservable=new X,this.onNewLightAddedObservable=new X,this.onLightRemovedObservable=new X,this.onNewGeometryAddedObservable=new X,this.onGeometryRemovedObservable=new X,this.onNewTransformNodeAddedObservable=new X,this.onTransformNodeRemovedObservable=new X,this.onNewMeshAddedObservable=new X,this.onMeshRemovedObservable=new X,this.onNewSkeletonAddedObservable=new X,this.onSkeletonRemovedObservable=new X,this.onNewMaterialAddedObservable=new X,this.onNewMultiMaterialAddedObservable=new X,this.onMaterialRemovedObservable=new X,this.onMultiMaterialRemovedObservable=new X,this.onNewTextureAddedObservable=new X,this.onTextureRemovedObservable=new X,this.onBeforeRenderTargetsRenderObservable=new X,this.onAfterRenderTargetsRenderObservable=new X,this.onBeforeStepObservable=new X,this.onAfterStepObservable=new X,this.onActiveCameraChanged=new X,this.onActiveCamerasChanged=new X,this.onBeforeRenderingGroupObservable=new X,this.onAfterRenderingGroupObservable=new X,this.onMeshImportedObservable=new X,this.onAnimationFileImportedObservable=new X,this._registeredForLateAnimationBindings=new _s(256),this._pointerPickingConfiguration=new or,this.onPrePointerObservable=new X,this.onPointerObservable=new X,this.onPreKeyboardObservable=new X,this.onKeyboardObservable=new X,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=dr.FOGMODE_NONE,this.fogColor=new Ce(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new de(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new _s(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new tr,this._activeIndices=new tr,this._activeParticles=new tr,this._activeBones=new tr,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new ds(256),this._processedMaterials=new ds(256),this._renderTargets=new _s(256),this._materialsRenderTargets=new _s(256),this._activeParticleSystems=new ds(256),this._activeSkeletons=new _s(32),this._softwareSkinnedMeshes=new _s(32),this._activeAnimatables=new Array,this._transformMatrix=fe.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Is.Create(),this._beforeClearStage=Is.Create(),this._beforeRenderTargetClearStage=Is.Create(),this._gatherRenderTargetsStage=Is.Create(),this._gatherActiveCameraRenderTargetsStage=Is.Create(),this._isReadyForMeshStage=Is.Create(),this._beforeEvaluateActiveMeshStage=Is.Create(),this._evaluateSubMeshStage=Is.Create(),this._preActiveMeshStage=Is.Create(),this._cameraDrawRenderTargetStage=Is.Create(),this._beforeCameraDrawStage=Is.Create(),this._beforeRenderTargetDrawStage=Is.Create(),this._beforeRenderingGroupDrawStage=Is.Create(),this._beforeRenderingMeshStage=Is.Create(),this._afterRenderingMeshStage=Is.Create(),this._afterRenderingGroupDrawStage=Is.Create(),this._afterCameraDrawStage=Is.Create(),this._afterCameraPostProcessStage=Is.Create(),this._afterRenderTargetDrawStage=Is.Create(),this._afterRenderTargetPostProcessStage=Is.Create(),this._afterRenderStage=Is.Create(),this._pointerMoveStage=Is.Create(),this._pointerDownStage=Is.Create(),this._pointerUpStage=Is.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||se.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(se._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Ps(this),Cs&&(this.postProcessManager=new Cs(this)),Lt()&&this.attachControl(),this._createUbo(),xs&&(this._imageProcessingConfiguration=new xs),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(s,n)||(r=!1);if(!e)continue;const o=s.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout((()=>{this._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=zt.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?sr.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=sr.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new bs(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return rr.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;return this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||1===r;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){hs.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(Re.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(dr.MinDeltaTime,Math.min(this._engine.getDeltaTime(),dr.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??0,this.activeCamera=s,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null})),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){we.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),se._LastCreatedScene===this&&(this._engine.scenes.length>0?se._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:se._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),r=s.boundingBox.minimumWorld,n=s.boundingBox.maximumWorld;de.CheckExtends(r,t,i),de.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw vt("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw vt("Ray")}createPickingRayInCameraSpace(e,t,i){throw vt("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw vt("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const o=vt("Ray",!0);return o&&we.Warn(o),new Ss}pickWithBoundingInfo(e,t,i,s,r){const n=vt("Ray",!0);return n&&we.Warn(n),new Ss}pickWithRay(e,t,i,s){throw vt("Ray")}multiPick(e,t,i,s,r){throw vt("Ray")}multiPickWithRay(e,t,i){throw vt("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;const s=[];for(const r in e){const n=e[r];bt&&bt.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,r,n,o){const a=Ki(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._loadFile(e,(e=>{n(e)}),t,i,s,((e,t)=>{o(t)}),r)}))}_requestFile(e,t,i,s,r,n,o){const a=$i(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._requestFile(e,(e=>{n(e)}),t,i,s,(e=>{o(e)}),r)}))}_readFile(e,t,i,s,r){const n=ji(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((s,r)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw vt("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}dr.FOGMODE_NONE=0,dr.FOGMODE_EXP=1,dr.FOGMODE_EXP2=2,dr.FOGMODE_LINEAR=3,dr.MinDeltaTime=1,dr.MaxDeltaTime=1e3,function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(lr||(lr={}));class _r{}_r.X=new de(1,0,0),_r.Y=new de(0,1,0),_r.Z=new de(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(hr||(hr={}));class pr extends Ct{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,o=null){super(e,t.getScene()),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??fe.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new fe,this._absoluteBindMatrix=new fe,this._absoluteInverseBindMatrix=new fe,this._finalMatrix=new fe,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=ge.Vector3[0],t=ge.Quaternion[0],i=ge.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??pe.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=de.Zero(),this._localRotation=pe.Zero(),this._localPosition=de.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,fe.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let i=r.length-1;i>=0;i--){const s=r[i];e&&s.animation.name!=e||t&&!t(s.target)||(s.dispose(),r.splice(i,1))}0==r.length&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let s;for(s=0;s0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const s=this._animationTime;for(let e=0;ee.playOrder-t.playOrder))},dr.prototype.beginWeightedAnimation=function(e,t,i,s=1,r,n=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,r,n,o,a,!1,l,h,c);return u.weight=s,u},dr.prototype.beginAnimation=function(e,t,i,s,r=1,n,o,a=!0,l,h,c=!1){t>i&&r>0&&(r*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new fr(this,e,t,i,s,r,n,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;es&&n>0)n*=-1;else if(s>i&&n<0){const e=s;s=i,i=e}return new fr(this,e,i,s,r,n,o,t,a,l)},dr.prototype.beginDirectHierarchyAnimation=function(e,t,i,s,r,n,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));return u},dr.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,r),a.scaleAndAddToRef(l,i)}r.normalize()}for(let t=0;t0)r.copyFrom(s);else if(1===e.animations.length){if(pe.SlerpToRef(s,i.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let i,n,o=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],n=[],i.push(s),n.push(t)}else{if(2===e.animations.length&&(pe.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],o=e.totalWeight}for(let t=0;t=o&&m.frame<=a&&(s?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(_))):p&&r?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(r))):v=m.value):v=m.value,f.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0};class mr{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=Nt.ANIMATIONLOOPMODE_CYCLE}}!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(cr||(cr={}));class gr{static Interpolate(e,t,i,s,r){const n=1-3*s+3*t,o=3*s-6*t,a=3*t;let l=e;for(let t=0;t<5;t++){const t=l*l;l-=1/(3*n*t+2*o*l+a)*(n*(t*l)+o*t+a*l-e),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*r+Math.pow(l,3)}}class vr{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new vr(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new vr(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=xe.Clamp(s,-1,1);const r=Math.acos(s);return new vr(r)}static FromRadians(e){return new vr(e)}static FromDegrees(e){return new vr(e*Math.PI/180)}}class xr{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new ue((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=vr.BetweenTwoPoints(this.centerPoint,this.startPoint);const a=this.startAngle.degrees();let l=vr.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=vr.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-a>180&&(l-=360),l-a<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-a<0?cr.CW:cr.CCW,this.angle=vr.FromDegrees(this.orientation===cr.CW?a-h:h-a)}}class br{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new ue(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new ue(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new ue(e,t),a=new ue(i,s),l=new xr(n,o,a);let h=l.angle.radians()/r;l.orientation===cr.CW&&(h*=-1);let c=l.startAngle.radians()+h;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s,o=this._points[this._points.length-1];for(let a=0;a<=r;a++){const l=a/r,h=n(l,o.x,e,i),c=n(l,o.y,t,s);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const a=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,u=a(c,l.x,e,i,r),d=a(c,l.y,t,s,n);this.addLineTo(u,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;rNumber.EPSILON){if(a<0&&(i=this._points[r],o=-o,n=this._points[s],a=-a),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const s=a*(e.x-i.x)-o*(e.y-i.y);if(0===s)return!0;if(s<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return ue.Zero();const t=e*this.length();let i=0;for(let e=0;e=i&&t<=o){const e=n.normalize(),s=t-i;return new ue(r.x+e.x*s,r.y+e.y*s)}i=o}return ue.Zero()}static StartingAt(e,t){return new br(e,t)}}class Tr{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:de.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:fe.Identity()};for(let t=0;tt){const i=e;e=t,t=i}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(r++,a.push(s)),a.push(...i.slice(r,o)),1===t&&1!==e||a.push(n),new Tr(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(0===s&&(s=1),null==t){let t;t=xe.WithinEpsilon(Math.abs(e.y)/s,1,K)?xe.WithinEpsilon(Math.abs(e.x)/s,1,K)?xe.WithinEpsilon(Math.abs(e.z)/s,1,K)?de.Zero():new de(0,0,1):new de(1,0,0):new de(0,-1,0),i=de.Cross(e,t)}else i=de.Cross(e,t),de.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s,r=i[0],n=0;const o=e*this.length();for(let a=1;ao){const i=(n-o)/l,h=r.subtract(s),c=s.add(h.scaleInPlace(i));return this._setPointAtData(e,1-i,c,a-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=fe.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),a=this._binormals[t].clone(),l=pe.RotationQuaternionFromAxis(s,r,i),h=pe.RotationQuaternionFromAxis(o,a,n);pe.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class yr{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(e,t,i,s)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s;for(let o=0;o<=s;o++)r.push(new de(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new yr(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],o=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r;for(let a=0;a<=r;a++)n.push(new de(o(a/r,e.x,t.x,i.x,s.x),o(a/r,e.y,t.y,i.y,s.y),o(a/r,e.z,t.z,i.z,s.z)));return new yr(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],o=1/r;for(let a=0;a<=r;a++)n.push(de.Hermite(e,t,i,s,a*o));return new yr(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const i=e.length;for(let o=0;o=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}Sr.EASINGMODE_EASEIN=0,Sr.EASINGMODE_EASEOUT=1,Sr.EASINGMODE_EASEINOUT=2;class Cr extends Sr{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Er extends Sr{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class Ar extends Sr{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const s=Math.pow(i,t),r=1-i,n=(1-s)/r+.5*s,o=e*n,a=Math.log(-o*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(r*n),u=.5*(c+(1-Math.pow(i,h))/(r*n)),d=e-u,_=u-c;return-Math.pow(1/i,t-l)/(_*_)*(d-_)*(d+_)}}class Pr extends Sr{easeInCore(e){return e*e*e}}class Rr extends Sr{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),s=Math.max(0,this.springiness);return t=0==s?e:(Math.exp(s*e)-1)/(Math.exp(s)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class Ir extends Sr{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class Mr extends Sr{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class Or extends Sr{easeInCore(e){return e*e}}class Dr extends Sr{easeInCore(e){return e*e*e*e}}class wr extends Sr{easeInCore(e){return e*e*e*e*e}}class Nr extends Sr{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Fr extends Sr{constructor(e=0,t=0,i=1,s=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=s}easeInCore(e){return gr.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class Br{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new Br(this.frame,this.action,this.onlyOnce)}}class Lr{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class kr{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(this.mask||e){this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);const o=new kr(e[0].name+"_merged",e[0]._scene,s);for(const s of e){i&&s.normalize(r,n);for(const e of s.targetedAnimations)o.addTargetedAnimation(e.animation,e.target);t&&s.dispose()}return o}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new X,this.onAnimationLoopObservable=new X,this.onAnimationGroupLoopObservable=new X,this.onAnimationGroupEndObservable=new X,this.onAnimationGroupPauseObservable=new X,this.onAnimationGroupPlayObservable=new X,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||se.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new Lr;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};s.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,n),this._animatables.push(a)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new kr(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const e of this._targetedAnimations)s.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tr[0].frame&&(e=r[0].frame),t=t&&e<=i||r&&s.frame>=t&&s.frame<=i){const e={frame:s.frame,value:s.value.clone?s.value.clone():s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation,lockedTangent:s.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),o1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach((e=>e(this))),this}onchange(e){return this._onchange.push(e),this}}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(ur||(ur={}));class Ur{constructor(e,t=ur.Include){this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}addTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.add(t);else this._targetNames.add(e)}removeTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.delete(t);else this._targetNames.delete(e)}hasTarget(e){return this._targetNames.has(e)}retainsTarget(e){return this._targetNames.has(e)===(this.mode===ur.Include)}}function Gr(e,t,i){try{const s=e.next();s.done?t(s):s.value?s.value.then((()=>{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function zr(e=25){let t;return(i,s,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{Gr(i,s,r)}),0)):Gr(i,s,r)}}function Wr(e,t,i,s,r){const n=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:n()};do{o=void 0,r&&r.aborted?s(new Error("Aborted")):t(e,a,s),void 0===o&&(o=!1)}while(o)};n()}function Hr(e,t){let i;return Wr(e,Gr,(e=>i=e),(e=>{throw e}),t),i}function Xr(e,t,i){return new Promise(((s,r)=>{Wr(e,t,s,r,i)}))}function Yr(e,t){return(...i)=>Hr(e(...i),t)}function Qr(e,t,i){return(...s)=>Xr(e(...s),t,i)}class jr{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new jr(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new jr(this.x,this.y,this.width,this.height)}}class Kr extends Ct{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===Kr.PERSPECTIVE_CAMERA)this.fovMode===Kr.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i),this._position=de.Zero(),this._upVector=de.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=Kr.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new jr(0,0,1,1),this.layerMask=268435455,this.fovMode=Kr.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Kr.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new X,this.onProjectionMatrixChangedObservable=new X,this.onAfterCheckInputsObservable=new X,this.onRestoreStateObservable=new X,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new fe,this._postProcesses=new Array,this._activeMeshes=new ds(256),this._globalPosition=de.Zero(),this._computedViewMatrix=fe.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=fe.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=pe.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(we.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return fe.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===Kr.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=i.useRightHandedSystem?fe.PerspectiveFovRHToRef:fe.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Kr.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?fe.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):fe.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?fe.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):fe.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?de.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?sr.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=sr.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw vt("Ray")}getForwardRayToRef(e,t=100,i,s){throw vt("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==Kr.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=hs.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Kr.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return fe.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=hs.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eKr._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=Kr.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=yt.Parse(s,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=de.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(de.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(de.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw vt("UniversalCamera")},Kr.PERSPECTIVE_CAMERA=0,Kr.ORTHOGRAPHIC_CAMERA=1,Kr.FOVMODE_VERTICAL_FIXED=0,Kr.FOVMODE_HORIZONTAL_FIXED=1,Kr.RIG_MODE_NONE=0,Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Kr.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Kr.RIG_MODE_VR=20,Kr.RIG_MODE_CUSTOM=22,Kr.ForceAttachControlToAlwaysPreventDefault=!1,qe([lt("position")],Kr.prototype,"_position",void 0),qe([lt("upVector")],Kr.prototype,"_upVector",void 0),qe([st()],Kr.prototype,"orthoLeft",null),qe([st()],Kr.prototype,"orthoRight",null),qe([st()],Kr.prototype,"orthoBottom",null),qe([st()],Kr.prototype,"orthoTop",null),qe([st()],Kr.prototype,"fov",void 0),qe([st()],Kr.prototype,"projectionPlaneTilt",void 0),qe([st()],Kr.prototype,"minZ",void 0),qe([st()],Kr.prototype,"maxZ",void 0),qe([st()],Kr.prototype,"inertia",void 0),qe([st()],Kr.prototype,"mode",null),qe([st()],Kr.prototype,"layerMask",void 0),qe([st()],Kr.prototype,"fovMode",void 0),qe([st()],Kr.prototype,"cameraRigMode",void 0),qe([st()],Kr.prototype,"interaxialDistance",void 0),qe([st()],Kr.prototype,"isStereoscopicSideBySide",void 0);class $r{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class qr{constructor(e,t,i){this.vectors=$.BuildArray(8,de.Zero),this.center=de.Zero(),this.centerWorld=de.Zero(),this.extendSize=de.Zero(),this.extendSizeWorld=de.Zero(),this.directions=$.BuildArray(3,de.Zero),this.vectorsWorld=$.BuildArray(8,de.Zero),this.minimumWorld=de.Zero(),this.maximumWorld=de.Zero(),this.minimum=de.Zero(),this.maximum=de.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,o=t.x,a=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,a,l),h[0].copyFromFloats(s,r,n),h[1].copyFromFloats(o,a,l),h[2].copyFromFloats(o,r,n),h[3].copyFromFloats(s,a,n),h[4].copyFromFloats(s,r,l),h[5].copyFromFloats(o,a,n),h[6].copyFromFloats(s,a,l),h[7].copyFromFloats(o,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||fe.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=qr._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(.5*r),o=this.center.subtractToRef(n,t[1]),a=this.center.addToRef(n,t[2]);return this.reConstruct(o,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const o=r[s];de.TransformCoordinatesToRef(n[s],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}de.FromArrayToRef(e.m,0,s[0]),de.FromArrayToRef(e.m,4,s[1]),de.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return qr.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return qr.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,a=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-K;return!(o-hh-s||a-cc-r||l-uu-n)}intersectsSphere(e){return qr.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,o=i.z,a=s.x,l=s.y,h=s.z,c=e.x,u=e.y,d=e.z,_=t.x,p=t.y,f=t.z;return!(a_||lp||hf)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=qr._TmpVector3[0];return de.ClampToRef(i,e,t,r),de.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}qr._TmpVector3=$.BuildArray(3,de.Zero);class Zr{constructor(e,t,i){this.center=de.Zero(),this.centerWorld=de.Zero(),this.minimum=de.Zero(),this.maximum=de.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=de.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||fe.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Zr._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{de.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Zr._TmpVector3[0];de.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=de.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const s=de.Dot(t.centerWorld,e),r=Math.abs(de.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(de.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(de.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-r,i.max=s+r},sn=(e,t,i)=>(tn(e,t,Jr),tn(e,i,en),!(Jr.min>en.max||en.min>Jr.max));class rn{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new qr(e,t,i),this.boundingSphere=new Zr(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=rn._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=rn._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=de.Minimize(this.minimum,e),i=de.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=ge.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=ge.Vector3[0];return de.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),de.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,rn._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e)}intersects(e,t){if(!Zr.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!qr.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!(sn(i.directions[0],i,s)&&sn(i.directions[1],i,s)&&sn(i.directions[2],i,s)&&sn(s.directions[0],i,s)&&sn(s.directions[1],i,s)&&sn(s.directions[2],i,s)&&sn(de.Cross(i.directions[0],s.directions[0]),i,s)&&sn(de.Cross(i.directions[0],s.directions[1]),i,s)&&sn(de.Cross(i.directions[0],s.directions[2]),i,s)&&sn(de.Cross(i.directions[1],s.directions[0]),i,s)&&sn(de.Cross(i.directions[1],s.directions[1]),i,s)&&sn(de.Cross(i.directions[1],s.directions[2]),i,s)&&sn(de.Cross(i.directions[2],s.directions[0]),i,s)&&sn(de.Cross(i.directions[2],s.directions[1]),i,s)&&sn(de.Cross(i.directions[2],s.directions[2]),i,s))}}rn._TmpVector3=$.BuildArray(2,de.Zero);class nn{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o!Array.isArray(e)&&!Array.isArray(t)))],nn,"extractMinAndMaxIndexed",null),qe([mt.filter(((...[e])=>!Array.isArray(e)))],nn,"extractMinAndMax",null);class ln{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Fi(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,o,a=!0){return new ln(e,t,i,s,r,n,o,a)}constructor(e,t,i,s,r,n,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=o||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,a&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(ys.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=on(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new rn(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;ta&&(a=t)}return new ln(e,o,a-o+1,t,i,s,r,n)}}class hn{}class cn{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Yr(this._applyToCoroutine.bind(this)),this.uniqueId=cn._UniqueIDGenerator,cn._UniqueIDGenerator++}set(e,t){switch(e.length||we.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case ys.PositionKind:this.positions=e;break;case ys.NormalKind:this.normals=e;break;case ys.TangentKind:this.tangents=e;break;case ys.UVKind:this.uvs=e;break;case ys.UV2Kind:this.uvs2=e;break;case ys.UV3Kind:this.uvs3=e;break;case ys.UV4Kind:this.uvs4=e;break;case ys.UV5Kind:this.uvs5=e;break;case ys.UV6Kind:this.uvs6=e;break;case ys.ColorKind:this.colors=e;break;case ys.MatricesIndicesKind:this.matricesIndices=e;break;case ys.MatricesWeightsKind:this.matricesWeights=e;break;case ys.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case ys.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(ys.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(ys.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(ys.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(ys.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(ys.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(ys.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(ys.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(ys.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(ys.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(ys.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(ys.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(ys.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(ys.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(ys.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new ln(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(ys.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(ys.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(ys.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(ys.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(ys.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(ys.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(ys.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(ys.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(ys.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(ys.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(ys.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(ys.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(ys.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(ys.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=ge.Vector3[0],n=ge.Vector3[1];for(let o=i;o({vertexData:e}))):[{vertexData:e}];return Hr(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){this._validate();let a=t.map((e=>e.vertexData)),l=this;if(o)for(const e of a)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of a)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,s=0,r=0;const n=[];let o=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,o&&o.materialIndex===i)o.indexCount+=t.indices.length,o.verticesCount+=t.positions.length/3;else{const e=new hn;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),o=e}s+=t.indices.length,r+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,a=h.map((e=>e.vertexData)),t=h,this.materialInfos=n}const h=a.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=r||a.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let r=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&cn._FlipFaces(c,0,r)}let n=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),s&&(yield),l.normals&&(this.normals=cn._MergeElement(ys.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),l.tangents&&(this.tangents=cn._MergeElement(ys.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),l.uvs&&(this.uvs=cn._MergeElement(ys.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),l.uvs2&&(this.uvs2=cn._MergeElement(ys.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),l.uvs3&&(this.uvs3=cn._MergeElement(ys.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),l.uvs4&&(this.uvs4=cn._MergeElement(ys.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),l.uvs5&&(this.uvs5=cn._MergeElement(ys.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),l.uvs6&&(this.uvs6=cn._MergeElement(ys.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),l.colors&&(this.colors=cn._MergeElement(ys.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),l.matricesIndices&&(this.matricesIndices=cn._MergeElement(ys.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),l.matricesWeights&&(this.matricesWeights=cn._MergeElement(ys.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=cn._MergeElement(ys.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=cn._MergeElement(ys.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const r=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),o=e===ys.PositionKind?cn._TransformVector3Coordinates:e===ys.NormalKind?cn._TransformVector3Normals:e===ys.TangentKind?cn._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&o(e,i,0,t.length);let s=t.length;for(const[t,i]of r)e.set(t,s),i&&o(e,i,s,t.length),s+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=ys.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(ys.PositionKind,this.positions),i=(i,s)=>{const r=e(i,s);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(ys.NormalKind,this.normals),this.tangents&&i(ys.TangentKind,this.tangents),this.uvs&&i(ys.UVKind,this.uvs),this.uvs2&&i(ys.UV2Kind,this.uvs2),this.uvs3&&i(ys.UV3Kind,this.uvs3),this.uvs4&&i(ys.UV4Kind,this.uvs4),this.uvs5&&i(ys.UV5Kind,this.uvs5),this.uvs6&&i(ys.UV6Kind,this.uvs6),this.colors&&i(ys.ColorKind,this.colors),this.matricesIndices&&i(ys.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(ys.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(ys.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(ys.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return cn.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return cn._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return cn._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new cn;return e.isVerticesDataPresent(ys.PositionKind)&&(s.positions=e.getVerticesData(ys.PositionKind,t,i)),e.isVerticesDataPresent(ys.NormalKind)&&(s.normals=e.getVerticesData(ys.NormalKind,t,i)),e.isVerticesDataPresent(ys.TangentKind)&&(s.tangents=e.getVerticesData(ys.TangentKind,t,i)),e.isVerticesDataPresent(ys.UVKind)&&(s.uvs=e.getVerticesData(ys.UVKind,t,i)),e.isVerticesDataPresent(ys.UV2Kind)&&(s.uvs2=e.getVerticesData(ys.UV2Kind,t,i)),e.isVerticesDataPresent(ys.UV3Kind)&&(s.uvs3=e.getVerticesData(ys.UV3Kind,t,i)),e.isVerticesDataPresent(ys.UV4Kind)&&(s.uvs4=e.getVerticesData(ys.UV4Kind,t,i)),e.isVerticesDataPresent(ys.UV5Kind)&&(s.uvs5=e.getVerticesData(ys.UV5Kind,t,i)),e.isVerticesDataPresent(ys.UV6Kind)&&(s.uvs6=e.getVerticesData(ys.UV6Kind,t,i)),e.isVerticesDataPresent(ys.ColorKind)&&(s.colors=e.getVerticesData(ys.ColorKind,t,i)),e.isVerticesDataPresent(ys.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(ys.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(ys.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(ys.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(ys.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(ys.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(ys.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(ys.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw vt("ribbonBuilder")}static CreateBox(e){throw vt("boxBuilder")}static CreateTiledBox(e){throw vt("tiledBoxBuilder")}static CreateTiledPlane(e){throw vt("tiledPlaneBuilder")}static CreateSphere(e){throw vt("sphereBuilder")}static CreateCylinder(e){throw vt("cylinderBuilder")}static CreateTorus(e){throw vt("torusBuilder")}static CreateLineSystem(e){throw vt("linesBuilder")}static CreateDashedLines(e){throw vt("linesBuilder")}static CreateGround(e){throw vt("groundBuilder")}static CreateTiledGround(e){throw vt("groundBuilder")}static CreateGroundFromHeightMap(e){throw vt("groundBuilder")}static CreatePlane(e){throw vt("planeBuilder")}static CreateDisc(e){throw vt("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw vt("polygonBuilder")}static CreateIcoSphere(e){throw vt("icoSphereBuilder")}static CreatePolyhedron(e){throw vt("polyhedronBuilder")}static CreateCapsule(e={orientation:de.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw vt("capsuleBuilder")}static CreateTorusKnot(e){throw vt("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=0,v=0,x=0,b=0,T=0,y=0,S=0,C=!1,E=!1,A=!1,P=!1,R=1,I=0,M=null;s&&(C=!!s.facetNormals,E=!!s.facetPositions,A=!!s.facetPartitioning,R=!0===s.useRightHandedSystem?-1:1,I=s.ratio||0,P=!!s.depthSort,M=s.distanceTo,P&&void 0===M&&(M=de.Zero()));let O=0,D=0,w=0,N=0;for(A&&s&&s.bbSize&&(O=s.subDiv.X*I/s.bbSize.x,D=s.subDiv.Y*I/s.bbSize.y,w=s.subDiv.Z*I/s.bbSize.z,N=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],cn,"_TransformVector3Coordinates",null),qe([mt.filter(((...[e])=>!Array.isArray(e)))],cn,"_TransformVector3Normals",null),qe([mt.filter(((...[e])=>!Array.isArray(e)))],cn,"_TransformVector4Normals",null),qe([mt.filter(((...[e])=>!Array.isArray(e)))],cn,"_FlipFaces",null);class un{static get ForceFullSceneLoadingForIncremental(){return un._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){un._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return un._ShowLoadingScreen}static set ShowLoadingScreen(e){un._ShowLoadingScreen=e}static get loggingLevel(){return un._LoggingLevel}static set loggingLevel(e){un._LoggingLevel=e}static get CleanBoneMatrixWeights(){return un._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){un._CleanBoneMatrixWeights=e}}un._ForceFullSceneLoadingForIncremental=!1,un._ShowLoadingScreen=!0,un._CleanBoneMatrixWeights=!1,un._LoggingLevel=0;class dn{}dn.UseOpenGLOrientationForUV=!1;class _n{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new _n(_n.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||se.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new ys(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const r=this._meshes,n=r.length;if(s===ys.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new de(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(ys.PositionKind)))return;this._extend=an(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===ys.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new cn;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(ys.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(ys.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(ys.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(ys.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(ys.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(ys.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(ys.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(ys.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(ys.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(ys.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(_n._CleanMatricesWeights(e,t),t.setVerticesData(ys.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(ys.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const r=t.getVerticesData(ys.MatricesIndicesKind),n=t.getVerticesData(ys.MatricesIndicesExtraKind),o=e.matricesWeights,a=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let e=0;el-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)o[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else h>=4?(a[e+h-4]=1-t,n[e+h-4]=s):(o[e+h]=1-t,r[e+h]=s)}t.setVerticesData(ys.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(ys.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new _n(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,bt&&bt.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new rn(de.FromArray(e.boundingBoxMinimum),de.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(ys.UVKind),e.hasUVs2&&s._delayInfo.push(ys.UV2Kind),e.hasUVs3&&s._delayInfo.push(ys.UV3Kind),e.hasUVs4&&s._delayInfo.push(ys.UV4Kind),e.hasUVs5&&s._delayInfo.push(ys.UV5Kind),e.hasUVs6&&s._delayInfo.push(ys.UV6Kind),e.hasColors&&s._delayInfo.push(ys.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(ys.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(ys.MatricesWeightsKind),s._delayLoadingFunction=cn.ImportVertexData):cn.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class pn{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new fn(e)}sampleFrame(e=zt.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class fn{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}function mn(e,t,i=!1,s){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return s&&e.set(new Int8Array(s)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return s&&e.set(new Uint8Array(s)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return s&&e.set(new Int16Array(s)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return s&&e.set(new Uint16Array(s)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return s&&e.set(new Int32Array(s)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return s&&e.set(new Uint32Array(s)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return s&&e.set(new Float32Array(s)),e}}const r=(ArrayBuffer,new Uint8Array(t));return s&&r.set(new Uint8Array(s)),r}ki.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},ki.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},ki.prototype.getAlphaMode=function(){return this._alphaMode},ki.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},ki.prototype.getAlphaEquation=function(){return this._alphaEquation},ki.prototype._readTexturePixelsSync=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return a?n||(n=mn(e.type,4*t*i)):u===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),u=c.FLOAT),o&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},ki.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,r,n,o,a,l,h))},ki.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},ki.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===s||s>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()};class gn extends ki{static get NpmPackage(){return ki.NpmPackage}static get Version(){return ki.Version}static get Instances(){return se.Instances}static get LastCreatedEngine(){return se.LastCreatedEngine}static get LastCreatedScene(){return se.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise(((i,s)=>{const r=new Image;r.onload=()=>{r.decode().then((()=>{this.createImageBitmap(r,t).then((e=>{i(e)}))}))},r.onerror=()=>{s(`Error loading image ${r.src}`)},r.src=e}))}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const s=this.createCanvas(t,i).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(e,0,0),s.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};const t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!gn.audioEngine&&this._creationOptions.audioEngine&&gn.AudioEngineFactory&&(gn.audioEngine=gn.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),Vt()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&gn._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==gn.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){this._onPointerLockChange?.()}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()}restoreStencilState(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}setDirectViewport(e,t,i,s){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise(((s,r)=>{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{r(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))}setTextureFromPostProcess(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)}setTextureFromPostProcessOutput(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures();super._rebuildTextures()}_renderFrame(){for(let e=0;e1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++gn._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()})))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new Ni(e,this._gl),o=new Pi(this,Ai.Unknown,!0);return o._hardwareTexture=n,o.baseWidth=s,o.baseHeight=r,o.width=s,o.height=r,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=r.TEXTURE_2D;e.isCube&&(h=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(h,s,a,o,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void we.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new Di(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((r,n)=>{const o=()=>{const a=s.clientWaitSync(e,t,0);a!=s.WAIT_FAILED?a!=s.TIMEOUT_EXPIRED?r():setTimeout(o,i):n()};o()}))}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,s,r,n,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===se.Instances.length&&gn.audioEngine&&(gn.audioEngine.dispose(),gn.audioEngine=null);const e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),Vt()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();const t=se.Instances.indexOf(this);t>=0&&se.Instances.splice(t,1),gn.Instances.length||se.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!Lt())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!Lt())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=gn.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){const t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}}gn.ALPHA_DISABLE=0,gn.ALPHA_ADD=1,gn.ALPHA_COMBINE=2,gn.ALPHA_SUBTRACT=3,gn.ALPHA_MULTIPLY=4,gn.ALPHA_MAXIMIZED=5,gn.ALPHA_ONEONE=6,gn.ALPHA_PREMULTIPLIED=7,gn.ALPHA_PREMULTIPLIED_PORTERDUFF=8,gn.ALPHA_INTERPOLATE=9,gn.ALPHA_SCREENMODE=10,gn.DELAYLOADSTATE_NONE=0,gn.DELAYLOADSTATE_LOADED=1,gn.DELAYLOADSTATE_LOADING=2,gn.DELAYLOADSTATE_NOTLOADED=4,gn.NEVER=512,gn.ALWAYS=519,gn.LESS=513,gn.EQUAL=514,gn.LEQUAL=515,gn.GREATER=516,gn.GEQUAL=518,gn.NOTEQUAL=517,gn.KEEP=7680,gn.REPLACE=7681,gn.INCR=7682,gn.DECR=7683,gn.INVERT=5386,gn.INCR_WRAP=34055,gn.DECR_WRAP=34056,gn.TEXTURE_CLAMP_ADDRESSMODE=0,gn.TEXTURE_WRAP_ADDRESSMODE=1,gn.TEXTURE_MIRROR_ADDRESSMODE=2,gn.TEXTUREFORMAT_ALPHA=0,gn.TEXTUREFORMAT_LUMINANCE=1,gn.TEXTUREFORMAT_LUMINANCE_ALPHA=2,gn.TEXTUREFORMAT_RGB=4,gn.TEXTUREFORMAT_RGBA=5,gn.TEXTUREFORMAT_RED=6,gn.TEXTUREFORMAT_R=6,gn.TEXTUREFORMAT_RG=7,gn.TEXTUREFORMAT_RED_INTEGER=8,gn.TEXTUREFORMAT_R_INTEGER=8,gn.TEXTUREFORMAT_RG_INTEGER=9,gn.TEXTUREFORMAT_RGB_INTEGER=10,gn.TEXTUREFORMAT_RGBA_INTEGER=11,gn.TEXTURETYPE_UNSIGNED_BYTE=0,gn.TEXTURETYPE_UNSIGNED_INT=0,gn.TEXTURETYPE_FLOAT=1,gn.TEXTURETYPE_HALF_FLOAT=2,gn.TEXTURETYPE_BYTE=3,gn.TEXTURETYPE_SHORT=4,gn.TEXTURETYPE_UNSIGNED_SHORT=5,gn.TEXTURETYPE_INT=6,gn.TEXTURETYPE_UNSIGNED_INTEGER=7,gn.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,gn.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,gn.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,gn.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,gn.TEXTURETYPE_UNSIGNED_INT_24_8=12,gn.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,gn.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,gn.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,gn.TEXTURE_NEAREST_SAMPLINGMODE=1,gn.TEXTURE_BILINEAR_SAMPLINGMODE=2,gn.TEXTURE_TRILINEAR_SAMPLINGMODE=3,gn.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,gn.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,gn.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,gn.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,gn.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,gn.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,gn.TEXTURE_NEAREST_LINEAR=7,gn.TEXTURE_NEAREST_NEAREST=1,gn.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,gn.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,gn.TEXTURE_LINEAR_LINEAR=2,gn.TEXTURE_LINEAR_NEAREST=12,gn.TEXTURE_EXPLICIT_MODE=0,gn.TEXTURE_SPHERICAL_MODE=1,gn.TEXTURE_PLANAR_MODE=2,gn.TEXTURE_CUBIC_MODE=3,gn.TEXTURE_PROJECTION_MODE=4,gn.TEXTURE_SKYBOX_MODE=5,gn.TEXTURE_INVCUBIC_MODE=6,gn.TEXTURE_EQUIRECTANGULAR_MODE=7,gn.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,gn.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,gn.SCALEMODE_FLOOR=1,gn.SCALEMODE_NEAREST=2,gn.SCALEMODE_CEILING=3,gn._RescalePostProcessFactory=null,gn._RenderPassIdCounter=0;const vn=fe.Compose(de.One(),pe.FromEulerAngles(0,Math.PI,0),de.Zero());class xn extends Ct{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&xn.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==xn.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new de(0,0,1),this._up=new de(0,1,0),this._right=new de(1,0,0),this._position=de.Zero(),this._rotation=de.Zero(),this._rotationQuaternion=null,this._scaling=de.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=xn.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=fe.Zero(),this._usePivotMatrix=!1,this._absolutePosition=de.Zero(),this._absoluteScaling=de.Zero(),this._absoluteRotationQuaternion=pe.Identity(),this._pivotMatrix=fe.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new X,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return de.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return de.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return de.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=fe.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==xn.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=fe.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||pe.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const e=ge.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),de.TransformCoordinatesFromFloatsToRef(t,i,s,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=de.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=ge.Matrix[0];return this._localMatrix.invertToRef(e),de.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=de.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=lr.LOCAL){const n=xn._LookAtVectorCache,o=r===lr.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===lr.WORLD&&this.parent)if(this.rotationQuaternion){const e=ge.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=ge.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=ge.Quaternion[0];pe.FromEulerVectorToRef(this.rotation,e);const t=ge.Matrix[0];e.toRotationMatrix(t);const i=ge.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=de.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return de.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?pe.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=lr.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==lr.WORLD){const t=ge.Matrix[0];i.invertToRef(t),e=de.TransformCoordinates(e,t)}return this.setPivotMatrix(fe.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=de.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=de.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),de.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=ge.Quaternion[0],r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Matrix[1];fe.IdentityToRef(o);const a=ge.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=xn._TmpRotation,pe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),fe.ComposeToRef(this.scaling,l,this.position,a),this.parent&&a.multiplyToRef(this.parent.computeWorldMatrix(!0),a),e&&(e.computeWorldMatrix(!0).invertToRef(o),a.multiplyToRef(o,a)),a.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(fe.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==lr.LOCAL){if(this.parent){const i=this.parent.getWorldMatrix(),s=ge.Matrix[0];i.invertToRef(s),e=de.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=pe.RotationAxisToRef(e,t,xn._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=pe.RotationAxisToRef(e,t,xn._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=pe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=ge.Vector3[0],r=ge.Vector3[1],n=ge.Vector3[2],o=ge.Quaternion[0],a=ge.Matrix[0],l=ge.Matrix[1],h=ge.Matrix[2],c=ge.Matrix[3];return e.subtractToRef(this.position,s),fe.TranslationToRef(s.x,s.y,s.z,a),fe.TranslationToRef(-s.x,-s.y,-s.z,l),fe.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(a,c),c.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&i!==lr.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=ge.Quaternion[1],pe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=ge.Quaternion[0];return pe.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==xn.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=xn._TmpScaling;let o,a=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new de(e.m[12],e.m[13],e.m[14]);a=xn._TmpTranslation,a.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(pe.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=xn._TmpRotation,pe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const e=ge.Matrix[1];fe.ScalingToRef(n.x,n.y,n.z,e);const t=ge.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,ge.Matrix[4]),ge.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else fe.ComposeToRef(n,o,a,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),ge.Matrix[7])}else ge.Matrix[7].copyFrom(r.getWorldMatrix());const e=ge.Vector3[5],t=ge.Vector3[6],i=ge.Quaternion[0];ge.Matrix[7].decompose(t,i,e),fe.ScalingToRef(t.x,t.y,t.z,ge.Matrix[7]),ge.Matrix[7].setTranslation(e),xn.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(ge.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),ge.Matrix[6]),ge.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=ge.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),ge.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&ge.Matrix[1].multiplyToRef(vn,ge.Matrix[1]),ge.Matrix[1].setTranslationFromFloats(0,0,0),ge.Matrix[1].invertToRef(ge.Matrix[0]),(this.billboardMode&xn.BILLBOARDMODE_ALL)!==xn.BILLBOARDMODE_ALL){ge.Matrix[0].decompose(void 0,ge.Quaternion[0],void 0);const e=ge.Vector3[1];ge.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&xn.BILLBOARDMODE_X)!==xn.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&xn.BILLBOARDMODE_Y)!==xn.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&xn.BILLBOARDMODE_Z)!==xn.BILLBOARDMODE_Z&&(e.z=0),fe.RotationYawPitchRollToRef(e.y,e.x,e.z,ge.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ge.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ge.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=ge.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(ge.Matrix[1]);const s=ge.Vector3[1];de.TransformCoordinatesToRef(i,ge.Matrix[1],s),s.normalize();const r=-Math.atan2(s.z,s.x)+Math.PI/2,n=Math.sqrt(s.x*s.x+s.z*s.z),o=-Math.atan2(s.y,n);if(pe.RotationYawPitchRollToRef(r,o,0,ge.Quaternion[0]),(this.billboardMode&xn.BILLBOARDMODE_ALL)!==xn.BILLBOARDMODE_ALL){const e=ge.Vector3[1];ge.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&xn.BILLBOARDMODE_X)!==xn.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&xn.BILLBOARDMODE_Y)!==xn.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&xn.BILLBOARDMODE_Z)!==xn.BILLBOARDMODE_Z&&(e.z=0),fe.RotationYawPitchRollToRef(e.y,e.x,e.z,ge.Matrix[0])}else fe.FromQuaternionToRef(ge.Quaternion[0],ge.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ge.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ge.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=fe.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew xn(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew xn(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(fe.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(fe.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof xn)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}xn.BILLBOARDMODE_NONE=0,xn.BILLBOARDMODE_X=1,xn.BILLBOARDMODE_Y=2,xn.BILLBOARDMODE_Z=4,xn.BILLBOARDMODE_ALL=7,xn.BILLBOARDMODE_USE_POSITION=128,xn.BillboardUseParentOrientation=!1,xn._TmpRotation=pe.Zero(),xn._TmpScaling=de.Zero(),xn._TmpTranslation=de.Zero(),xn._LookAtVectorCache=new de(0,0,0),xn._RotationAxisCache=new pe,qe([lt("position")],xn.prototype,"_position",void 0),qe([lt("rotation")],xn.prototype,"_rotation",void 0),qe([_t("rotationQuaternion")],xn.prototype,"_rotationQuaternion",void 0),qe([lt("scaling")],xn.prototype,"_scaling",void 0),qe([st("billboardMode")],xn.prototype,"_billboardMode",void 0),qe([st()],xn.prototype,"scalingDeterminant",void 0),qe([st("infiniteDistance")],xn.prototype,"_infiniteDistance",void 0),qe([st()],xn.prototype,"ignoreNonUniformScaling",void 0),qe([st()],xn.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class bn{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new de(0,0,0),this._diffPositionForCollisions=new de(0,0,0),this._collisionResponse=!0}}class Tn{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=de.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class yn{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Tn,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new bn,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Sn extends xn{static get BILLBOARDMODE_NONE(){return xn.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return xn.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return xn.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return xn.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return xn.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return xn.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return!!super._updateNonUniformScalingState(e)&&(this._markSubMeshesAsMiscDirty(),!0)}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new yn,this._waitingMaterialId=null,this.cullingStrategy=Sn.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new X,this.onCollisionPositionChangeObservable=new X,this.onMaterialChangedObservable=new X,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Ce.Red(),this.outlineWidth=.02,this.overlayColor=Ce.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new de(.5,1,.5),this.ellipsoidOffset=new de(0,0,0),this.edgesWidth=1,this.edgesColor=new Ee(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new X,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>gn.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new bs(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case ar.Aggressive:this.doNotSyncBoundingInfo=!0;case ar.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==xn.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new rn(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(ys.MatricesIndicesKind)&&this.isVerticesDataPresent(ys.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===xn.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new fe;(this.rotationQuaternion?this.rotationQuaternion:pe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=de.Zero(),n=this.definedFacingForward?-1:1;return de.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,s,r),r}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new de(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=an(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new rn(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=r?this.getVerticesData(ys.MatricesIndicesExtraKind):null,o=r?this.getVerticesData(ys.MatricesWeightsExtraKind):null,a=this.skeleton.getTransformMatrices(this),l=ge.Vector3[0],h=ge.Matrix[0],c=ge.Matrix[1];let u=0;for(let d=0;d0&&(fe.FromFloat32ArrayToRefScaled(a,Math.floor(16*e[u+_]),p,c),h.addToSelf(c));if(r)for(_=0;_<4;_++)p=o[u+_],p>0&&(fe.FromFloat32ArrayToRefScaled(a,Math.floor(16*n[u+_]),p,c),h.addToSelf(c));s===ys.NormalKind?de.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):de.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),s===ys.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,ys.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,ys.PositionKind)}_getPositionData(e,t){let i=this.getVerticesData(ys.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let r=i;r1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=ge.Matrix[0],i=ge.Matrix[1];return fe.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const o=new Ss,a=this.getClassName(),l="InstancedLinesMesh"===a||"LinesMesh"===a||"GreasedLineMesh"===a?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return o;if(!(n||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:de.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let _=!1;for(let e=0;e1&&!n&&!r.canIntersects(e))continue;const o=r.intersects(e,this._positions,this.getIndices(),t,i);if(o&&(t||!c||o.distancee!==this&&e.actionManager===this.actionManager))||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:de.Zero()}e.depthSortedFacets=[];for(let t=0;tK?r.maximum.x-r.minimum.x:K,e.bbSize.y=r.maximum.y-r.minimum.y>K?r.maximum.y-r.minimum.y:K,e.bbSize.z=r.maximum.z-r.minimum.z>K?r.maximum.z-r.minimum.z:K;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),de.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&cn.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;sr.subDiv.max||o<0||o>r.subDiv.max||a<0||a>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),a=ge.Matrix[5];o.invertToRef(a);const l=ge.Vector3[8];de.TransformCoordinatesFromFloatsToRef(e,t,i,a,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,s,r,n);return s&&de.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),h}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0;const f=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,x,b,T=Number.MAX_VALUE,y=T;for(let S=0;S=0||r&&!n&&c<=0)&&(c=x.x*b.x+x.y*b.y+x.z*b.z,u=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*u,_=t+x.y*u,p=i+x.z*u,a=d-e,l=_-t,h=p-i,y=a*a+l*l+h*h,ye.emitter===this))}}Sn.OCCLUSION_TYPE_NONE=0,Sn.OCCLUSION_TYPE_OPTIMISTIC=1,Sn.OCCLUSION_TYPE_STRICT=2,Sn.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Sn.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Sn.CULLINGSTRATEGY_STANDARD=0,Sn.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Sn.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Sn.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,ee("BABYLON.AbstractMesh",Sn);class Cn{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){yt.Clone((()=>e),this)}serialize(){return yt.Serialize(this)}parse(e,t,i){yt.Parse((()=>this),e,t,i)}}var En;function An(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function Pn(e,t,i){const s=!!(e.clipPlane??t.clipPlane),r=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),a=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);s&&i.push("#define CLIPPLANE"),r&&i.push("#define CLIPPLANE2"),n&&i.push("#define CLIPPLANE3"),o&&i.push("#define CLIPPLANE4"),a&&i.push("#define CLIPPLANE5"),l&&i.push("#define CLIPPLANE6")}function Rn(e,t,i){let s=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),o=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,s=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,s=!0),i.CLIPPLANE3!==o&&(i.CLIPPLANE3=o,s=!0),i.CLIPPLANE4!==a&&(i.CLIPPLANE4=a,s=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,s=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,s=!0),s}function In(e,t,i){let s=t.clipPlane??i.clipPlane;Mn(e,"vClipPlane",s),s=t.clipPlane2??i.clipPlane2,Mn(e,"vClipPlane2",s),s=t.clipPlane3??i.clipPlane3,Mn(e,"vClipPlane3",s),s=t.clipPlane4??i.clipPlane4,Mn(e,"vClipPlane4",s),s=t.clipPlane5??i.clipPlane5,Mn(e,"vClipPlane5",s),s=t.clipPlane6??i.clipPlane6,Mn(e,"vClipPlane6",s)}function Mn(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}qe([st()],Cn.prototype,"func",null),qe([st()],Cn.prototype,"funcRef",null),qe([st()],Cn.prototype,"funcMask",null),qe([st()],Cn.prototype,"opStencilFail",null),qe([st()],Cn.prototype,"opDepthFail",null),qe([st()],Cn.prototype,"opStencilDepthPass",null),qe([st()],Cn.prototype,"mask",null),qe([st()],Cn.prototype,"enabled",null),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(En||(En={}));const On=Ce.Black(),Dn={NUM_MORPH_INFLUENCERS:0};function wn(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;1===e.mode&&we.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function Nn(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(On,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",On)):i.setColor3("vFogColor",e.fogColor))}function Fn(e,t,i){Dn.NUM_MORPH_INFLUENCERS=i,Bn(e,t,Dn)}function Bn(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&se.LastCreatedEngine){const r=se.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const o=n&&n.supportsNormals&&i.NORMAL,a=n&&n.supportsTangents&&i.TANGENT,l=n&&n.supportsUVs&&i.UV1;for(let i=0;ir&&we.Error("Cannot add more vertex attributes for mesh "+t.name)}}function Ln(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function kn(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function Vn(e,t){t.bindToEffect(e,"Scene")}function Un(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function Gn(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function zn(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function Wn(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=n,i.previousBones[e.uniqueId].set(s)))}}}function Hn(e,t,i){e.transferToEffect(t,i+"")}function Xn(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}function Yn(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let r=0;r0&&(s.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}function jn(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&Ln(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}function Kn(e,t,i=4,s=0){let r=0;for(let n=0;n0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}function $n(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}function qn(e,t,i,s,r,n,o,a=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=s,o.FOG=r&&$n(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=a)}function Zn(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(Jn(e,t,n,o,i,s,a),o++,o===r)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e0&&(o.shadowEnabled=!0,t.prepareDefines(r,s))}}i.lightmapMode!=nr.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==nr.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}function eo(e,t,i,s,r,n=null,o=!1){let a=lo(e,s);!1!==n&&(a=Rn(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,a=!0),s.INSTANCES!==r&&(s.INSTANCES=r,a=!0),s.THIN_INSTANCES!==o&&(s.THIN_INSTANCES=o,a=!0),a&&s.markAsUnprocessed()}function to(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function io(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function so(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function ro(e,t,i,s,r=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&to(e,t),r&&io(e,t),o&&so(e,t),!0}function no(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function oo(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,s===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function ao(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||se.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||hs.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Fi(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=uo.ClockWiseSideOrientation:this.sideOrientation=uo.CounterClockWiseSideOrientation,this._uniformBuffer=new bs(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),uo.OnEventObservable.notifyObservers(this,En.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===uo.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===uo.MATERIAL_OPAQUE||this._transparencyMode===uo.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(uo.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===uo.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(En.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,Vn(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(En.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(En.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(En.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),uo._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new ir(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new ln(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,n&&s&&s(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);r.clipPlane&&(n.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(uo._DirtyCallbackArray.length=0,e&uo.TextureDirtyFlag&&uo._DirtyCallbackArray.push(uo._TextureDirtyCallBack),e&uo.LightDirtyFlag&&uo._DirtyCallbackArray.push(uo._LightsDirtyCallBack),e&uo.FresnelDirtyFlag&&uo._DirtyCallbackArray.push(uo._FresnelDirtyCallBack),e&uo.AttributesDirtyFlag&&uo._DirtyCallbackArray.push(uo._AttributeDirtyCallBack),e&uo.MiscDirtyFlag&&uo._DirtyCallbackArray.push(uo._MiscDirtyCallBack),e&uo.PrePassDirtyFlag&&uo._DirtyCallbackArray.push(uo._PrePassDirtyCallBack),uo._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(uo._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(uo._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(uo._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(uo._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(uo._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(uo._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(uo._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(uo._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(uo._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(uo._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(uo._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==ar.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(En.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=yt.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return we.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=hs.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let o=t.pluginManager?.getPlugin(n.name);if(!o){const e=hs.Instantiate("BABYLON."+r);e&&(o=new e(t))}o?.parse(n,i,s)}}}uo.TriangleFillMode=0,uo.WireFrameFillMode=1,uo.PointFillMode=2,uo.PointListDrawMode=3,uo.LineListDrawMode=4,uo.LineLoopDrawMode=5,uo.LineStripDrawMode=6,uo.TriangleStripDrawMode=7,uo.TriangleFanDrawMode=8,uo.ClockWiseSideOrientation=0,uo.CounterClockWiseSideOrientation=1,uo.TextureDirtyFlag=1,uo.LightDirtyFlag=2,uo.FresnelDirtyFlag=4,uo.AttributesDirtyFlag=8,uo.MiscDirtyFlag=16,uo.PrePassDirtyFlag=32,uo.AllDirtyFlag=63,uo.MATERIAL_OPAQUE=0,uo.MATERIAL_ALPHATEST=1,uo.MATERIAL_ALPHABLEND=2,uo.MATERIAL_ALPHATESTANDBLEND=3,uo.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,uo.MATERIAL_NORMALBLENDMETHOD_RNM=1,uo.OnEventObservable=new X,uo._AllDirtyCallBack=e=>e.markAllAsDirty(),uo._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),uo._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),uo._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),uo._MiscDirtyCallBack=e=>e.markAsMiscDirty(),uo._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),uo._LightsDirtyCallBack=e=>e.markAsLightDirty(),uo._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),uo._FresnelAndMiscDirtyCallBack=e=>{uo._FresnelDirtyCallBack(e),uo._MiscDirtyCallBack(e)},uo._TextureAndMiscDirtyCallBack=e=>{uo._TextureDirtyCallBack(e),uo._MiscDirtyCallBack(e)},uo._DirtyCallbackArray=[],uo._RunDirtyCallBacks=e=>{for(const t of uo._DirtyCallbackArray)t(e)},qe([st()],uo.prototype,"id",void 0),qe([st()],uo.prototype,"uniqueId",void 0),qe([st()],uo.prototype,"name",void 0),qe([st()],uo.prototype,"metadata",void 0),qe([st()],uo.prototype,"checkReadyOnEveryCall",void 0),qe([st()],uo.prototype,"checkReadyOnlyOnce",void 0),qe([st()],uo.prototype,"state",void 0),qe([st("alpha")],uo.prototype,"_alpha",void 0),qe([st("backFaceCulling")],uo.prototype,"_backFaceCulling",void 0),qe([st("cullBackFaces")],uo.prototype,"_cullBackFaces",void 0),qe([st()],uo.prototype,"sideOrientation",void 0),qe([st("alphaMode")],uo.prototype,"_alphaMode",void 0),qe([st()],uo.prototype,"_needDepthPrePass",void 0),qe([st()],uo.prototype,"disableDepthWrite",void 0),qe([st()],uo.prototype,"disableColorWrite",void 0),qe([st()],uo.prototype,"forceDepthWrite",void 0),qe([st()],uo.prototype,"depthFunction",void 0),qe([st()],uo.prototype,"separateCullingPass",void 0),qe([st("fogEnabled")],uo.prototype,"_fogEnabled",void 0),qe([st()],uo.prototype,"pointSize",void 0),qe([st()],uo.prototype,"zOffset",void 0),qe([st()],uo.prototype,"zOffsetUnits",void 0),qe([st()],uo.prototype,"pointsCloud",null),qe([st()],uo.prototype,"fillMode",null),qe([st()],uo.prototype,"useLogarithmicDepth",null),qe([st()],uo.prototype,"transparencyMode",null);class _o extends uo{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new _o(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,bt&&bt.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}ee("BABYLON.MultiMaterial",_o);class po{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class fo{}class mo{constructor(){this.visibleInstances={},this.batchCache=new go,this.batchCacheReplacementModeInFrozenMode=new go,this.instancesBufferSize=2048}}class go{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class vo{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class xo{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class bo extends Sn{static _GetDefaultSideOrientation(e){return e||bo.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(ys.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(ys.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new X),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new X),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new X),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new X),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new X),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new xo,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new mo,this._thinInstanceDataStorage=new vo,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=bo.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),Xe.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,bt&&bt.HasTags(s)&&bt.AddTagsTo(this,bt.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const t=s.getDescendants(!0);for(let i=0;i{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new X(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return we.Warn("You cannot use a mesh as LOD level twice"),this;const i=new po(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;io*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const o=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new ln(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)ln.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new cn;s.set(t,e);const r=this.getScene();new _n(_n.RandomId(),r,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=_n.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(ys.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(ys.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(ys.NormalKind);if(!t)return this;cn.ComputeNormals(i,e,t),this.updateVerticesData(ys.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(_n.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new _n(_n.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new cn;t.indices=e;const s=this.getScene();new _n(_n.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case uo.PointFillMode:n=null;break;case uo.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case uo.TriangleFillMode:n=this._geometry.getIndexBuffer()}return s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==uo.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==uo.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),o=s?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&o&&(n.visibleInstances[e]=t[o])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],o=n?n.length:0,a=this._instanceDataStorage,l=a.instancesBufferSize;let h=a.instancesBuffer,c=a.instancesPreviousBuffer;const u=16*(o+1)*4;for(;a.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const o=s.getEngine();let a=0,l=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(a=s.activeCamera.maxZ,l=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let _;t&&o.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),_=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const p=_?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,n,p);if(!_||!p)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;const f=i||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=f._getWorldMatrixDeterminant();m=this.overrideMaterialSideOrientation,null==m&&(m=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(m=m===uo.ClockWiseSideOrientation?uo.CounterClockWiseSideOrientation:uo.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(_,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&o.setDepthWrite(!0);const v=this._internalMeshDataInfo._effectiveMaterial,x=v.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,p,x,!1);const b=f.getWorldMatrix();v._storeEffectOnSubMeshes?v.bindForSubMesh(b,this,e):v.bind(b,this),!v.backFaceCulling&&v.separateCullingPass&&(o.setState(!0,v.zOffset,!1,!g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),o.setState(!0,v.zOffset,!1,g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,n,p);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=a,s.updateTransformMatrix(!0)),s.performancePriority!==ar.Aggressive||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(ys.MatricesWeightsKind)&&(this.isVerticesDataPresent(ys.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(ys.MatricesWeightsKind),t=e.length;for(let i=0;ii&&s++,0!==n&&u++,c+=n,i=n}if(l[u]++,u>n&&(n=u),0===c)r++;else{const i=1/c;let s=0;for(let r=0;r.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(ys.MatricesIndicesKind),u=this.getVerticesData(ys.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===r&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return hs.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(ys.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(ys.PositionKind);const s=de.Zero();let r;for(r=0;r{const a=e.width,l=e.height,h=this.getEngine().createCanvas(a,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,a,l).data;this.applyDisplacementMapFromBuffer(c,a,l,t,i,r,n,o),s&&s(this)}),a||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,a=!1){if(!this.isVerticesDataPresent(ys.PositionKind)||!this.isVerticesDataPresent(ys.NormalKind)||!this.isVerticesDataPresent(ys.UVKind))return we.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(ys.PositionKind,!0,!0),h=this.getVerticesData(ys.NormalKind),c=this.getVerticesData(ys.UVKind);let u=de.Zero();const d=de.Zero(),_=ue.Zero();n=n||ue.Zero(),o=o||new ue(1,1);for(let a=0;a{const s=new Float32Array(i.length*t);let r=0;for(let n=0;n{const t=s.length-1-e,i=s[t];for(let e=0;e{for(let e=0;e-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=a?this.getVerticesData(ys.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(ys.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=de.Zero(),d=new fe,_=new fe;let p,f=0;for(let e=0;e0&&(fe.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[f+p]),m,_),d.addToSelf(_));if(a)for(p=0;p<4;p++)m=h[f+p],m>0&&(fe.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[f+p]),m,_),d.addToSelf(_));de.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(s,e),t&&(de.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(ys.PositionKind,s),t&&this.updateVerticesData(ys.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:de.Zero(),max:de.Zero()}}static Center(e){const t=e instanceof Array?bo.MinMax(e):e;return de.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return Hr(bo._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return Xr(bo._MergeMeshesCoroutine(e,t,i,s,r,n,!0),zr())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a=65536)return we.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const l=new Array,h=new Array,c=new Array,u=e[0].overrideMaterialSideOrientation;for(a=0;a{const t=e.computeWorldMatrix(!0);return{vertexData:cn.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:p,transform:f}=_(d);o&&(yield);const m=new Array(e.length-1);for(let t=1;t{throw vt("GroundMesh")},bo._GoldbergMeshParser=(e,t)=>{throw vt("GoldbergMesh")},bo._LinesMeshParser=(e,t)=>{throw vt("LinesMesh")},bo._GreasedLineMeshParser=(e,t)=>{throw vt("GreasedLineMesh")},bo._GreasedLineRibbonMeshParser=(e,t)=>{throw vt("GreasedLineRibbonMesh")},bo._TrailMeshParser=(e,t)=>{throw vt("TrailMesh")},ee("BABYLON.Mesh",bo),bo._instancedMeshFactory=(e,t)=>{const i=new To(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class To extends Sn{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&hs.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&hs.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&hs.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&hs.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&we.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||we.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==xn.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new fe);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,ge.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(ge.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=yo.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=yt.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=yt.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((t=>{e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((t=>{e.includedOnlyMeshesIds.push(t.id)}))),yt.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return Ct.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=yo.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=yt.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._resyncMeshes(),r},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===yo.INTENSITYMODE_AUTOMATIC&&(i=t===yo.LIGHTTYPEID_DIRECTIONALLIGHT?yo.INTENSITYMODE_ILLUMINANCE:yo.INTENSITYMODE_LUMINOUSINTENSITY),t){case yo.LIGHTTYPEID_POINTLIGHT:case yo.LIGHTTYPEID_SPOTLIGHT:switch(i){case yo.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case yo.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case yo.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case yo.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case yo.INTENSITYMODE_ILLUMINANCE:e=1;break;case yo.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case yo.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}yo.FALLOFF_DEFAULT=nr.FALLOFF_DEFAULT,yo.FALLOFF_PHYSICAL=nr.FALLOFF_PHYSICAL,yo.FALLOFF_GLTF=nr.FALLOFF_GLTF,yo.FALLOFF_STANDARD=nr.FALLOFF_STANDARD,yo.LIGHTMAP_DEFAULT=nr.LIGHTMAP_DEFAULT,yo.LIGHTMAP_SPECULAR=nr.LIGHTMAP_SPECULAR,yo.LIGHTMAP_SHADOWSONLY=nr.LIGHTMAP_SHADOWSONLY,yo.INTENSITYMODE_AUTOMATIC=nr.INTENSITYMODE_AUTOMATIC,yo.INTENSITYMODE_LUMINOUSPOWER=nr.INTENSITYMODE_LUMINOUSPOWER,yo.INTENSITYMODE_LUMINOUSINTENSITY=nr.INTENSITYMODE_LUMINOUSINTENSITY,yo.INTENSITYMODE_ILLUMINANCE=nr.INTENSITYMODE_ILLUMINANCE,yo.INTENSITYMODE_LUMINANCE=nr.INTENSITYMODE_LUMINANCE,yo.LIGHTTYPEID_POINTLIGHT=nr.LIGHTTYPEID_POINTLIGHT,yo.LIGHTTYPEID_DIRECTIONALLIGHT=nr.LIGHTTYPEID_DIRECTIONALLIGHT,yo.LIGHTTYPEID_SPOTLIGHT=nr.LIGHTTYPEID_SPOTLIGHT,yo.LIGHTTYPEID_HEMISPHERICLIGHT=nr.LIGHTTYPEID_HEMISPHERICLIGHT,qe([nt()],yo.prototype,"diffuse",void 0),qe([nt()],yo.prototype,"specular",void 0),qe([st()],yo.prototype,"falloffType",void 0),qe([st()],yo.prototype,"intensity",void 0),qe([st()],yo.prototype,"range",null),qe([st()],yo.prototype,"intensityMode",null),qe([st()],yo.prototype,"radius",null),qe([st()],yo.prototype,"_renderPriority",void 0),qe([it("_reorderLightsInScene")],yo.prototype,"renderPriority",void 0),qe([st("shadowEnabled")],yo.prototype,"_shadowEnabled",void 0),qe([st("excludeWithLayerMask")],yo.prototype,"_excludeWithLayerMask",void 0),qe([st("includeOnlyWithLayerMask")],yo.prototype,"_includeOnlyWithLayerMask",void 0),qe([st("lightmapMode")],yo.prototype,"_lightmapMode",void 0);class So extends G{}class Co{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach((e=>{e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0}}class Eo extends G{constructor(e){super(),this._wasAddedToScene=!1,(e=e||se.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,r=i.dependsOn.get(e);if(s instanceof To){const n=s.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const r of s.getDescendants()){const s=r.uniqueId;t.has(s)&&(n.add(s),i.dependsOn.get(s).add(e))}}const s=[],r=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(r.push(s),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();s.push(e);const r=i.dependedBy.get(e.uniqueId);for(const s of Array.from(r.values())){const r=i.dependsOn.get(s);r.delete(e.uniqueId),0===r.size&&t.get(s)&&(n.push(t.get(s)),t.delete(s))}}return t.size>0&&(we.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>we.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof Sn&&-1!==this.meshes.indexOf(e)||e instanceof xn&&-1!==this.transformNodes.indexOf(e)||e instanceof yo&&-1!==this.lights.indexOf(e)||e instanceof Kr&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return we.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return we.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return we.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return we.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||hs.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new Co,o=[],a=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,o)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof bo){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&r[s[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[s[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===o.parent&&n.rootNodes.push(o)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=s[i.uniqueId],o=("number"==typeof n?r[n]:i).createInstance(t.name);d(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[s[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[s[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||hs.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach((i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))})),this.lights.forEach((i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))})),this.meshes.forEach((i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||hs.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const s of e){let e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new So);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new bo("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=se.LastCreatedScene,t,i=null){if(!e)return we.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof bo?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof xn?this.transformNodes.push(e):e instanceof yo?this.lights.push(e):e instanceof Kr&&this.cameras.push(e),e instanceof Sn){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class Ao{constructor(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},(e=e||se.LastCreatedScene)&&(this._scene=e,gn.audioEngine?(this._audioEngine=gn.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))):hs.Warn("No audio engine initialized, failed to create an audio analyser"))}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;tnew Po(e,t,i);class Po{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new X,this.onAudioLockedObservable=new X,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!Lt())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContext(){return this._audioContext?.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,we.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)})).catch((()=>{this._tryToRun=!1,this.unlocked=!1})))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const e=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this.unlock()}),!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class Ro{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if(gn.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:gn.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,s=null,r){if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new X,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=de.Zero(),this._localDirection=new de(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,i=i||se.LastCreatedScene)if(this._scene=i,Ro._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(e,t,i,s,r)=>t0&&(s=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&we.Error("XHR "+e.status+" error on: "+t+"."),we.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?s||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):we.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){we.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),gn.audioEngine&&!gn.audioEngine.WarnedWebAudioUnsupported&&(we.Error("Web Audio is not supported by your browser."),gn.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){gn.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){gn.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){gn.audioEngine?.audioContext&&gn.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{we.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){gn.audioEngine?.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){gn.audioEngine?.canUseWebAudio&&gn.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??gn.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){gn.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){gn.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(gn.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{gn.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=gn.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=gn.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const r=()=>{if(gn.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=gn.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},s=e?gn.audioEngine?.audioContext.currentTime+e:gn.audioEngine.audioContext.currentTime;const r=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(s,r,this.loop?void 0:i)}}};"suspended"===gn.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===gn.audioEngine?.audioContext.state?(gn.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=gn.audioEngine.onAudioUnlockedObservable.addOnce((()=>{r()})))):r()}),500):r()}this._startTime=s,this.isPlaying=!0,this.isPaused=!1}catch(e){we.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(gn.audioEngine?.audioContext&&this._soundSource){const t=e?gn.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):gn.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=gn.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){gn.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&gn.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(gn.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,gn.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,gn.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);gn.audioEngine?.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Ro(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,s){const r=e.name;let n;n=e.url?i+e.url:i+r;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let a;if(s){const e=()=>{s._isReadyToPlay?(a._audioBuffer=s.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(e,300)};a=new Ro(r,new ArrayBuffer(0),t,null,o),e()}else a=new Ro(r,n,t,(()=>{t.removePendingData(a)}),o),t.addPendingData(a);if(e.position){const t=de.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=de.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(gn.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Ro._SceneComponentInitialization=e=>{throw vt("AudioSceneComponent")};class Io{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||se.LastCreatedScene)&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){gn.audioEngine?.canUseWebAudio&&gn.audioEngine.audioContext&&(this._outputAudioNode=gn.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(gn.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(gn.audioEngine&&gn.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){this._isInitialized||this._initializeSoundTrackAudioGraph(),gn.audioEngine?.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){gn.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){if(gn.audioEngine?.canUseWebAudio)for(let e=0;e{let r,n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,a=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),de.TransformNormalToRef(Mo._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(Rs.NAME_AUDIO);t||(t=new Mo(e),e._addComponent(t))};class Oo{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let s=0;for(const e of i)s+=e;const r=s>0?1/s:0;for(let e=0;e{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee),this)}serialize(){return yt.Serialize(this)}parse(e,t,i){yt.Parse((()=>this),e,t,i)}}qe([rt(),it("_markSubMeshesAsAttributesDirty")],Do.prototype,"texture",void 0),qe([st(),it("_markSubMeshesAsAttributesDirty")],Do.prototype,"isEnabled",void 0),qe([st()],Do.prototype,"animationParameters",void 0),qe([st()],Do.prototype,"time",void 0);class wo{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return!!this._texture&&this._texture.isCube}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Et.Zero(),this._cachedBaseSize=Et.Zero(),this._initialSamplingMode=2,this._texture=wo._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class No extends wo{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=ns()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=No.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new X,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?No._IsScene(e)?this._scene=e:this._engine=e:this._scene=se.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return fe.IdentityReadOnly}getReflectionTextureMatrix(){return fe.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!r,t),l=o.getLoadedTexturesCache();for(let o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=yt.Serialize(this);return yt.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Fo(e,t,i=!1){const s=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const n=document.createElement("canvas");n.width=s,n.height=r;const o=n.getContext("2d");if(!o)return null;const a=o.createImageData(s,r);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function Bo(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?Fo(r,e.getSize(),s.invertY):null}async function Lo(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?Fo(r,e.getSize(),s.invertY):null}No.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,qe([st()],No.prototype,"uniqueId",void 0),qe([st()],No.prototype,"name",void 0),qe([st()],No.prototype,"metadata",void 0),qe([st("hasAlpha")],No.prototype,"_hasAlpha",void 0),qe([st("getAlphaFromRGB")],No.prototype,"_getAlphaFromRGB",void 0),qe([st()],No.prototype,"level",void 0),qe([st("coordinatesIndex")],No.prototype,"_coordinatesIndex",void 0),qe([st()],No.prototype,"optimizeUVAllocation",void 0),qe([st("coordinatesMode")],No.prototype,"_coordinatesMode",void 0),qe([st()],No.prototype,"wrapU",null),qe([st()],No.prototype,"wrapV",null),qe([st()],No.prototype,"wrapR",void 0),qe([st()],No.prototype,"anisotropicFilteringLevel",void 0),qe([st()],No.prototype,"isCube",null),qe([st()],No.prototype,"is3D",null),qe([st()],No.prototype,"is2DArray",null),qe([st()],No.prototype,"gammaSpace",null),qe([st()],No.prototype,"invertZ",void 0),qe([st()],No.prototype,"lodLevelInAlpha",void 0),qe([st()],No.prototype,"lodGenerationOffset",null),qe([st()],No.prototype,"lodGenerationScale",null),qe([st()],No.prototype,"linearSpecularLOD",null),qe([rt()],No.prototype,"irradianceTexture",null),qe([st()],No.prototype,"isRenderTarget",void 0);const ko={GenerateBase64StringFromPixelData:Fo,GenerateBase64StringFromTexture:Bo,GenerateBase64StringFromTextureAsync:Lo};class Vo extends No{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=Vo.TRILINEAR_SAMPLINGMODE,o={},a,l=5){throw vt("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,r=Vo.TRILINEAR_SAMPLINGMODE,n=null,o=null,a=null,l=!1,h,c,u,d,_){let p;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new X,this._isBlocking=!0,this.name=e||"",this.url=e;let f=!1,m=null,g=!0;"object"==typeof i&&null!==i?(p=i.noMipmap??!1,s=i.invertY??!dn.UseOpenGLOrientationForUV,r=i.samplingMode??Vo.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,o=i.onError??null,a=i.buffer??null,l=i.deleteBuffer??!1,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,f=i.useSRGBBuffer??!1,m=i.internalTexture??null,g=i.gammaSpace??g):p=!!i,this._gammaSpace=g,this._noMipmap=p,this._invertY=void 0===s?!dn.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=a,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=f,this._forcedExtension=_,h&&(this._format=h);const v=this.getScene(),x=this._getEngine();if(!x)return;x.onBeforeTextureInitObservable.notifyObservers(this);const b=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&v&&v.resetCachedMaterial()},T=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},o&&o(e,t),Vo.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m)return this._delayedOnLoad=b,void(this._delayedOnError=T);if(this._texture=m??this._getFromCache(this.url,p,r,this._invertY,f,this.isCube),this._texture)if(this._texture.isReady)Vi.SetImmediate((()=>b()));else{const e=this._texture.onLoadedObservable.add(b);this._texture.onErrorObservable.add((t=>{T(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(v&&v.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=b,this._delayedOnError=T;else{try{this._texture=x.createTexture(this.url,p,this._invertY,v,r,b,T,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,f)}catch(e){throw T("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Vi.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,de.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=fe.Zero(),this._rowGenerationMatrix=new fe,this._t0=de.Zero(),this._t1=de.Zero(),this._t2=de.Zero()),fe.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(fe.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,ge.Matrix[0]),fe.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,ge.Matrix[1]),fe.ScalingToRef(this._cachedUScale,this._cachedVScale,0,ge.Matrix[2]),fe.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,ge.Matrix[3]),ge.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ge.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ge.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ge.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),fe.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==Vo.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=fe.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=fe.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case Vo.PLANAR_MODE:fe.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case Vo.PROJECTION_MODE:{fe.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:fe.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return yt.Clone((()=>new Vo(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;Vo.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(Vo._SerializeInternalTextureUniqueId);return t?((Vo.SerializeBuffers||Vo.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+qt(this._buffer):(Vo.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Bo(this):Lo(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,Vo._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=rs.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return Vo._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=Vo._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=ir.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(o)}),e._creationFlags??0,e._useSRGBBuffer??!1),o.name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||Vo.UseSerializedUrlIfAny)&&(a=e.url);const l={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(o)},internalTexture:r};o=new Vo(a,t,l)}return o}}),e,t);return o}static CreateFromBase64String(e,t,i,s,r,n=Vo.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h,c){return new Vo("data:"+t,i,s,r,n,o,a,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=Vo.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Vo(e,i,r,n,o,a,l,t,s,h,void 0,void 0,c,u)}}function Uo(e,t,i,s){let r,n=1;1===s?r=new Float32Array(t*i*4):2===s?(r=new Uint16Array(t*i*4),n=15360):r=7===s?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let s=0;s{throw vt("CubeTexture")},Vo._CreateMirror=(e,t,i,s)=>{throw vt("MirrorTexture")},Vo._CreateRenderTargetTexture=(e,t,i,s,r)=>{throw vt("RenderTargetTexture")},Vo.NEAREST_SAMPLINGMODE=1,Vo.NEAREST_NEAREST_MIPLINEAR=8,Vo.BILINEAR_SAMPLINGMODE=2,Vo.LINEAR_LINEAR_MIPNEAREST=11,Vo.TRILINEAR_SAMPLINGMODE=3,Vo.LINEAR_LINEAR_MIPLINEAR=3,Vo.NEAREST_NEAREST_MIPNEAREST=4,Vo.NEAREST_LINEAR_MIPNEAREST=5,Vo.NEAREST_LINEAR_MIPLINEAR=6,Vo.NEAREST_LINEAR=7,Vo.NEAREST_NEAREST=1,Vo.LINEAR_NEAREST_MIPNEAREST=9,Vo.LINEAR_NEAREST_MIPLINEAR=10,Vo.LINEAR_LINEAR=2,Vo.LINEAR_NEAREST=12,Vo.EXPLICIT_MODE=0,Vo.SPHERICAL_MODE=1,Vo.PLANAR_MODE=2,Vo.CUBIC_MODE=3,Vo.PROJECTION_MODE=4,Vo.SKYBOX_MODE=5,Vo.INVCUBIC_MODE=6,Vo.EQUIRECTANGULAR_MODE=7,Vo.FIXED_EQUIRECTANGULAR_MODE=8,Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Vo.CLAMP_ADDRESSMODE=0,Vo.WRAP_ADDRESSMODE=1,Vo.MIRROR_ADDRESSMODE=2,Vo.UseSerializedUrlIfAny=!1,qe([st()],Vo.prototype,"url",void 0),qe([st()],Vo.prototype,"uOffset",void 0),qe([st()],Vo.prototype,"vOffset",void 0),qe([st()],Vo.prototype,"uScale",void 0),qe([st()],Vo.prototype,"vScale",void 0),qe([st()],Vo.prototype,"uAng",void 0),qe([st()],Vo.prototype,"vAng",void 0),qe([st()],Vo.prototype,"wAng",void 0),qe([st()],Vo.prototype,"uRotationCenter",void 0),qe([st()],Vo.prototype,"vRotationCenter",void 0),qe([st()],Vo.prototype,"wRotationCenter",void 0),qe([st()],Vo.prototype,"homogeneousRotationInUVTransform",void 0),qe([st()],Vo.prototype,"isBlocking",null),ee("BABYLON.Texture",Vo),yt._TextureParser=Vo.Parse,ki.prototype.updateRawTexture=function(e,t,i,s,r=null,n=0,o=!1){if(!e)return;const a=this._getRGBABufferInternalSizedFormat(n,i,o),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=s,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},ki.prototype.createRawTexture=function(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new Pi(this,Ai.Raw);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(o,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},ki.prototype.createRawCubeTexture=function(e,t,i,s,r,n,o,a=null){const l=this._gl,h=new Pi(this,Ai.CubeRaw);h.isCube=!0,h.format=i,h.type=s,this._doNotHandleContextLost||(h._bufferViewArray=e);const c=this._getWebGLTextureType(s);let u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,we.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,we.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,o=1,we.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,o=1,we.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const d=t,_=d;if(h.width=d,h.height=_,h.invertY=n,h._compression=a,!this.needPOTTextures||as(h.width)&&as(h.height)||(r=!1),e)this.updateRawCubeTexture(h,e,i,s,n,a);else{const e=this._getRGBABufferInternalSizedFormat(s),t=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let i=0;i<6;i++)a?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[a],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const p=this._getSamplingParameters(o,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=r,h.samplingMode=o,h.isReady=!0,h},ki.prototype.updateRawCubeTexture=function(e,t,i,s,r,n=null,o=0){e._bufferViewArray=t,e.format=i,e.type=s,e.invertY=r,e._compression=n;const a=this._gl,l=this._getWebGLTextureType(s);let h=this._getInternalFormat(i);const c=this._getRGBABufferInternalSizedFormat(s);let u=!1;h===a.RGB&&(h=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let r=t[i];n?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,this.getCaps().s3tc[n],e.width,e.height,0,r):(u&&(r=Uo(r,e.width,e.height,s)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,c,e.width,e.height,0,h,l,r))}(!this.needPOTTextures||as(e.width)&&as(e.height))&&e.generateMipMaps&&0===o&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},ki.prototype.createRawCubeTextureFromUrl=function(e,t,i,s,r,n,o,a,l=null,h=null,c=3,u=!1){const d=this._gl,_=this.createRawCubeTexture(null,i,s,r,!n,u,c,null);t?.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_);const p=e=>{const i=_.width,n=o(e);if(n){if(a){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(s);const o=this._getRGBABufferInternalSizedFormat(r);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const h=a(n);for(let s=0;s>s;for(let i=0;i<6;i++){let a=h[s][i];l&&(a=Uo(a,n,n,r)),d.texImage2D(i,s,o,n,n,0,t,e,a)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(_,n,s,r,u);_.isReady=!0,t?.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{p(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(_),h&&e&&h(e.status+" "+e.statusText,i)})),_},ki.prototype.createRawTexture2DArray=Go(!1),ki.prototype.createRawTexture3D=Go(!0),ki.prototype.updateRawTexture2DArray=zo(!1),ki.prototype.updateRawTexture3D=zo(!0);class Wo extends Vo{constructor(e,t,i,s,r,n=!0,o=!1,a=3,l=0,h,c){super(null,r,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=s,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,s,n,o,a,null,l,h??0,c??!1),this.wrapU=Vo.CLAMP_ADDRESSMODE,this.wrapV=Vo.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,s,r=!0,n=!1,o=3){return new Wo(e,t,i,1,s,r,n,o)}static CreateLuminanceAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Wo(e,t,i,2,s,r,n,o)}static CreateAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Wo(e,t,i,0,s,r,n,o)}static CreateRGBTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new Wo(e,t,i,4,s,r,n,o,a,l,h)}static CreateRGBATexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new Wo(e,t,i,5,s,r,n,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=!1){return new Wo(e,t,i,5,s,r,n,o,a,1,l)}static CreateRTexture(e,t,i,s,r=!0,n=!1,o=Vo.TRILINEAR_SAMPLINGMODE,a=1){return new Wo(e,t,i,6,s,r,n,o,a)}static CreateRStorageTexture(e,t,i,s,r=!0,n=!1,o=Vo.TRILINEAR_SAMPLINGMODE,a=1){return new Wo(e,t,i,6,s,r,n,o,a,1)}}class Ho{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=fe.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new X,this.bones=[],this._scene=i||se.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,ge.Matrix[1]),e._updateAbsoluteBindMatrices(ge.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=Wo.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=Wo.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new Ho(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=de.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s-1&&(n=i.bones[t.parentBoneIndex]);const o=t.rest?fe.FromArray(t.rest):null,a=new pr(t.name,i,n,fe.FromArray(t.matrix),o,null,r);void 0!==t.id&&null!==t.id&&(a.id=t.id),t.length&&(a.length=t.length),t.metadata&&(a.metadata=t.metadata),t.animation&&a.animations.push(Nt.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,a._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class Xo{constructor(e,t){this._scene=e,t instanceof Ho?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}async bakeVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=e.reduce(((e,t)=>e+t.to-t.from+1),0);if(isNaN(i))throw new Error("Invalid animation ranges.");let s=0;const r=new Float32Array(4*(t+1)*4*i);this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest();for(const t of e)for(let e=t.from;e<=t.to;e++)await this._executeAnimationFrame(r,e,s++);return r}async _executeAnimationFrame(e,t,i){return new Promise(((s,r)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,(()=>{const t=this._skeleton.getTransformMatrices(this._mesh);e.set(t,i*t.length),s()}))}))}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=Wo.CreateRGBATexture(e,4*(t+1),e.length/(4*(t+1)*4),this._scene,!1,!1,Vo.NEAREST_NEAREST,1);return i.name="VAT"+this._skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=4*(t+1),s=e.length/(4*(t+1)*4);return{vertexData:qt(e),width:i,height:s}}loadBakedVertexDataFromObject(e){return new Float32Array(Jt(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}class Yo{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Ms.POINTERDOWN?e.type===Ms.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=zt.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??zt.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Qo.EasingFunction.setEasingMode(Qo.EasingMode),this._radiusBounceTransition=Nt.CreateAnimation("radius",Nt.ANIMATIONTYPE_FLOAT,60,Qo.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Nt.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(()=>this._clearAnimationLocks()));t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}Qo.EasingFunction=new Er(.3),Qo.EasingMode=Sr.EASINGMODE_EASEOUT;class jo{constructor(){this.onTargetFramingAnimationEndObservable=new X,this._mode=jo.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();jo.EasingFunction.setEasingMode(jo.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Ms.POINTERDOWN?e.type===Ms.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new de(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===jo.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=zt.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Nt.CreateAnimation("beta",Nt.ANIMATIONTYPE_FLOAT,60,jo.EasingFunction));const e=Nt.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=zt.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}jo.EasingFunction=new Ir,jo.EasingMode=Sr.EASINGMODE_EASEINOUT,jo.IgnoreBoundsSizeMode=0,jo.FitFrustumSidesMode=1;class Ko{constructor(e,t=new de,i=0,s=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=s}}class $o{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new Ko(de.Up()),new Ko(de.Down()),new Ko(de.Left()),new Ko(de.Right()),new Ko(de.Forward()),new Ko(de.Forward().scaleInPlace(-1))],this._tmpMatrix=new fe,this._tmpVector=new de,this._zeroVector=de.Zero(),this._lookAtTmpMatrix=new fe}init(){}_closestFace(e){return this._faceVectors.forEach((t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=pe.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),de.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=de.GetAngleBetweenVectors(t.rotatedDirection,e,de.Cross(t.rotatedDirection,e))})),this._faceVectors.reduce(((e,t)=>e.ignore?t:t.ignore||e.diff{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),de.TransformCoordinatesToRef(de.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach((e=>{i.direction.x&&e.direction.x&&(e.ignore=!0),i.direction.y&&e.direction.y&&(e.ignore=!0),i.direction.z&&e.direction.z&&(e.ignore=!0)}));const s=this._closestFace(this._tmpVector);this._faceVectors.forEach((e=>{e.ignore=!1})),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=pe.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,s.rotatedDirection,this._ui.rotationQuaternion),s.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),s.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),s.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)}))}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}class qo{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time)return this._hoverValue=this._time,void this._detachObserver()}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0))return this._hoverValue=0,void this._detachObserver();this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0)||(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach((e=>{this._setAllVisibility(e,t)}))}_attachObserver(){this._onBeforeRenderObserver||(this._onBeforeRenderObserver=this._ownerNode?.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){this._onBeforeRenderObserver&&(this._ownerNode?.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}class Zo{constructor(e,t,i=Number.MAX_VALUE,s=K){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new Zo(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Zo._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=Zo._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.x)return!1}else if(n=1/this.direction.x,o=(s.x-this.origin.x)*n,a=(r.x-this.origin.x)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(n=1/this.direction.y,o=(s.y-this.origin.y)*n,a=(r.y-this.origin.y)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(n=1/this.direction.z,o=(s.z-this.origin.z)*n,a=(r.z-this.origin.z)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,a=o*o;if(n<=a)return!0;const l=i*this.direction.x+s*this.direction.y+r*this.direction.z;return!(l<0)&&n-l*l<=a}intersectsTriangle(e,t,i){const s=Zo._TmpVector3[0],r=Zo._TmpVector3[1],n=Zo._TmpVector3[2],o=Zo._TmpVector3[3],a=Zo._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),de.CrossToRef(this.direction,r,n);const l=de.Dot(s,n);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,o);const c=de.Dot(o,n)*h;if(c<-this.epsilon||c>1+this.epsilon)return null;de.CrossToRef(o,s,a);const u=de.Dot(this.direction,a)*h;if(u<-this.epsilon||c+u>1+this.epsilon)return null;const d=de.Dot(r,a)*h;return d>this.length?null:new $r(1-c-u,c,d)}intersectsPlane(e){let t;const i=de.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const s=de.Dot(e.normal,this.origin);return t=(-e.d-s)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new de(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new de(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new de(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=ge.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?Zo.TransformToRef(this,o,this._tmpRay):this._tmpRay=Zo.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Vector3[2],a=ge.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(Zo._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,a);const l=de.Dot(r,r),h=de.Dot(r,o),c=de.Dot(o,o),u=de.Dot(r,a),d=de.Dot(o,a),_=l*c-h*h;let p,f,m=_,g=_;_m&&(p=m,f=d+h,g=c)),f<0?(f=0,-u<0?p=0:-u>l?p=m:(p=-u,m=l)):f>g&&(f=g,-u+h<0?p=0:-u+h>l?p=m:(p=-u+h,m=l));const v=Math.abs(p)0&&x<=this.length&&y.lengthSquared()=e.distance?null:h:null},dr.prototype._internalPick=function(e,t,i,s,r){let n=null;const o=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let o=0;o(this._tempPickingRay||(this._tempPickingRay=Zo.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null),this._tempPickingRay)),i,s,!0);return n&&(n.ray=this.createPickingRay(e,t,fe.Identity(),r||null)),n},Object.defineProperty(dr.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),dr.prototype.pick=function(e,t,i,s,r,n,o=!1){const a=this._internalPick(((i,s)=>(this._tempPickingRay||(this._tempPickingRay=Zo.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null,!1,s),this._tempPickingRay)),i,s,!1,n);return a&&(a.ray=this.createPickingRay(e,t,fe.Identity(),r||null)),a},dr.prototype.pickWithRay=function(e,t,i,s){const r=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=fe.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Zo.Zero()),Zo.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,s);return r&&(r.ray=e),r},dr.prototype.multiPick=function(e,t,i,s,r){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,s||null)),i,r)},dr.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=fe.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Zo.Zero()),Zo.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},Kr.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new Zo(de.Zero(),de.Zero(),e),e,t,i)},Kr.prototype.getForwardRayToRef=function(e,t=100,i,s){i||(i=this.getWorldMatrix()),e.length=t,s?e.origin.copyFrom(s):e.origin.copyFrom(this.position);const r=ge.Vector3[2];r.set(0,0,this._scene.useRightHandedSystem?-1:1);const n=ge.Vector3[3];return de.TransformNormalToRef(r,i,n),de.NormalizeToRef(n,e.direction),e};class Jo{static _RemoveAndStorePivotPoint(e){e&&0===Jo._PivotCached&&(e.getPivotPointToRef(Jo._OldPivotPoint),Jo._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,Jo._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(fe.IdentityReadOnly),Jo._OldPivotPoint.subtractToRef(e.getPivotPoint(),Jo._PivotTranslation),Jo._PivotTmpVector.copyFromFloats(1,1,1),Jo._PivotTmpVector.subtractInPlace(e.scaling),Jo._PivotTmpVector.multiplyInPlace(Jo._PivotTranslation),e.position.addInPlace(Jo._PivotTmpVector))),Jo._PivotCached++}static _RestorePivotPoint(e){e&&!Jo._OldPivotPoint.equalsToFloats(0,0,0)&&1===Jo._PivotCached&&(e.setPivotPoint(Jo._OldPivotPoint),e._postMultiplyPivotMatrix=Jo._PivotPostMultiplyPivotMatrix,Jo._PivotTmpVector.copyFromFloats(1,1,1),Jo._PivotTmpVector.subtractInPlace(e.scaling),Jo._PivotTmpVector.multiplyInPlace(Jo._PivotTranslation),e.position.subtractInPlace(Jo._PivotTmpVector)),this._PivotCached--}}function ea(e){const t=[],i=[],s=[],r=[],n=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,l=n/2,h=o/2;i.push(-l,-h,0),s.push(0,0,-1),r.push(0,dn.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),s.push(0,0,-1),r.push(1,dn.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),s.push(0,0,-1),r.push(1,dn.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),s.push(0,0,-1),r.push(0,dn.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),cn._ComputeSides(a,i,t,s,r,e.frontUVs,e.backUVs);const c=new cn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function ta(e,t={},i=null){const s=new bo(e,i);return t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,ea(t).applyToMesh(s,t.updatable),t.sourcePlane&&(s.translate(t.sourcePlane.normal,-t.sourcePlane.d),s.setDirection(t.sourcePlane.normal.scale(-1))),s}Jo._PivotCached=0,Jo._OldPivotPoint=new de,Jo._PivotTranslation=new de,Jo._PivotTmpVector=new de,Jo._PivotPostMultiplyPivotMatrix=!1;const ia={CreatePlane:ta};cn.CreatePlane=ea,bo.CreatePlane=(e,t,i,s,r)=>ta(e,{size:t,width:t,height:t,sideOrientation:r,updatable:s},i);class sa{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new X,this.onDragStartObservable=new X,this.onDragEndObservable=new X,this.onEnabledObservable=new X,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new de(0,0,0),this._alternatePickedPoint=new de(0,0,0),this._worldDragAxis=new de(0,0,0),this._targetPosition=new de(0,0,0),this._attachedToElement=!1,this._startDragRay=new Zo(new de,new de),this._lastPointerRay={},this._dragDelta=new de,this._pointA=new de(0,0,0),this._pointC=new de(0,0,0),this._localAxis=new de(0,0,0),this._lookAt=new de(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,sa._PlaneScene||(this._debugMode?sa._PlaneScene=this._scene:(sa._PlaneScene=new dr(this._scene.getEngine(),{virtual:!0}),sa._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{sa._PlaneScene.dispose(),sa._PlaneScene=null})))),this._dragPlane=ta("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:bo.DOUBLESIDE},sa._PlaneScene),this.lastDragPosition=new de(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==Ms.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==Ms.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==Ms.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===sa._AnyMouseId&&t!==sa._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new Zo(new de,new de)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;Jo._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),Jo._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=sa._AnyMouseId,t,i){this._startDrag(e,t,i);let s=this._lastPointerRay[e];e===sa._AnyMouseId&&(s=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),s&&this._moveDrag(s)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;Jo._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const s=this._pickWithRayOnDragPlane(this._startDragRay);s?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(s),this.onDragStartObservable.notifyObservers({dragPlanePoint:s,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),Jo._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){Jo._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?de.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=de.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),Jo._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(de.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*de.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=de.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=this._dragPlane.forward,s=this._dragPlane.position,r=e.direction.dot(i);if(Math.abs(r).999?Math.abs(de.Dot(de.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(de.Right()):this._lookAt.copyFrom(de.UpReadOnly):(de.CrossToRef(this._localAxis,this._pointC,this._lookAt),de.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?de.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}sa._AnyMouseId=-2;class ra{constructor(){this._startDistance=0,this._initialScale=new de(0,0,0),this._targetScale=new de(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new sa({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new sa({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const e=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(e,this._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}}))}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)}))}}class na{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new de,this._tmpQuaternion=new pe,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new X,this.onDragObservable=new X,this.onDragEndObservable=new X,this.allowMultiPointer=!0}get currentDraggingPointerId(){return void 0!==this.currentDraggingPointerIds[0]?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new Sn("",na._virtualScene);e.rotationQuaternion=new pe;const t=new Sn("",na._virtualScene);t.rotationQuaternion=new pe;const i=new Sn("",na._virtualScene);return i.rotationQuaternion=new pe,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new de,startingPivotOrientation:new pe,startingPosition:new de,startingOrientation:new pe,lastOriginPosition:new de,lastDragPosition:new de}}_resetVirtualMeshesPosition(){for(let e=0;el&&(l=Math.min(h-a,0)),o.scaleInPlace(l),o.addToRef(r.pivotMesh.absolutePosition,this._tmpVector),r.pivotMesh.setAbsolutePosition(this._tmpVector),o.addToRef(r.dragMesh.absolutePosition,this._tmpVector),r.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),na._virtualScene||(na._virtualScene=new dr(this._scene.getEngine(),{virtual:!0}),na._virtualScene.detachControl());const t=e=>this._ownerNode===e||e.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||-1!==this.draggableMeshes.indexOf(e));this._pointerObserver=this._scene.onPointerObservable.add((e=>{const i=e.event.pointerId;this._virtualMeshesInfo[i]||(this._virtualMeshesInfo[i]=this._createVirtualMeshInfo());const s=this._virtualMeshesInfo[i],r="xr-near"===e.event.pointerType||"xr"===e.event.pointerType;if(e.type==Ms.POINTERDOWN){if(!s.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&(!r||e.pickInfo.aimTransform)&&t(e.pickInfo.pickedMesh)){if((!this.allowMultiPointer||r)&&this.currentDraggingPointerIds.length>0)return;!this._pointerCamera||this._pointerCamera.cameraRigMode!==Kr.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||e.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const t=this._virtualMeshesInfo[i];r?(this._dragging=e.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,t.originMesh.position.copyFrom(e.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&e.pickInfo.gripTransform?t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.gripTransform.rotationQuaternion):t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,t.originMesh.position.copyFrom(e.pickInfo.ray.origin)),t.lastOriginPosition.copyFrom(t.originMesh.position),t.dragMesh.position.copyFrom(e.pickInfo.pickedPoint),t.lastDragPosition.copyFrom(e.pickInfo.pickedPoint),t.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),t.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),t.startingPosition.copyFrom(t.dragMesh.position),t.startingPivotPosition.copyFrom(t.pivotMesh.position),t.startingOrientation.copyFrom(t.dragMesh.rotationQuaternion),t.startingPivotOrientation.copyFrom(t.pivotMesh.rotationQuaternion),r?(t.originMesh.addChild(t.dragMesh),t.originMesh.addChild(t.pivotMesh)):t.originMesh.lookAt(t.dragMesh.position),t.dragging=!0,-1===this.currentDraggingPointerIds.indexOf(i)&&this.currentDraggingPointerIds.push(i),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):this.allowMultiPointer&&0!==this.currentDraggingPointerIds.length||(this._attachedToElement=!1)),this._targetDragStart(t.pivotMesh.position,t.pivotMesh.rotationQuaternion,i),this.onDragStartObservable.notifyObservers({position:t.pivotMesh.position})}}else if(e.type==Ms.POINTERUP||e.type==Ms.POINTERDOUBLETAP){const e=this.currentDraggingPointerIds.indexOf(i);s.dragging=!1,-1!==e&&(this.currentDraggingPointerIds.splice(e,1),0===this.currentDraggingPointerIds.length&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),s.originMesh.removeChild(s.dragMesh),s.originMesh.removeChild(s.pivotMesh),this._targetDragEnd(i),this.onDragEndObservable.notifyObservers({}))}else if(e.type==Ms.POINTERMOVE&&-1!==this.currentDraggingPointerIds.indexOf(i)&&s.dragging&&e.pickInfo&&(e.pickInfo.ray||e.pickInfo.aimTransform)){let t=this.zDragFactor;(this.currentDraggingPointerIds.length>1||e.pickInfo.originMesh)&&(t=0),this._ownerNode.computeWorldMatrix(!0),r?this._pointerUpdateXR(e.pickInfo.aimTransform,e.pickInfo.gripTransform,i,t):this._pointerUpdate2D(e.pickInfo.ray,i,t),this._tmpQuaternion.copyFrom(s.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,s.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),s.pivotMesh.absolutePosition.subtractToRef(s.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:s.pivotMesh.position,pickInfo:e.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,i),s.lastDragPosition.copyFrom(s.dragMesh.absolutePosition),this._moving=!0}}))}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if("ArcRotateCamera"===this._pointerCamera.getClassName()){const e=this._pointerCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(!this._pointerCamera.inputs||this._pointerCamera.inputs.noPreventDefault)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}class oa extends na{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new de(0,0,0),this._targetOrientation=new pe,this._targetScaling=new de(1,1,1),this._startingPosition=new de(0,0,0),this._startingOrientation=new pe,this._startingScaling=new de(1,1,1),this.onPositionChangedObservable=new X,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,e.getChildMeshes().forEach((e=>{e.isNearGrabbable=!0})),this._virtualTransformNode=new xn("virtual_sixDof",na._virtualScene),this._virtualTransformNode.rotationQuaternion=pe.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(1===this.currentDraggingPointerIds.length&&this._moving&&!this.disableMovement){const t=ge.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=ge.Vector3[1];if(i.copyFrom(t),e.parent){const s=ge.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(s),s.invert(),de.TransformNormalToRef(t,s,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const t=ge.Quaternion[0];if(t.copyFrom(this._targetOrientation),e.parent){const i=ge.Quaternion[0];i.copyFrom(e.parent.absoluteRotationQuaternion),i.invertInPlace(),i.multiplyToRef(this._targetOrientation,t)}pe.SlerpToRef(e.rotationQuaternion,t,this.dragDeltaRatio,e.rotationQuaternion)}}}))}_getPositionOffsetAround(e,t,i){const s=ge.Matrix[0],r=ge.Matrix[1],n=ge.Matrix[2],o=ge.Matrix[3],a=ge.Matrix[4];return fe.TranslationToRef(e.x,e.y,e.z,s),fe.TranslationToRef(-e.x,-e.y,-e.z,r),fe.FromQuaternionToRef(i,n),fe.ScalingToRef(t,t,t,o),r.multiplyToRef(n,a),a.multiplyToRef(o,a),a.multiplyToRef(s,a),a.getTranslation()}_onePointerPositionUpdated(e,t){ge.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?pe.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,ge.Quaternion[0]):ge.Quaternion[0].copyFrom(t),ge.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=ge.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const s=ge.Vector3[1];t.subtractToRef(e,s);const r=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,n=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=ge.Vector3[2];r.addToRef(n,o),o.scaleInPlace(.5);const a=ge.Vector3[3];n.subtractToRef(r,a);const l=a.length()/s.length(),h=o.subtract(i),c=pe.FromEulerAngles(0,de.GetAngleBetweenVectorsOnPlane(s.normalize(),a.normalize(),de.UpReadOnly),0),u=this._ownerNode.parent;this._ownerNode.setParent(null);const d=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),l,c);this._virtualTransformNode.rotationQuaternion.multiplyToRef(c,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(l,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(h.addInPlace(d),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(u)}_targetDragStart(){const e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=pe.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const t=this._ownerNode.getAbsolutePivotPoint();if(1===e){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const e=ge.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,e),e.normalize();const i=ge.Quaternion[0];this._scene.useRightHandedSystem?pe.FromLookDirectionRHToRef(e,new de(0,1,0),i):pe.FromLookDirectionLHToRef(e,new de(0,1,0),i),i.normalize(),pe.RotationYawPitchRollToRef(i.toEulerAngles().y,0,0,ge.Quaternion[0]),this._targetOrientation.copyFrom(ge.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else 2===e&&(this._virtualTransformNode.setPivotPoint(new de(0,0,0),lr.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,lr.WORLD),this._resetVirtualMeshesPosition())}_targetDrag(e,t){1===this.currentDraggingPointerIds.length?this._onePointerPositionUpdated(e,t):2===this.currentDraggingPointerIds.length&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(1===this.currentDraggingPointerIds.length){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}class aa{constructor(){this._attachPointLocalOffset=new de,this._workingPosition=new de,this._workingQuaternion=new pe,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=pe.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const s=ge.Vector3[0];return s.copyFrom(t),s.scaleInPlace(this.hitNormalOffset),s.addInPlace(i),this._attachedMesh.parent&&(ge.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),de.TransformNormalToRef(s,ge.Matrix[0],s)),{position:s,quaternion:pe.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const e=this._getTargetPose(t);e&&de.Distance(this._attachedMesh.position,e.position){this.enabled&&e.type==Ms.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)})),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}class la{constructor(){this._tmpQuaternion=new pe,this._tmpVectors=[new de,new de,new de,new de,new de,new de,new de],this._tmpMatrix=new fe,this._tmpInvertView=new fe,this._tmpForward=new de,this._tmpNodeForward=new de,this._tmpPosition=new de,this._workingPosition=new de,this._workingQuaternion=new pe,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(de.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,s=this.maximumDistance;const r=this.defaultDistance,n=this._tmpVectors[0];n.copyFrom(e);let o=n.length();if(n.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(n)*i,s=this._length2D(n)*s;const t=this._length2D(e);n.scaleInPlace(o/t),o=t}let a=o;return a=t?r:xe.Clamp(o,i,s),e.copyFrom(n).scaleInPlace(a),o!==a}_applyVerticalClamp(e){0!==this.verticalMaxDistance&&(e.y=xe.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){pe.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),de.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),de.TransformNormalToRef(i,e,i),pe.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const s=this._tmpVectors[6];s.copyFromFloats(1,0,0),de.TransformNormalToRef(i,e,i),de.TransformNormalToRef(s,e,s);const r=de.UpReadOnly;if(t.length()r&&(pe.RotationAxisToRef(s,-e+r,o),t.rotateByQuaternionToRef(o,t),n=!0)}const a=this._angleBetweenVectorAndPlane(t,s)*(this._scene.useRightHandedSystem?-1:1),l=this.maxViewHorizontalDegrees*Math.PI/180*.5;return a<-l?(pe.RotationAxisToRef(r,-a-l,o),t.rotateByQuaternionToRef(o,t),n=!0):a>l&&(pe.RotationAxisToRef(r,-a+l,o),t.rotateByQuaternionToRef(o,t),n=!0),n}_orientationClamp(e,t){const i=this._tmpVectors[0];i.copyFrom(e).scaleInPlace(-1).normalize();const s=this._tmpVectors[1],r=this._tmpVectors[2];s.copyFromFloats(0,1,0),de.CrossToRef(i,s,r);const n=r.length();nthis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),s=this._workingPosition,r=this._workingQuaternion,n=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),de.TransformCoordinatesToRef(n,i,s);const a=this._tmpPosition;a.copyFromFloats(0,0,0),de.TransformCoordinatesToRef(a,i,a),a.scaleInPlace(-1).subtractInPlace(n),s.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let l=!1;const h=this._tmpForward;h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),de.TransformNormalToRef(h,o,h);const c=this._tmpNodeForward;if(c.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),de.TransformNormalToRef(c,i,c),this._recenterNextUpdate)s.copyFrom(h).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const e=s.length();s.copyFrom(h).scaleInPlace(e)}else l=this._angularClamp(o,s);let u=!1;this.ignoreDistanceClamp||(u=this._distanceClamp(s,l),this._applyVerticalClamp(s)),this.useFixedVerticalOffset&&(s.y=a.y-e.globalPosition.y+this.fixedVerticalOffset),(l||u||this._passedOrientationDeadzone(s,c)||this._recenterNextUpdate)&&this._orientationClamp(s,r),this._workingPosition.subtractInPlace(n),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=pe.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose)return this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),void this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);const i=new de;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),de.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const s=new pe;s.copyFrom(this.attachedNode.rotationQuaternion),pe.SmoothToRef(s,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}class ha{}ha.ANCHOR_SYSTEM="xr-anchor-system",ha.BACKGROUND_REMOVER="xr-background-remover",ha.HIT_TEST="xr-hit-test",ha.MESH_DETECTION="xr-mesh-detection",ha.PHYSICS_CONTROLLERS="xr-physics-controller",ha.PLANE_DETECTION="xr-plane-detection",ha.POINTER_SELECTION="xr-controller-pointer-selection",ha.TELEPORTATION="xr-controller-teleportation",ha.FEATURE_POINTS="xr-feature-points",ha.HAND_TRACKING="xr-hand-tracking",ha.IMAGE_TRACKING="xr-image-tracking",ha.NEAR_INTERACTION="xr-near-interaction",ha.DOM_OVERLAY="xr-dom-overlay",ha.MOVEMENT="xr-controller-movement",ha.LIGHT_ESTIMATION="xr-light-estimation",ha.EYE_TRACKING="xr-eye-tracking",ha.WALKING_LOCOMOTION="xr-walking-locomotion",ha.LAYERS="xr-layers",ha.DEPTH_SENSING="xr-depth-sensing",ha.SPACE_WARP="xr-space-warp",ha.RAW_CAMERA_ACCESS="xr-raw-camera-access";class ca{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||hs.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||hs.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},s=!0,r=!0){const n="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(o="stable"===t?ca.GetStableVersionOfFeature(n):"latest"===t?ca.GetLatestVersionOfFeature(n):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const a=ca._ConflictingFeatures[n];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${n} cannot be enabled while ${a} is enabled.`);const l=this._features[n],h=ca.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);l&&this.disableFeature(n);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[n]={featureImplementation:c,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return hs.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],s=t.featureImplementation.xrNativeFeatureName;if(s&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(s)&&e.requiredFeatures.push(s)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(s)&&e.optionalFeatures.push(s))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}ca._AvailableFeatures={},ca._ConflictingFeatures={[ha.TELEPORTATION]:ha.MOVEMENT,[ha.MOVEMENT]:ha.TELEPORTATION};class ua{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===this._xrSessionManager.enabledFeatures?.indexOf(e)&&we.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new X,this.onFeatureDetachObservable=new X}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(this._xrSessionManager.enabledFeatures){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else we.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class da{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}da.DistanceJoint=0,da.HingeJoint=1,da.BallAndSocketJoint=2,da.WheelJoint=3,da.SliderJoint=4,da.PrismaticJoint=5,da.UniversalJoint=6,da.Hinge2Joint=da.WheelJoint,da.PointToPointJoint=8,da.SpringJoint=9,da.LockJoint=10;class _a extends da{constructor(e){super(da.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class pa extends da{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class fa extends pa{constructor(e){super(da.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class ma extends pa{constructor(e){super(da.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}bo._PhysicsImpostorParser=function(e,t,i){return new ga(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class ga{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},s){this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=de.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new pe,this._tmpQuat2=new pe,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new pe),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(this)})),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,ga._TmpVecs[0]),this.object.translate(ga._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&we.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=pe.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new pe),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&we.Warn("You must affect impostors to children before affecting impostor to parent.")):we.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):we.Error("No object was provided. A physics object is obligatory")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof Sn?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=ga.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const s=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}return ga.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):de.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):de.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):we.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):we.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let s=-1;this._onPhysicsCollideCallbacks.some(((e,r)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(s=r),t}return!1}))?this._onPhysicsCollideCallbacks.splice(s,1):we.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):pe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const s=new da(t,i);return this.addJoint(e,s),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new ga(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach((e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new pe),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,s,r){const n=ga._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const i=ga._TmpQuat;o.rotationQuaternion.multiplyToRef(r,i),e.setRotationQuaternion(i,lr.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,lr.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==s&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const i=ga._TmpQuat;e.getRotationQuaternionToRef(lr.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(lr.WORLD,t,o.rotationQuaternion);const a=ga._TmpVecs[0],l=ga._TmpVecs[1];n||((n=ga._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}}var va,xa,ba,Ta,ya,Sa,Ca,Ea,Aa;ga.DEFAULT_OBJECT_SIZE=new de(1,1,1),ga.IDENTITY_QUATERNION=pe.Identity(),ga._TmpVecs=$.BuildArray(3,de.Zero),ga._TmpQuat=pe.Identity(),ga.NoImpostor=0,ga.SphereImpostor=1,ga.BoxImpostor=2,ga.PlaneImpostor=3,ga.MeshImpostor=4,ga.CapsuleImpostor=6,ga.CylinderImpostor=7,ga.ParticleImpostor=8,ga.HeightmapImpostor=9,ga.ConvexHullImpostor=10,ga.CustomImpostor=100,ga.RopeImpostor=101,ga.ClothImpostor=102,ga.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(va||(va={}));class Pa{static get ForceFullSceneLoadingForIncremental(){return un.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){un.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return un.ShowLoadingScreen}static set ShowLoadingScreen(e){un.ShowLoadingScreen=e}static get loggingLevel(){return un.loggingLevel}static set loggingLevel(e){un.loggingLevel=e}static get CleanBoneMatrixWeights(){return un.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){un.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Pa._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return Pa._RegisteredPlugins[e]||(we.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),Pa.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Pa._RegisteredPlugins){const i=Pa._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Pa._RegisteredPlugins[t]}return Pa.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return Pa._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,r,n,o,a){const l=Pa._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?Pa._GetPluginForExtension(o):l?Pa._GetPluginForDirectLoad(e.url):Pa._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(Pa.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!Zi(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const u=h.isBinary,d=(e,s)=>{t.isDisposed?r("Scene has been disposed"):i(c,e,s)};let _=null,p=!1;const f=c.onDisposeObservable;f&&f.add((()=>{p=!0,_&&(_.abort(),_=null),n()}));const m=()=>{if(p)return;const i=(e,t)=>{r(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";_=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,s,u,i,a):t._loadFile(e.file||e.url,d,s,!0,u,i)},g=t.getEngine();let v=g.enableOfflineSupport;if(v){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}v=!i}return v&&gn.OfflineProviderFactory?t.offlineProvider=gn.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,r=e}else if(ArrayBuffer.isView(t))i="",s=ns(),n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const r=t;if("/"===r.substr(0,1))return hs.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}else i=e,s=hs.GetFilename(e),e=hs.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return Pa._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Pa._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;Pa._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Pa._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=se.LastCreatedScene,r=null,n=null,o=null,a=null,l=""){if(!s)return we.Error("No scene available to import mesh to"),null;const h=Pa._GetFileInfo(t,i);if(!h)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(e,t)=>{const i=Pa._FormatErrorMessage(h,e,t);o?o(s,i,new Qt(i,Yt.SceneLoaderError,t)):we.Error(i),u()},_=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,p=(e,t,i,n,o,a,l,u)=>{if(s.importedMeshesFiles.push(h.url),r)try{r(e,t,i,n,o,a,l,u)}catch(e){d("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return Pa._LoadData(h,s,((t,i,r)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,r)),t.importMesh){const r=[],n=[],o=[];if(!t.importMesh(e,s,i,h.rootUrl,r,n,o,d))return;s.loadingPluginName=t.name,p(r,n,o,[],[],[],[],[])}else t.importMeshAsync(e,s,i,h.rootUrl,_,h.name).then((e=>{s.loadingPluginName=t.name,p(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{d(e.message,e)}))}),_,d,u,a,l)}static ImportMeshAsync(e,t,i="",s=se.LastCreatedScene,r=null,n=null,o=""){return new Promise(((a,l)=>{Pa.ImportMesh(e,t,i,s,((e,t,i,s,r,n,o,l)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:r,geometries:n,lights:o,spriteManagers:l})}),r,((e,t,i)=>{l(i||new Error(t))}),n,o)}))}static Load(e,t="",i=se.LastCreatedEngine,s=null,r=null,n=null,o=null,a=""){return i?Pa.Append(e,t,new dr(i),s,r,n,o,a):(hs.Error("No engine available"),null)}static LoadAsync(e,t="",i=se.LastCreatedEngine,s=null,r=null,n=""){return new Promise(((o,a)=>{Pa.Load(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static Append(e,t="",i=se.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return we.Error("No scene available to append to"),null;const l=Pa._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};Pa.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const u=(e,t)=>{const s=Pa._FormatErrorMessage(l,e,t);n?n(i,s,new Qt(s,Yt.SceneLoaderError,t)):we.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=()=>{if(s)try{s(i)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Pa._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,u))return;i.loadingPluginName=e.name,_()}else e.loadAsync(i,t,l.rootUrl,d,l.name).then((()=>{i.loadingPluginName=e.name,_()})).catch((e=>{u(e.message,e)}))}),d,u,c,o,a)}static AppendAsync(e,t="",i=se.LastCreatedScene,s=null,r=null,n=""){return new Promise(((o,a)=>{Pa.Append(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static LoadAssetContainer(e,t="",i=se.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return we.Error("No scene available to load asset container to"),null;const l=Pa._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},u=(e,t)=>{const s=Pa._FormatErrorMessage(l,e,t);n?n(i,s,new Qt(s,Yt.SceneLoaderError,t)):we.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=e=>{if(s)try{s(e)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Pa._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,l.rootUrl,u);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,_(s)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,_(t)})).catch((e=>{u(e.message,e)})):u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),d,u,c,o,a)}static LoadAssetContainerAsync(e,t="",i=se.LastCreatedScene,s=null,r=null){return new Promise(((n,o)=>{Pa.LoadAssetContainer(e,t,i,(e=>{n(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=se.LastCreatedScene,s=!0,r=va.Clean,n=null,o=null,a=null,l=null,h=null){if(!i)return void we.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case va.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case va.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case va.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case va.NoSync:break;default:return void we.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h)}static ImportAnimationsAsync(e,t="",i=se.LastCreatedScene,s=!0,r=va.Clean,n=null,o=null,a=null,l=null,h=null){return new Promise(((o,l)=>{Pa.ImportAnimations(e,t,i,s,r,n,(e=>{o(e)}),a,((e,t,i)=>{l(i||new Error(t))}),h)}))}}Pa.NO_LOGGING=0,Pa.MINIMAL_LOGGING=1,Pa.SUMMARY_LOGGING=2,Pa.DETAILED_LOGGING=3,Pa.OnPluginActivatedObservable=new X,Pa._RegisteredPlugins={},Pa._ShowingLoadingScreen=!1;class Ra extends uo{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new fe,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(xa||(xa={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(ba||(ba={}));class Ia{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){const t=e.sharedData.emitComments,i=this.target===ba.Fragment;this.compilationString=`\n${t?"//Entry point\n":""}void main(void) {\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\n${t?"//Constants\n":""}${this._constantDeclaration}\n${this.compilationString}`);let s="";for(const e in this.functions)s+=this.functions[e]+"\n";this.compilationString=`\n${s}\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\n${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\n${t?"//Samplers\n":""}${this._samplerDeclaration}\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\n${t?"//Uniforms\n":""}${this._uniformDeclaration}\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\n${t?"//Attributes\n":""}${this._attributeDeclaration}\n${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defined(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString);for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\n${t}\n${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2D ${e};\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\n`,this.samplers.push(e))}_getGLType(e){switch(e){case xa.Float:return"float";case xa.Int:return"int";case xa.Vector2:return"vec2";case xa.Color3:case xa.Vector3:return"vec3";case xa.Color4:case xa.Vector4:return"vec4";case xa.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\n${t}\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`;let s=Ti.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(s=t+"\n"+s),!i)return s;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`:this.functions[r]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""}\n`,void(this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]));if(this.functions[r]=Ti.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;ethis._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;te.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ba.Vertex)return!0;if((e.ownerBlock.target===ba.Neutral||e.ownerBlock.target===ba.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===ba.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ba.Vertex)return!0;if(e.target===ba.Vertex)return!0;if((e.ownerBlock.target===ba.Neutral||e.ownerBlock.target===ba.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===ba.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ba.Fragment)return!0;if((e.ownerBlock.target===ba.Neutral||e.ownerBlock.target===ba.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=xa.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new X,this.onDisconnectionObservable=new X,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=ba.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===Ta.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===ba.Fragment){if(i.target===ba.Vertex)return Ta.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=ba.Neutral&&e.isConnectedInVertexShader)return Ta.TargetIncompatible}if(this.type!==e.type&&e.innerType!==xa.AutoDetect)return Da.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&Da.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?Ta.Compatible:Ta.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return Ta.TypeIncompatible;let s=i,r=t;return this.direction===ya.Input&&(s=t,r=i),s.isAnAncestorOf(r)?Ta.HierarchyIssue:Ta.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class wa{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=ba.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===ba.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=rr.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===ba.Neutral}initialize(e){}bind(e,t,i,s){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some((e=>e.isConnectedInFragmentShader))}registerInput(e,t,i=!1,s,r){return(r=r??new Da(e,this,ya.Input)).type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return(s=s??new Da(e,this,ya.Output)).type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==xa.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===ba.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=(()=>!0)){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===ba.Vertex||this.target!==ba.VertexAndFragment&&this.target!==ba.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,s=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,s){e.build(t,s);const r=null!=t._vertexState,n=e._buildTarget===ba.Vertex&&e.target!==ba.VertexAndFragment;if(r&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==ba.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName};\n`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==ba.Neutral){if(!(i.target&this.target))continue;if(!(i.target&e.target))continue}const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&we.Log(`${e.target===ba.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case ba.Vertex:e.sharedData.checks.emitVertex=!0;break;case ba.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\n//${this.name}\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const s of i.endpoints){const i=s.ownerBlock;i&&i.target&e.target&&-1!==t.indexOf(i)&&this._processBuild(i,e,s,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\n${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.target = ${this.target};\n`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`,s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}clone(e,t=""){const i=this.serialize(),s=te(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class Na extends wa{constructor(e){super(e,ba.Neutral),this.complementW=1,this.complementZ=0,this.target=ba.Vertex,this.registerInput("vector",xa.AutoDetect),this.registerInput("transform",xa.Matrix),this.registerOutput("output",xa.Vector4),this.registerOutput("xyz",xa.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){const s=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",s),e.sharedData.blocksWithDefines.push(this);const r=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${r} = mat3(${i.associatedVariableName});\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\n",e.compilationString+=`${r} = transposeMat3(inverseMat3(${r}));\n`,e.compilationString+="#endif\n",t.connectedPoint.type){case xa.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`;break;case xa.Vector3:case xa.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`}}else{const s=i.associatedVariableName;switch(t.connectedPoint.type){case xa.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`;break;case xa.Vector3:case xa.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * ${t.associatedVariableName};\n`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\n`,e}}ee("BABYLON.TransformBlock",Na);class Fa extends wa{constructor(e){super(e,ba.Vertex,!0),this.registerInput("vector",xa.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName};\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n"),this}}function Ba(e,t=Sa.Boolean,i="PROPERTIES",s){return(r,n)=>{let o=r._propStore;o||(o=[],r._propStore=o),o.push({propertyName:n,displayName:e,type:t,groupName:i,options:s??{}})}}ee("BABYLON.VertexOutputBlock",Fa),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(Sa||(Sa={}));class La extends wa{constructor(e){super(e,ba.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",xa.Color4,!0),this.registerInput("rgb",xa.AutoDetect,!0),this.registerInput("a",xa.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&wn(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",r),t.connectedPoint)s.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${s.associatedVariableName});\n`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName};\n`;else if(i.connectedPoint){let t="1.0";s.connectedPoint&&(t=s.associatedVariableName),i.connectedPoint.type===xa.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\n`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t});\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+="gl_FragColor = toLinearSpace(gl_FragColor);\n",e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+="gl_FragColor = toGammaSpace(gl_FragColor);\n",e.compilationString+="#endif\n",(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n"),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="gl_FragData[0] = gl_FragColor;\r\n",e.compilationString+="#endif\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}qe([Ba("Convert to gamma space",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],La.prototype,"convertToGammaSpace",void 0),qe([Ba("Convert to linear space",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],La.prototype,"convertToLinearSpace",void 0),qe([Ba("Use logarithmic depth",Sa.Boolean,"PROPERTIES")],La.prototype,"useLogarithmicDepth",void 0),ee("BABYLON.FragmentOutputBlock",La),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(Ca||(Ca={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(Ea||(Ea={}));class ka{constructor(e=de.Zero(),t=de.Up()){this.position=e,this.normal=t}clone(){return new ka(this.position.clone(),this.normal.clone())}}class Va{constructor(e=de.Zero(),t=de.Up(),i=ue.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new Va(this.position.clone(),this.normal.clone(),this.uv.clone())}}!function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(Aa||(Aa={}));const Ua={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},Ga={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},za={particle_texturemask:!0};class Wa extends wa{get type(){if(this._type===xa.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=xa.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=xa.Vector2,this._type;case"Vector3":return this._type=xa.Vector3,this._type;case"Vector4":return this._type=xa.Vector4,this._type;case"Color3":return this._type=xa.Color3,this._type;case"Color4":return this._type=xa.Color4,this._type;case"Matrix":return this._type=xa.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=xa.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=xa.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=xa.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=xa.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Ea.World:case Ea.WorldView:case Ea.WorldViewProjection:case Ea.View:case Ea.ViewProjection:case Ea.Projection:return this._type=xa.Matrix,this._type;case Ea.CameraPosition:return this._type=xa.Vector3,this._type;case Ea.FogColor:return this._type=xa.Color3,this._type;case Ea.DeltaTime:case Ea.MaterialAlpha:return this._type=xa.Float,this._type;case Ea.CameraParameters:return this._type=xa.Vector4,this._type}}return this._type}constructor(e,t=ba.Vertex,i=xa.AutoDetect){super(e,t,!1),this._mode=Ca.Undefined,this._animationType=Aa.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new X,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=Ca.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===xa.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=Ca.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Ca.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===Ca.Undefined}get isUniform(){return this._mode===Ca.Uniform}set isUniform(e){this._mode=e?Ca.Uniform:Ca.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Ca.Attribute}set isAttribute(e){this._mode=e?Ca.Attribute:Ca.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Ca.Varying}set isVarying(e){this._mode=e?Ca.Varying:Ca.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Ca.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Aa.Time:this.type===xa.Float&&(this.value+=.01*e.getAnimationRatio());break;case Aa.RealTime:this.type===xa.Float&&(this.value=(zt.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\n`:`#ifdef ${e}\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case xa.Float:this.value=0;break;case xa.Vector2:this.value=ue.Zero();break;case xa.Vector3:this.value=de.Zero();break;case xa.Vector4:this.value=_e.Zero();break;case xa.Color3:this.value=Ce.White();break;case xa.Color4:this.value=new Ee(1,1,1,1);break;case xa.Matrix:this.value=fe.Identity()}}_emitConstant(e){switch(this.type){case xa.Float:return`${e._emitFloat(this.value)}`;case xa.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case xa.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case xa.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case xa.Color3:return Ae.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Ae.Color3[0].toGammaSpaceToRef(Ae.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Ae.Color3[0].toLinearSpaceToRef(Ae.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${Ae.Color3[0].r}, ${Ae.Color3[0].g}, ${Ae.Color3[0].b})`;case xa.Color4:return Ae.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Ae.Color4[0].toGammaSpaceToRef(Ae.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Ae.Color4[0].toLinearSpaceToRef(Ae.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${Ae.Color4[0].r}, ${Ae.Color4[0].g}, ${Ae.Color4[0].b}, ${Ae.Color4[0].a})`}return""}get _noContextSwitch(){return Ga[this.name]}_emit(e,t){if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)};\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName};\n`,t&&(e._uniformDeclaration+="#endif\n");const i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case Ea.WorldView:i.needWorldViewMatrix=!0;break;case Ea.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==Aa.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=Ua[this.name]??this.name,this.target===ba.Vertex&&e._vertexState)return void(Ga[this.name]?za[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),Ga[this.name]?za[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName};\n`,t&&(e._attributeDeclaration+="#endif\n"))}}_transmitWorld(e,t,i,s){if(!this._systemValue)return;const r=this.associatedVariableName;switch(this._systemValue){case Ea.World:e.setMatrix(r,t);break;case Ea.WorldView:e.setMatrix(r,i);break;case Ea.WorldViewProjection:e.setMatrix(r,s)}}_transmit(e,t,i){if(this.isAttribute)return;const s=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case Ea.World:case Ea.WorldView:case Ea.WorldViewProjection:return;case Ea.View:e.setMatrix(s,t.getViewMatrix());break;case Ea.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case Ea.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case Ea.CameraPosition:t.bindEyePosition(e,s,!0);break;case Ea.FogColor:e.setColor3(s,t.fogColor);break;case Ea.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case Ea.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Ea.MaterialAlpha:e.setFloat(s,i.alpha)}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(null!==r)switch(this.type){case xa.Float:e.setFloat(s,r);break;case xa.Int:e.setInt(s,r);break;case xa.Color3:Ae.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Ae.Color3[0].toGammaSpaceToRef(Ae.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Ae.Color3[0].toLinearSpaceToRef(Ae.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,Ae.Color3[0]);break;case xa.Color4:Ae.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Ae.Color4[0].toGammaSpaceToRef(Ae.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Ae.Color4[0].toLinearSpaceToRef(Ae.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,Ae.Color4[0]);break;case xa.Vector2:e.setVector2(s,r);break;case xa.Vector3:e.setVector3(s,r);break;case xa.Vector4:e.setVector4(s,r);break;case xa.Matrix:e.setMatrix(s,r)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${Ea[this._systemValue]});\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case xa.Float:i=`${this.value}`;break;case xa.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case xa.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case xa.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case xa.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case xa.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case xa.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===xa.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Aa[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===Ca.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===Ca.Attribute&&e.type===xa.Vector3&&(this._type=xa.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=te(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}ee("BABYLON.InputBlock",Wa);class Ha extends wa{constructor(e){super(e,ba.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",xa.AutoDetect,!1,ba.VertexAndFragment),this.registerOutput("rgba",xa.Color4,ba.Neutral),this.registerOutput("rgb",xa.Color3,ba.Neutral),this.registerOutput("r",xa.Float,ba.Neutral),this.registerOutput("g",xa.Float,ba.Neutral),this.registerOutput("b",xa.Float,ba.Neutral),this.registerOutput("a",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?ba.VertexAndFragment:ba.Fragment:ba.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ba.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}else this.uv.ownerBlock.target!==ba.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ba.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target!==ba.Fragment?(e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"):e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==ba.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}ee("BABYLON.CurrentScreenBlock",Ha);class Xa extends wa{constructor(e){super(e,ba.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",xa.AutoDetect,!1,ba.VertexAndFragment),this.registerOutput("rgba",xa.Color4,ba.Neutral),this.registerOutput("rgb",xa.Color3,ba.Neutral),this.registerOutput("r",xa.Float,ba.Neutral),this.registerOutput("g",xa.Float,ba.Neutral),this.registerOutput("b",xa.Float,ba.Neutral),this.registerOutput("a",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name&&t(e)));i||(i=new Wa("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"}_buildBlock(e){if(super._buildBlock(e),e.target===ba.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}ee("BABYLON.ParticleTextureBlock",Xa);class Ya extends wa{constructor(e){super(e,ba.Fragment),this._isUnique=!0,this.registerInput("color",xa.Color4,!1,ba.Fragment),this.registerOutput("rampColor",xa.Color4,ba.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==ba.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${this._declareOutput(this.rampColor,e)} = baseColor;\n #else\n ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}ee("BABYLON.ParticleRampGradientBlock",Ya);class Qa extends wa{constructor(e){super(e,ba.Fragment),this._isUnique=!0,this.registerInput("color",xa.Color4,!1,ba.Fragment),this.registerInput("alphaTexture",xa.Float,!1,ba.Fragment),this.registerInput("alphaColor",xa.Float,!1,ba.Fragment),this.registerOutput("blendColor",xa.Color4,ba.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==ba.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${this._declareOutput(this.blendColor,e)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}ee("BABYLON.ParticleBlendMultiplyBlock",Qa);class ja{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;n!==Ai.Depth&&n!==Ai.DepthStencil||(i=!0,r=t[t.length-1].format,s--);const o=[],a=[],l=[],h=[],c=[],u=[],d=[],_={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,o,e._hardwareTexture.underlyingResource,s)}this._engine._bindUnboundFramebuffer(n)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1&&(15===o.format?u=i.DEPTH_COMPONENT16:16===o.format?u=i.DEPTH_COMPONENT24:17===o.format||13===o.format?u=i.DEPTH24_STENCIL8:14===o.format?u=i.DEPTH_COMPONENT32F:18===o.format&&(u=i.DEPTH32F_STENCIL8)),o.is2DArray?i.texImage3D(n,0,u,o.width,o.height,s,0,c,h,null):o.is3D?i.texImage3D(n,0,u,o.width,o.height,r,0,c,h,null):i.texImage2D(n,0,u,o.width,o.height,0,c,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(o),o},ki.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t};class qa{static RegisterShaderCodeProcessing(e,t){t?qa._CustomShaderCodeProcessing[e??""]=t:delete qa._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return qa._CustomShaderCodeProcessing[e]??qa._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,o=1,a,l,h=null,c=0,u="postprocess",d,_=!1,p=5,f=ui.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new ds(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new ue(1,1),this._texelSize=ue.Zero(),this.onActivateObservable=new X,this.onSizeChangedObservable=new X,this.onApplyObservable=new X,this.onBeforeRenderObservable=new X,this.onAfterRenderObservable=new X,this.name=e;let m=1,g=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,m=e.size??1,n=e.camera??null,o=e.samplingMode??1,a=e.engine,l=e.reusable,h=e.defines??null,c=e.textureType??0,u=e.vertexUrl??"postprocess",d=e.indexParameters,_=e.blockCompilation??!1,p=e.textureFormat??5,f=e.shaderLanguage??ui.GLSL,g=e.uniformBuffers??null}else r&&(m="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):a&&(this._engine=a,this._engine.postProcesses.push(this)),this._options=m,this.renderTargetSamplingMode=o||1,this._reusable=l||!1,this._textureType=c,this._textureFormat=p,this._shaderLanguage=f,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=g||[],this._indexParameters=d,this._drawWrapper=new Fi(this._engine),_||this.updateEffect(h)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new ds(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,a){const l=qa._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=l.defineCustomBindings(this.name,e,s,r),t=s,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:a??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(e,t)=>l.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:l?.processFinalCode?(e,t)=>l.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,a/h),this._engine.bindFramebuffer(u,0,o,a,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),qa._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=yt.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=qa.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=te(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return yt.Parse((()=>new qa(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,s)}}qa._CustomShaderCodeProcessing={},qe([st()],qa.prototype,"uniqueId",void 0),qe([st()],qa.prototype,"name",void 0),qe([st()],qa.prototype,"width",void 0),qe([st()],qa.prototype,"height",void 0),qe([st()],qa.prototype,"renderTargetSamplingMode",void 0),qe([ut()],qa.prototype,"clearColor",void 0),qe([st()],qa.prototype,"autoClear",void 0),qe([st()],qa.prototype,"forceAutoClearInAlphaMode",void 0),qe([st()],qa.prototype,"alphaMode",void 0),qe([st()],qa.prototype,"alphaConstants",void 0),qe([st()],qa.prototype,"enablePixelPerfectMode",void 0),qe([st()],qa.prototype,"forceFullscreenViewport",void 0),qe([st()],qa.prototype,"scaleMode",void 0),qe([st()],qa.prototype,"alwaysForcePOT",void 0),qe([st("samples")],qa.prototype,"_samples",void 0),qe([st()],qa.prototype,"adaptScaleToCurrentViewport",void 0),ee("BABYLON.PostProcess",qa);class Za extends wa{constructor(e){super(e,ba.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",xa.Vector4,!0),this.registerInput("xyz ",xa.Vector3,!0),this.registerInput("xy ",xa.Vector2,!0),this.registerInput("zw ",xa.Vector2,!0),this.registerInput("x",xa.Float,!0),this.registerInput("y",xa.Float,!0),this.registerInput("z",xa.Float,!0),this.registerInput("w",xa.Float,!0),this.registerOutput("xyzw",xa.Vector4),this.registerOutput("xyz",xa.Vector3),this.registerOutput("xy",xa.Vector2),this.registerOutput("zw",xa.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\n`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`,e}}ee("BABYLON.VectorMergerBlock",Za);class Ja extends wa{constructor(e){super(e,ba.Neutral),this.sourceRange=new ue(-1,1),this.targetRange=new ue(0,1),this.registerInput("input",xa.AutoDetect),this.registerInput("sourceMin",xa.Float,!0),this.registerInput("sourceMax",xa.Float,!0),this.registerInput("targetMin",xa.Float,!0),this.registerInput("targetMax",xa.Float,!0),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${i});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=ue.FromArray(e.sourceRange),this.targetRange=ue.FromArray(e.targetRange)}}qe([Ba("From",Sa.Vector2)],Ja.prototype,"sourceRange",void 0),qe([Ba("To",Sa.Vector2)],Ja.prototype,"targetRange",void 0),ee("BABYLON.RemapBlock",Ja);class el extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(xa.Float),this.right.acceptedConnectionPointTypes.push(xa.Float),this._connectionObservers=[this.left.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.left.onDisconnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onDisconnectionObservable.add((()=>this._updateInputOutputTypes()))]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===xa.Int||this.left.type===xa.Float&&this.right.type!==xa.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[xa.Int,xa.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==xa.Int&&t.type!==xa.Float||e.acceptedConnectionPointTypes.push(xa.Vector2,xa.Vector3,xa.Vector4,xa.Color3,xa.Color4,xa.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}}class tl extends el{constructor(e){super(e)}getClassName(){return"MultiplyBlock"}_buildBlock(e){return super._buildBlock(e),e.compilationString+=this._declareOutput(this.output,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\n`,this}}var il;ee("BABYLON.MultiplyBlock",tl),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(il||(il={}));class sl extends Oa{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class rl{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:de.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:de.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:de.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:de.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let s=0;for(const i of t){if(i.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=de.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new de(10,10,10),this.onAnimationEnd=null,this.blendMode=rl.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new ue(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new de(0,0,0),this._useLogarithmicDepth=!1,this.gravity=de.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new Ee(1,1,1,1),this.color2=new Ee(1,1,1,1),this.colorDead=new Ee(0,0,0,1),this.textureMask=new Ee(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new sl,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new de(0,1,0),i=new de(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,s=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,s){throw new Error("Method not implemented.")}}rl.BLENDMODE_ONEONE=0,rl.BLENDMODE_STANDARD=1,rl.BLENDMODE_ADD=2,rl.BLENDMODE_MULTIPLY=3,rl.BLENDMODE_MULTIPLYADD=4;class nl extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("rgba",xa.Color4,!0),this.registerInput("rgb ",xa.Color3,!0),this.registerOutput("rgb",xa.Color3),this.registerOutput("r",xa.Float),this.registerOutput("g",xa.Float),this.registerOutput("b",xa.Float),this.registerOutput("a",xa.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb;\n`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.r;\n`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.g;\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b;\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.a;\n`),this}}ee("BABYLON.ColorSplitterBlock",nl),ki.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1);const r=this._gl,n=new Pi(this,Ai.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const o=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);1!==s.type||this._caps.textureFloat||(s.type=0,we.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,o.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const a=r.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),i.setTextures(n),i};const ol={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class al{constructor(e,t=ol){this._fullscreenViewport=new jr(0,0,1,1);const i=t.positions??ol.positions,s=t.indices??ol.indices;this.engine=e,this._vertexBuffers={[ys.PositionKind]:new ys(e,i,ys.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[ys.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[ys.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class ll{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new X;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new Fi(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new Ti(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const hl="passPixelShader",cl="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";bi.ShadersStore[hl]=cl;const ul=hl,dl=cl;class _l{static _CreateDumpRenderer(){if(!_l._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new ki(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new ki(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;const s=new al(t),r=new ll({engine:t,name:ul,fragmentShader:dl,samplerNames:["textureSampler"]});_l._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return _l._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const a=await i.readPixels(0,0,e,t),l=new Uint8Array(a.buffer);_l.DumpData(e,t,l,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,a){return new Promise((l=>{_l.DumpData(e,t,i,(e=>l(e)),s,r,n,o,a)}))}static DumpData(e,t,i,s,r="image/png",n,o=!1,a=!1,l){const h=_l._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*xe.Clamp(s))}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),a?hs.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),r,l):hs.EncodeScreenshotCanvasData(h.canvas,s,r,n,l),c.dispose()}static Dispose(){_l._DumpToolsEngine&&(_l._DumpToolsEngine.wrapper.dispose(),_l._DumpToolsEngine.renderer.dispose(),_l._DumpToolsEngine.engine.dispose()),_l._DumpToolsEngine=null}}hs.DumpData=_l.DumpData,hs.DumpDataAsync=_l.DumpDataAsync,hs.DumpFramebuffer=_l.DumpFramebuffer;class pl extends Vo{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=Z(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new X,this.onAfterUnbindObservable=new X,this.onBeforeRenderObservable=new X,this.onAfterRenderObservable=new X,this.onClearObservable=new X,this.onResizeObservable=new X,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=de.Zero(),!(i=this.getScene()))return;const x=this.getScene().getEngine();this._gammaSpace=v,this._coordinatesMode=Vo.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=x.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new Ps(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:_,creationFlags:p,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:g,label:this.name},this.samplingMode===Vo.NEAREST_SAMPLINGMODE&&(this.wrapU=Vo.CLAMP_ADDRESSMODE,this.wrapV=Vo.CLAMP_ADDRESSMODE),d||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Vo.INVCUBIC_MODE,this._textureMatrix=fe.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;return this._size.depth||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){const n=this.getScene();if(!n)return;const o=n.getEngine();if(o._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&1===o.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let a=null;const l=this.renderList?this.renderList:n.getActiveMeshes().data,h=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(a=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,l,h)),a?this._prepareRenderingManager(a,a.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(l,h,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),a=l);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,a,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&_l.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&5===e&&o.generateMipMapsForCubemap(this._texture),o._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new pl(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===pl.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=pl.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}pl.REFRESHRATE_RENDER_ONCE=0,pl.REFRESHRATE_RENDER_ONEVERYFRAME=1,pl.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Vo._CreateRenderTargetTexture=(e,t,i,s,r)=>new pl(e,t,i,s);class fl{constructor(e){this.name=Rs.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(Rs.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){hs.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}bi.ShadersStore.proceduralVertexShader="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class ml extends Vo{constructor(e,t,i,s,r=null,n=!0,o=!1,a=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new X,this.onBeforeGenerationObservable=new X,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===r||r instanceof Vo?(this._options={},this._fallbackTexture=r):(this._options=r,this._fallbackTexture=r.fallbackTexture??null);let l=(s=this.getScene()||se.LastCreatedScene)._getComponent(Rs.NAME_PROCEDURALTEXTURE);l||(l=new fl(s),s._addComponent(l)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=a,this._generateMipMaps=n,this._drawWrapper=new Fi(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,n,a);this._texture=h.texture;const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[ys.PositionKind]=new ys(this._fullEngine,c,ys.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===pl.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=pl.REFRESHRATE_RENDER_ONCE)}reset(){this._drawWrapper.effect?.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady())return void e(this);const t=this.getEffect();t&&t.executeWhenCompiled((()=>{e(this)}))}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[ys.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,(()=>{this._rtWrapper?.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;i._debugPushGroup?.(`procedural texture generation for ${this.name}`,1);const s=i.currentViewport;if(this.isCube)for(let e=0;e<6;e++)i.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(uo.TriangleFillMode,0,6);else i.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(uo.TriangleFillMode,0,6);i.unBindFramebuffer(this._rtWrapper,this.isCube),s&&i.setViewport(s),this.isCube&&i.generateMipMapsForCubemap(this._texture),i._debugPopGroup?.(1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new ml(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){const e=this.getScene();if(!e)return;const t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[ys.PositionKind];i&&(i.dispose(),this._vertexBuffers[ys.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var gl;qe([st()],ml.prototype,"isEnabled",void 0),qe([st()],ml.prototype,"autoClear",void 0),qe([st()],ml.prototype,"_generateMipMaps",void 0),qe([st()],ml.prototype,"_size",void 0),qe([st()],ml.prototype,"refreshRate",null),ee("BABYLON.ProceduralTexture",ml),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(gl||(gl={}));class vl extends wa{constructor(e){super(e,ba.Neutral),this.operation=gl.Cos,this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case gl.Cos:i="cos";break;case gl.Sin:i="sin";break;case gl.Abs:i="abs";break;case gl.Exp:i="exp";break;case gl.Exp2:i="exp2";break;case gl.Round:i="round";break;case gl.Floor:i="floor";break;case gl.Ceiling:i="ceil";break;case gl.Sqrt:i="sqrt";break;case gl.Log:i="log";break;case gl.Tan:i="tan";break;case gl.ArcTan:i="atan";break;case gl.ArcCos:i="acos";break;case gl.ArcSin:i="asin";break;case gl.Fract:i="fract";break;case gl.Sign:i="sign";break;case gl.Radians:i="radians";break;case gl.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${gl[this.operation]};\n`}}ee("BABYLON.TrigonometryBlock",vl);const xl={effect:null,subMesh:null};class bl extends Oa{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Tl extends Ra{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"ReflectionTextureBlock"===e.getClassName()||"ReflectionBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||se.LastCreatedScene),this._buildId=Tl._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new fe,this._cachedWorldViewProjectionMatrix=new fe,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new X,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=il.Material,this.forceAlphaBlending=!1,this._options={emitComments:!1,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return hs.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&ba.Vertex&&this._addVertexOutputNode(e),e.target&ba.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(e.target&ba.Vertex&&this._removeVertexOutputNode(e),e.target&ba.Fragment&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=ba.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=ba.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,s=!0){(e.target===ba.VertexAndFragment||t.target===ba.Fragment&&e.target===ba.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const r=n.ownerBlock;r!==e&&this._processInitializeOnLink(r,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===ba.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;const s=this.getScene().getEngine(),r=this._mode===il.Particle;if(0===this._vertexOutputNodes.length&&!r)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new Ia,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=ba.Vertex,this._fragmentCompilationState=new Ia,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=ba.Fragment,this._sharedData=new Ma,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=r;const n=[],o=[];for(const e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);this.optimize();for(const e of n)e.build(this._vertexCompilationState,n);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of o)this._resetDualBlocks(e,this._buildId-1);for(const e of o)e.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Tl._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(we.Log("Vertex shader:"),we.Log(this._vertexCompilationState.compilationString),we.Log("Fragment shader:"),we.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const e of a)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(ys.NormalKind),t.TANGENT=e.isVerticesDataPresent(ys.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(ys.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let i=1;i<=6;++i){const s=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==s}const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;ao(this.getScene(),t,!a),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate((e=>"PrePassOutputBlock"===e.getClassName())),t=[4];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t):t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter((e=>"PrePassTextureBlock"===e.getClassName())),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const e of t)i.texturesRequired.includes(e)||i.texturesRequired.push(e);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==il.PostProcess?(we.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,a=5){let l=this.name+this._buildId;const h=new bl,c=new Sn(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),Ti.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new qa(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete Ti.ShadersStore[l+"VertexShader"],delete Ti.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&(Ti.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Vi.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==il.ProceduralTexture)return we.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new ml(i,e,null,t),r=new Sn(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new bl,o=this._processDefines(r,n);Ti.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ys.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(a);let l=this._buildId;return s.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete Ti.ShadersStore[i+"VertexShader"],delete Ti.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);const e=this._processDefines(r,n);e&&(Ti.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Vi.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ys.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),e?.fallbacks,void 0),s._setEffect(a)}))),this._checkInternals(a)})),s}_createEffectForParticles(e,t,i,s,r,n,o,a=""){let l=this.name+this._buildId+"_"+t;n||(n=new bl),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new Sn(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=a;if(!r){const a=this._processDefines(o,n);Ti.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t),u=c.join("\n"),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,a?.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add((r=>{h!==this._buildId&&(delete Ti.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t);const d=c.join("\n");d!==u&&(n.markAllAsDirty(),u=d);const _=this._processDefines(o,n);if(_)return Ti.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,_?.fallbacks,i,s,e),e.setCustomEffect(r,t),void this._createEffectForParticles(e,t,i,s,r,n,o,a);this._checkInternals(r)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===il.Particle?(this._createEffectForParticles(e,rl.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,rl.BLENDMODE_MULTIPLY,t,i)):we.Log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===il.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):we.Log("Incompatible material mode")}_processDefines(e,t,i=!1,s){let r=null;if(lo(this.getScene(),t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((s=>{s.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((r=>{r.prepareDefines(e,this,t,i,s)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const s=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,s)}));const n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===n.indexOf(e)&&n.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new ja;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),r={lightDisposed:i,uniformBuffers:s,mergedUniforms:n,mergedSamplers:o,fallbacks:a}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const e=s.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(s);this._animationFrame=e}}const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new bl);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,n,i))))return!1;const a=this._processDefines(e,n,i,t);if(a){const e=t.effect,i=n.toString();let r=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS}},o);if(r)if(this._onEffectCreatedObservable&&(xl.effect=r,xl.subMesh=t,this._onEffectCreatedObservable.notifyObservers(xl)),this.allowShaderHotSwapping&&e&&!r.isReady()){if(r=e,n.markAsUnprocessed(),a.lightDisposed)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(r,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return`// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,i,t.visibility),o=this._sharedData;if(n){for(const e of o.bindableBlocks)e.bind(r,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);for(const e of o.inputBlocks)e._transmit(r,s,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Tl._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:Tl.EditorURL;hs.LoadBabylonScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()}))}else this._createNodeEditor(e?.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Wa("Position");e.setAsAttribute("position");const t=new Wa("World");t.setAsSystemValue(Ea.World);const i=new Na("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Wa("ViewProjection");s.setAsSystemValue(Ea.ViewProjection);const r=new Na("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new Fa("VertexOutput");r.connectTo(n);const o=new Wa("color");o.value=new Ee(.8,.8,.8,1);const a=new La("FragmentOutput");o.connectTo(a),this.addOutputNode(n),this.addOutputNode(a),this._mode=il.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Wa("Position");e.setAsAttribute("position2d");const t=new Wa("Constant1");t.isConstant=!0,t.value=1;const i=new Za("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Fa("VertexOutput");i.connectTo(s);const r=new Wa("Scale");r.visibleInInspector=!0,r.value=new ue(1,1);const n=new Ja("uv0");e.connectTo(n);const o=new tl("UV scale");n.connectTo(o),r.connectTo(o);const a=new Ha("CurrentScreen");o.connectTo(a),a.texture=new Vo("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new La("FragmentOutput");a.connectTo(l,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(l),this._mode=il.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Wa("Position");e.setAsAttribute("position2d");const t=new Wa("Constant1");t.isConstant=!0,t.value=1;const i=new Za("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Fa("VertexOutput");i.connectTo(s);const r=new Wa("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=Aa.Time,r.isConstant=!1;const n=new Wa("Color3");n.value=new Ce(1,1,1),n.isConstant=!1;const o=new La("FragmentOutput"),a=new Za("VectorMerger");a.visibleInInspector=!1;const l=new vl("Cos");l.operation=gl.Cos,e.connectTo(a),r.output.connectTo(l.input),l.output.connectTo(a.z),a.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=il.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Wa("uv");e.setAsAttribute("particle_uv");const t=new Xa("ParticleTexture");e.connectTo(t);const i=new Wa("Color");i.setAsAttribute("particle_color");const s=new tl("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new Ya("ParticleRampGradient");s.connectTo(r);const n=new nl("ColorSplitter");i.connectTo(n);const o=new Qa("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const a=new La("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=il.Particle}async loadAsync(e,t=""){return Tl.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,t);const s=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\n`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${il[this.mode]};\n`;for(const s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));for(const t of s)t.isInput&&-1===e.indexOf(t)&&(r+=t._dumpCode(i,e));e=[],r+="\n// Connections\n";for(const t of this._vertexOutputNodes)r+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)r+=t._dumpCodeForOutputConnections(e);r+="\n// Output nodes\n";for(const e of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;for(const e of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;return r+="nodeMaterial.build();\n",r}serialize(e){const t=e?{}:yt.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}parseSerializedObject(e,t="",i=!1){i||this.clear();const s={};for(const i of e.blocks){const e=te(i.customType);if(e){const r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,i=t._tempEntryPointUniqueId;i&&s[i].attachToEndpoint(t)}for(let t=0;tnew Tl(e,this.getScene(),this.options)),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach((t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise(((e,t)=>{i.onLoadedObservable.addOnce((()=>{e()})),i.onErrorObservable.addOnce((e=>{t(e)}))})))})),Promise.all(e)}static Parse(e,t,i=""){const s=yt.Parse((()=>new Tl(e.name,t)),e,t,i);return s.parseSerializedObject(e,i),s.build(),s}static async ParseFromFileAsync(e,t,i,s="",r=!1,n){const o=n??new Tl(e,i),a=await i._loadFileAsync(t),l=JSON.parse(a);return o.parseSerializedObject(l,s),r||o.build(),o}static ParseFromSnippetAsync(e,t=se.LastCreatedScene,i="",s,r=!1,n=!1){return"_BLANK"===e?Promise.resolve(Tl.CreateDefault("blank",t)):new Promise(((o,a)=>{const l=new At;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const h=JSON.parse(JSON.parse(l.responseText).jsonPayload),c=JSON.parse(h.nodeMaterial);s||((s=yt.Parse((()=>new Tl(e,t)),c,t,i)).uniqueId=t.getUniqueId()),s.parseSerializedObject(c),s.snippetId=e;try{r||s.build()}catch(e){a(e)}n?s.whenTexturesReadyAsync().then((()=>{o(s)})).catch((e=>{a(e)})):o(s)}else a("Unable to load the snippet "+e)})),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()}))}static CreateDefault(e,t){const i=new Tl(e,t);return i.setToDefault(),i.build(),i}}function yl(e){const t=e.sideOrientation||cn.DEFAULTSIDE,i=e.radius||1,s=void 0===e.flat||e.flat,r=0|(e.subdivisions||4),n=e.radiusX||i,o=e.radiusY||i,a=e.radiusZ||i,l=(1+Math.sqrt(5))/2,h=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],p=[],f=[],m=[],g=[];let v=0;const x=new Array(3),b=new Array(3);let T;for(T=0;T<3;T++)x[T]=de.Zero(),b[T]=ue.Zero();for(let e=0;e<20;e++){for(T=0;T<3;T++){const t=c[3*e+T];x[T].copyFromFloats(h[3*u[t]],h[3*u[t]+1],h[3*u[t]+2]),x[T].normalize(),b[T].copyFromFloats(.134765625*d[2*t]+.05859375+-.0390625*_[e],.2333984375*d[2*t+1]+.025390625+.01953125*_[e])}const t=(e,t,i,l)=>{const h=de.Lerp(x[0],x[2],t/r),c=de.Lerp(x[1],x[2],t/r),u=r===t?x[2]:de.Lerp(h,c,e/(r-t));let d;if(u.normalize(),s){const e=de.Lerp(x[0],x[2],l/r),t=de.Lerp(x[1],x[2],l/r);d=de.Lerp(e,t,i/(r-l))}else d=new de(u.x,u.y,u.z);d.x/=n,d.y/=o,d.z/=a,d.normalize();const _=ue.Lerp(b[0],b[2],t/r),T=ue.Lerp(b[1],b[2],t/r),y=r===t?b[2]:ue.Lerp(_,T,e/(r-t));f.push(u.x*n,u.y*o,u.z*a),m.push(d.x,d.y,d.z),g.push(y.x,dn.UseOpenGLOrientationForUV?1-y.y:y.y),p.push(v),v++};for(let e=0;eSl(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(El||(El={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(Al||(Al={}));const Pl=[Al.WRIST,Al.THUMB_METACARPAL,Al.THUMB_PHALANX_PROXIMAL,Al.THUMB_PHALANX_DISTAL,Al.THUMB_TIP,Al.INDEX_FINGER_METACARPAL,Al.INDEX_FINGER_PHALANX_PROXIMAL,Al.INDEX_FINGER_PHALANX_INTERMEDIATE,Al.INDEX_FINGER_PHALANX_DISTAL,Al.INDEX_FINGER_TIP,Al.MIDDLE_FINGER_METACARPAL,Al.MIDDLE_FINGER_PHALANX_PROXIMAL,Al.MIDDLE_FINGER_PHALANX_INTERMEDIATE,Al.MIDDLE_FINGER_PHALANX_DISTAL,Al.MIDDLE_FINGER_TIP,Al.RING_FINGER_METACARPAL,Al.RING_FINGER_PHALANX_PROXIMAL,Al.RING_FINGER_PHALANX_INTERMEDIATE,Al.RING_FINGER_PHALANX_DISTAL,Al.RING_FINGER_TIP,Al.PINKY_FINGER_METACARPAL,Al.PINKY_FINGER_PHALANX_PROXIMAL,Al.PINKY_FINGER_PHALANX_INTERMEDIATE,Al.PINKY_FINGER_PHALANX_DISTAL,Al.PINKY_FINGER_TIP],Rl={[El.WRIST]:[Al.WRIST],[El.THUMB]:[Al.THUMB_METACARPAL,Al.THUMB_PHALANX_PROXIMAL,Al.THUMB_PHALANX_DISTAL,Al.THUMB_TIP],[El.INDEX]:[Al.INDEX_FINGER_METACARPAL,Al.INDEX_FINGER_PHALANX_PROXIMAL,Al.INDEX_FINGER_PHALANX_INTERMEDIATE,Al.INDEX_FINGER_PHALANX_DISTAL,Al.INDEX_FINGER_TIP],[El.MIDDLE]:[Al.MIDDLE_FINGER_METACARPAL,Al.MIDDLE_FINGER_PHALANX_PROXIMAL,Al.MIDDLE_FINGER_PHALANX_INTERMEDIATE,Al.MIDDLE_FINGER_PHALANX_DISTAL,Al.MIDDLE_FINGER_TIP],[El.RING]:[Al.RING_FINGER_METACARPAL,Al.RING_FINGER_PHALANX_PROXIMAL,Al.RING_FINGER_PHALANX_INTERMEDIATE,Al.RING_FINGER_PHALANX_DISTAL,Al.RING_FINGER_TIP],[El.LITTLE]:[Al.PINKY_FINGER_METACARPAL,Al.PINKY_FINGER_PHALANX_PROXIMAL,Al.PINKY_FINGER_PHALANX_INTERMEDIATE,Al.PINKY_FINGER_PHALANX_DISTAL,Al.PINKY_FINGER_TIP]};class Il{get handMesh(){return this._handMesh}getHandPartMeshes(e){return Rl[e].map((e=>this._jointMeshes[Pl.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[Pl.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new X,this._jointTransforms=new Array(Pl.length),this._jointTransformMatrices=new Float32Array(16*Pl.length),this._tempJointMatrix=new fe,this._jointRadii=new Float32Array(Pl.length),this._scene=t[0].getScene();for(let e=0;e{e._doNotLoadControllerMesh=!0}))}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>{e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){const e=this._handMesh.skeleton;Pl.forEach(((i,s)=>{const r=e.getBoneIndexByName(t?t[i]:i);-1!==r&&e.bones[r].linkTransformNode(this._jointTransforms[s])}))}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=Pl.map((e=>s[e]||i.get(e)));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let i=0;i{const i=this._jointTransforms[t];fe.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const s=this._jointRadii[t]*this._jointScaleFactor,r=this._jointMeshes[t];r.isVisible=!this._handMesh&&!this._jointsInvisible,r.position.copyFrom(i.position),r.rotationQuaternion.copyFrom(i.rotationQuaternion),r.scaling.setAll(s),this._scene.useRightHandedSystem||(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){this._handMesh&&(e?(this._handMesh.skeleton?.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class Ml extends ua{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{const s=[],r=e.jointMeshes?.sourceMesh||Sl("jointParent",Ml._ICOSPHERE_PARAMS);r.isVisible=!!e.jointMeshes?.keepOriginalVisible;for(let t=0;t{const r={};Ml._RightHandGLB?.meshes[1]?.isDisposed()&&(Ml._RightHandGLB=null),Ml._LeftHandGLB?.meshes[1]?.isDisposed()&&(Ml._LeftHandGLB=null);const n=!(!Ml._RightHandGLB||!Ml._LeftHandGLB),o=await Promise.all([Ml._RightHandGLB||Pa.ImportMeshAsync("",Ml.DEFAULT_HAND_MODEL_BASE_URL,Ml.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Ml._LeftHandGLB||Pa.ImportMeshAsync("",Ml.DEFAULT_HAND_MODEL_BASE_URL,Ml.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Ml._RightHandGLB=o[0],Ml._LeftHandGLB=o[1];const a=await Tl.ParseFromFileAsync("handShader",Ml.DEFAULT_HAND_MODEL_SHADER_URL,e);a.needDepthPrePass=!0,a.transparencyMode=uo.MATERIAL_ALPHABLEND,a.alphaMode=2,a.build(!1);const l={base:Ce.FromInts(116,63,203),fresnel:Ce.FromInts(149,102,229),fingerColor:Ce.FromInts(177,130,255),tipFresnel:Ce.FromInts(220,200,255),...i?.handMeshes?.customColors},h={base:a.getBlockByName("baseColor"),fresnel:a.getBlockByName("fresnelColor"),fingerColor:a.getBlockByName("fingerColor"),tipFresnel:a.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const c=t._getBaseLayerWrapper()?.isMultiview;["left","right"].forEach((t=>{const i="left"==t?Ml._LeftHandGLB:Ml._RightHandGLB;if(!i)throw new Error("Could not load hand model");const s=i.meshes[1];s._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,c||(s.material=a.clone(`${t}HandShaderClone`,!0)),s.isVisible=!1,r[t]=s,n||e.useRightHandedSystem||i.meshes[1].rotate(_r.Y,Math.PI)})),a.dispose(),s({left:r.left,right:r.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[Al.WRIST]:`wrist_${t}`,[Al.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[Al.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[Al.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[Al.THUMB_TIP]:`thumb_tip_${t}`,[Al.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[Al.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[Al.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[Al.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[Al.INDEX_FINGER_TIP]:`index_tip_${t}`,[Al.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[Al.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[Al.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[Al.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[Al.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[Al.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[Al.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[Al.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[Al.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[Al.RING_FINGER_TIP]:`ring_tip_${t}`,[Al.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[Al.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[Al.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[Al.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[Al.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new X,this.onHandRemovedObservable=new X,this._attachHand=e=>{if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const t=e.inputSource.handedness,i=new Il(e,this._handResources.jointMeshes[t],this._handResources.handMeshes&&this._handResources.handMeshes[t],this._handResources.rigMappings&&this._handResources.rigMappings[t],this.options.handMeshes?.meshesUseLeftHandedCoordinates,this.options.jointMeshes?.invisible,this.options.jointMeshes?.scaleFactor);this._attachedHands[e.uniqueId]=i,this._trackingHands[t]=i,this.onHandAddedObservable.notifyObservers(i)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},s={};[[i.rigMapping.left,e],[i.rigMapping.right,s]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[Pl[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:s}}}attach(){return!!super.attach()&&(this._handResources={jointMeshes:Ml._GenerateTrackedJointMeshes(this.options),handMeshes:this.options.handMeshes?.customMeshes||null,rigMappings:this.options.handMeshes?.customRigMappings||null},this.options.handMeshes?.customMeshes||this.options.handMeshes?.disableDefaultMeshes||(Ml._GenerateDefaultHandMeshesAsync(se.LastCreatedScene,this._xrSessionManager,this.options).then((e=>{this._handResources.handMeshes=e,this._handResources.rigMappings={left:Ml._GenerateDefaultHandMeshRigMapping("left"),right:Ml._GenerateDefaultHandMeshRigMapping("right")},this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),this._trackingHands.right?.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)})),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add((e=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor))}))),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){this._trackingHands.left?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),this._trackingHands.right?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){const i=this.getHandByControllerId(e);if(i){const s="left"==i.xrController.inputSource.handedness?"left":"right";this._trackingHands[s]?.xrController.uniqueId===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e,this.options.handMeshes?.disposeOnSessionEnd))),this.options.handMeshes?.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose()))),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)}dispose(){super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!this.options.handMeshes?.customMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Ml._RightHandGLB=null,Ml._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}var Ol,Dl,wl;Ml.Name=ha.HAND_TRACKING,Ml.Version=1,Ml.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",Ml.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",Ml.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",Ml.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",Ml._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},Ml._RightHandGLB=null,Ml._LeftHandGLB=null,ca.AddWebXRFeature(Ml.Name,((e,t)=>()=>new Ml(e,t)),Ml.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(Ol||(Ol={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(Dl||(Dl={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(wl||(wl={}));class Nl{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=wl.PALM_AND_GAZE,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=Ol.ULNAR_SIDE,this.zoneOrientationMode=Dl.HAND_ROTATION,this.nodeOrientationMode=Dl.HAND_ROTATION,this.handedness="none",this.lerpTime=100,this._zoneAxis[Ol.ABOVE_FINGER_TIPS]=new de(0,1,0),this._zoneAxis[Ol.RADIAL_SIDE]=new de(-1,0,0),this._zoneAxis[Ol.ULNAR_SIDE]=new de(1,0,0),this._zoneAxis[Ol.BELOW_WRIST]=new de(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(e="none"===this.handedness?this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh(Al.PINKY_FINGER_METACARPAL),i=e.getJointMesh(Al.MIDDLE_FINGER_METACARPAL),s=e.getJointMesh(Al.WRIST);if(s&&i&&t){const r={position:i.absolutePosition,quaternion:new pe,id:e.xrController.uniqueId},n=ge.Vector3[0],o=ge.Vector3[1],a=ge.Vector3[2];return n.copyFrom(i.absolutePosition).subtractInPlace(s.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),de.CrossToRef(n,o,o),de.CrossToRef(o,n,a),pe.FromLookDirectionLHToRef(o,n,r.quaternion),r}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=pe.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{const e=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,e){const i=ge.Vector3[0],s=this._scene.activeCamera;i.copyFrom(this._zoneAxis[this.targetZone]);const r=ge.Quaternion[0];if(s&&(this.zoneOrientationMode===Dl.LOOK_AT_CAMERA||this.nodeOrientationMode===Dl.LOOK_AT_CAMERA)){const t=ge.Vector3[1];t.copyFrom(s.position).subtractInPlace(e.position).normalize(),this._scene.useRightHandedSystem?pe.FromLookDirectionRHToRef(t,de.UpReadOnly,r):pe.FromLookDirectionLHToRef(t,de.UpReadOnly,r)}this.zoneOrientationMode===Dl.HAND_ROTATION?e.quaternion.toRotationMatrix(ge.Matrix[0]):r.toRotationMatrix(ge.Matrix[0]),de.TransformNormalToRef(i,ge.Matrix[0],i),i.scaleInPlace(this.targetOffset);const n=ge.Vector3[2],o=ge.Quaternion[1];n.copyFrom(e.position).addInPlace(i),this.nodeOrientationMode===Dl.HAND_ROTATION?o.copyFrom(e.quaternion):o.copyFrom(r);const a=Date.now()-t;de.SmoothToRef(this._node.position,n,a,this.lerpTime,this._node.position),pe.SmoothToRef(this._node.rotationQuaternion,o,a,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=e.id}this._setVisibility(e),t=Date.now()}))}_setVisibility(e){let t=!0,i=!0;const s=this._scene.activeCamera;if(s){const r=s.getForwardRay();if(this.handConstraintVisibility===wl.GAZE_FOCUS||this.handConstraintVisibility===wl.PALM_AND_GAZE){let t;i=!1,this._eyeTracking&&(t=this._eyeTracking.getEyeGaze()),t=t||r;const s=ge.Vector3[0];e?e.position.subtractToRef(t.origin,s):this._node.getAbsolutePosition().subtractToRef(t.origin,s);const n=de.Dot(s,t.direction),o=n*n;n>0&&s.lengthSquared()-o2*this.palmUpStrictness-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(t){try{this._eyeTracking=t.getEnabledFeature(ha.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(ha.HAND_TRACKING)}catch{hs.Error("Hand tracking must be enabled for the Hand Menu to work")}}else hs.Error("XR features manager must be available or provided directly for the Hand Menu to work")}}class Fl{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=de.Zero(),this.poleTargetPosition=de.Zero(),this.poleTargetLocalOffset=de.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=pe.Identity(),this._bone1Mat=fe.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=de.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const s=t.getParent();if(!s)return this._notEnoughInformation=!0,void we.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=s,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void we.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const r=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,r.x>r.y&&r.x>r.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone2Length=de.Distance(t,i),this._bone1Length=de.Distance(i,s)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone1Length=de.Distance(i,s)}this._bone1.getRotationMatrixToRef(lr.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Fl._TmpMats[0],s=Fl._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&de.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const r=Fl._TmpVecs[0],n=Fl._TmpVecs[1],o=Fl._TmpVecs[2],a=Fl._TmpVecs[3],l=Fl._TmpVecs[4],h=Fl._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,r),t.subtractToRef(r,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(r,a),a.normalize(),de.CrossToRef(a,l,n),n.normalize(),de.CrossToRef(a,n,o),o.normalize(),fe.FromXYZAxesToRef(o,a,n,i);const c=this._bone1Length,u=this._bone2Length;let d=de.Distance(r,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let _=(u*u+d*d-c*c)/(2*u*d),p=(d*d+c*c-u*u)/(2*d*c);_>1&&(_=1),p>1&&(p=1),_<-1&&(_=-1),p<-1&&(p=-1);const f=Math.acos(_),m=Math.acos(p);let g=-f-m;if(this._rightHandedSystem)fe.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(i,i),fe.RotationAxisToRef(this._bendAxis,m,s),s.multiplyToRef(i,i);else{const e=Fl._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,fe.RotationAxisToRef(e,-m,s),s.multiplyToRef(i,i)}this.poleAngle&&(fe.RotationAxisToRef(a,this.poleAngle,s),i.multiplyToRef(s,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||pe.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),pe.FromRotationMatrixToRef(i,h),pe.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,lr.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,lr.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,lr.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new pe),e.getRotationQuaternionToRef(lr.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Fl._TmpVecs=[de.Zero(),de.Zero(),de.Zero(),de.Zero(),de.Zero(),de.Zero()],Fl._TmpQuat=pe.Identity(),Fl._TmpMats=[fe.Identity(),fe.Identity()];class Bl{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,s){if(this.upAxis=de.Up(),this.upAxisSpace=lr.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=pe.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=de.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,s){if(s.adjustYaw&&(this.adjustYaw=s.adjustYaw),s.adjustPitch&&(this.adjustPitch=s.adjustPitch),s.adjustRoll&&(this.adjustRoll=s.adjustRoll),null!=s.maxYaw?this.maxYaw=s.maxYaw:this.maxYaw=Math.PI,null!=s.minYaw?this.minYaw=s.minYaw:this.minYaw=-Math.PI,null!=s.maxPitch?this.maxPitch=s.maxPitch:this.maxPitch=Math.PI,null!=s.minPitch?this.minPitch=s.minPitch:this.minPitch=-Math.PI,null!=s.slerpAmount&&(this.slerpAmount=s.slerpAmount),null!=s.upAxis&&(this.upAxis=s.upAxis),null!=s.upAxisSpace&&(this.upAxisSpace=s.upAxisSpace),null!=s.yawAxis||null!=s.pitchAxis){let e=_r.Y,t=_r.X;null!=s.yawAxis&&(e=s.yawAxis.clone(),e.normalize()),null!=s.pitchAxis&&(t=s.pitchAxis.clone(),t.normalize());const i=de.Cross(t,e);this._transformYawPitch=fe.Identity(),fe.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==s.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=s.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=lr.BONE||(this.upAxisSpace=lr.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=Bl._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const s=Bl._TmpMats[0],r=Bl._TmpMats[1],n=this.mesh,o=e.getParent(),a=Bl._TmpVecs[1];a.copyFrom(this.upAxis),this.upAxisSpace==lr.BONE&&o?(this._transformYawPitch&&de.TransformCoordinatesToRef(a,this._transformYawPitchInv,a),o.getDirectionToRef(a,this.mesh,a)):this.upAxisSpace==lr.LOCAL&&(n.getDirectionToRef(a,a),1==n.scaling.x&&1==n.scaling.y&&1==n.scaling.z||a.normalize());let l=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(l=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),l||h){const e=Bl._TmpMats[2],s=Bl._TmpMats[3];if(this.upAxisSpace==lr.BONE&&1==a.y&&o)o.getRotationMatrixToRef(lr.WORLD,this.mesh,e);else if(this.upAxisSpace!=lr.LOCAL||1!=a.y||o){let t=Bl._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&de.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),o?o.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);const i=de.Cross(a,t);i.normalize(),t=de.Cross(i,a),fe.FromXYZAxesToRef(i,a,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(s);let r=null;if(h){const n=Bl._TmpVecs[3];i.subtractToRef(t,n),de.TransformCoordinatesToRef(n,s,n),r=Math.sqrt(n.x*n.x+n.z*n.z);const o=Math.atan2(n.y,r);let a=o;o>this._maxPitch?(n.y=this._maxPitchTan*r,a=this._maxPitch):othis._maxYaw||aMath.PI?this._isAngleBetween(o,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,l=this._maxYaw):this._isAngleBetween(o,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*r,n.x=this._minYawSin*r,l=this._minYaw):a>this._maxYaw?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,o<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):aMath.PI){const e=Bl._TmpVecs[8];e.copyFrom(_r.Z),this._transformYawPitch&&de.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=Bl._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),de.TransformCoordinatesToRef(e,t,e),de.TransformCoordinatesToRef(e,s,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,o)>this._getAngleBetween(i,this._midYawConstraint)){null==r&&(r=Math.sqrt(n.x*n.x+n.z*n.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e{const e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(ys.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(ys.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(ys.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),ys.prototype._rebuild=function(){this._buffer?._rebuild(),this._alignedBuffer?._rebuild()},ys.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._alignedBuffer?.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},ys.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},ys.prototype._alignBuffer=function(){const e=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4==0&&this.byteOffset%4==0||!e)return;const t=ys.GetTypeByteLength(this.type),i=this.byteStride+3&-4,s=i/t,r=this._maxVerticesCount,n=r*i/t;let o,a;if(Array.isArray(e)){const t=new Float32Array(e);o=new DataView(t.buffer,t.byteOffset,t.byteLength)}else o=e instanceof ArrayBuffer?new DataView(e,0,e.byteLength):new DataView(e.buffer,e.byteOffset,e.byteLength);a=this.type===ys.BYTE?new Int8Array(n):this.type===ys.UNSIGNED_BYTE?new Uint8Array(n):this.type===ys.SHORT?new Int16Array(n):this.type===ys.UNSIGNED_SHORT?new Uint16Array(n):this.type===ys.INT?new Int32Array(n):this.type===ys.UNSIGNED_INT?new Uint32Array(n):new Float32Array(n);const l=this.getSize();let h=this.byteOffset;for(let e=0;e{if(t.type!==Ms.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===Xs.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ms.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}qe([st()],Vl.prototype,"wheelPrecisionX",void 0),qe([st()],Vl.prototype,"wheelPrecisionY",void 0),qe([st()],Vl.prototype,"wheelPrecisionZ",void 0);class Ul{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const o=n.event,a="touch"===o.pointerType;if(n.type!==Ms.POINTERMOVE&&-1===this.buttons.indexOf(o.button))return;const l=o.target;if(this._altKey=o.altKey,this._ctrlKey=o.ctrlKey,this._metaKey=o.metaKey,this._shiftKey=o.shiftKey,this._buttonsPressed=o.buttons,t.isPointerLock){const e=o.movementX,t=o.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==Ms.POINTERDOWN&&a&&this._pointA?.pointerId!==o.pointerId&&this._pointB?.pointerId!==o.pointerId)return;if(n.type!==Ms.POINTERDOWN||-1!==this._currentActiveButton&&!a)if(n.type===Ms.POINTERDOUBLETAP)this.onDoubleTap(o.pointerType);else if(n.type!==Ms.POINTERUP||this._currentActiveButton!==o.button&&!a){if(n.type===Ms.POINTERMOVE)if(e||o.preventDefault(),this._pointA&&null===this._pointB){const e=o.clientX-this._pointA.x,t=o.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=o.clientX,this._pointA.y=o.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===o.pointerId?this._pointA:this._pointB;e.x=o.clientX,e.y=o.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:o.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,s,a,r,l),r=l,s=a}}else{try{l?.releasePointerCapture(o.pointerId)}catch(e){}a||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==o.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==o.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==s||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(o),e||o.preventDefault()}else{try{l?.setPointerCapture(o.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType};else{if(null!==this._pointB)return;this._pointB={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType}}-1!==this._currentActiveButton||a||(this._currentActiveButton=o.button),this.onButtonDown(o),e||(o.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ms.POINTERDOWN|Ms.POINTERUP|Ms.POINTERMOVE|Ms.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&hs.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&hs.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}qe([st()],Ul.prototype,"buttons",void 0);var Gl,zl,Wl,Hl,Xl,Yl,Ql={};class jl{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?we.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!Kr.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const i=this.attached[e],s=yt.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=Ql[e];if(i){const s=t[e],r=yt.Parse((()=>new i),s,null);this.add(r)}}}else for(const t in this.attached){const i=Ql[this.attached[t].getClassName()];if(i){const s=yt.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class Kl{constructor(e,t){this.x=e,this.y=t}}class $l{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=$l.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}$l.GAMEPAD=0,$l.GENERIC=1,$l.XBOX=2,$l.POSE_ENABLED=3,$l.DUALSHOCK=4;class ql extends $l{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new X,this.onButtonUpObservable=new X,this.type=$l.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==$l.POSE_ENABLED&&(this.gamepad&&e.type!==$l.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType($l.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}qe([st()],Zl.prototype,"gamepadRotationSensibility",void 0),qe([st()],Zl.prototype,"gamepadMoveSensibility",void 0),Ql.ArcRotateCameraGamepadInput=Zl;class Jl{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===Ns.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ms.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===Xs.DOM_DELTA_LINE?40:1,n=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=xe.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else s=n/(40*this.wheelPrecision);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ms.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=ir.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,fe.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=de.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/is&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,r=this._getPosition(),n=ge.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(s),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}th.MinimumRadiusForPinch=.001,qe([st()],th.prototype,"buttons",void 0),qe([st()],th.prototype,"angularSensibilityX",void 0),qe([st()],th.prototype,"angularSensibilityY",void 0),qe([st()],th.prototype,"pinchPrecision",void 0),qe([st()],th.prototype,"pinchDeltaPercentage",void 0),qe([st()],th.prototype,"useNaturalPinchZoom",void 0),qe([st()],th.prototype,"pinchZoom",void 0),qe([st()],th.prototype,"panningSensibility",void 0),qe([st()],th.prototype,"multiTouchPanning",void 0),qe([st()],th.prototype,"multiTouchPanAndZoom",void 0),Ql.ArcRotateCameraPointersInput=th;class ih extends jl{constructor(e){super(e)}addMouseWheel(){return this.add(new eh),this}addPointers(){return this.add(new th),this}addKeyboard(){return this.add(new Jl),this}}ih.prototype.addVRDeviceOrientation=function(){return this.add(new sh),this};class sh{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):hs.Warn("Permission not granted.")})).catch((e=>{hs.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Ql.ArcRotateCameraVRDeviceOrientationInput=sh;class rh{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(t.type===Ns.KEYDOWN)-1===this.keysForward.indexOf(i.keyCode)&&-1===this.keysBackward.indexOf(i.keyCode)&&-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(e)}),Ms.POINTERDOWN|Ms.POINTERUP|Ms.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)}))}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==Ms.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const s=t.target;if(e.type===Ms.POINTERDOWN){try{s?.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===Ms.POINTERUP){try{s?.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===Ms.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const s=t.clientX-this._previousPosition.x,r=t.clientY-this._previousPosition.y;this._rotateCamera(s,r),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=(e*=i._calculateHandednessMultiplier())/this.angularSensibility,r=t/this.angularSensibility,n=pe.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let o;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(o=pe.RotationAxis(_r.X,r),n.multiplyInPlace(o)),this.buttonsYaw.some((e=>e===this.activeButton))){o=pe.RotationAxis(_r.Y,s),n.multiplyInPlace(o);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(o=pe.RotationAxis(_r.Z,-s),i._trackRoll-=s,n.multiplyInPlace(o)),n.toEulerAnglesToRef(i.rotation)}}qe([st()],nh.prototype,"buttons",void 0),qe([st()],nh.prototype,"angularSensibility",void 0),Ql.FlyCameraMouseInput=nh;class oh{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===Ns.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)}))}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}qe([st()],oh.prototype,"keysHeightOffsetIncr",void 0),qe([st()],oh.prototype,"keysHeightOffsetDecr",void 0),qe([st()],oh.prototype,"keysHeightOffsetModifierAlt",void 0),qe([st()],oh.prototype,"keysHeightOffsetModifierCtrl",void 0),qe([st()],oh.prototype,"keysHeightOffsetModifierShift",void 0),qe([st()],oh.prototype,"keysRotationOffsetIncr",void 0),qe([st()],oh.prototype,"keysRotationOffsetDecr",void 0),qe([st()],oh.prototype,"keysRotationOffsetModifierAlt",void 0),qe([st()],oh.prototype,"keysRotationOffsetModifierCtrl",void 0),qe([st()],oh.prototype,"keysRotationOffsetModifierShift",void 0),qe([st()],oh.prototype,"keysRadiusIncr",void 0),qe([st()],oh.prototype,"keysRadiusDecr",void 0),qe([st()],oh.prototype,"keysRadiusModifierAlt",void 0),qe([st()],oh.prototype,"keysRadiusModifierCtrl",void 0),qe([st()],oh.prototype,"keysRadiusModifierShift",void 0),qe([st()],oh.prototype,"heightSensibility",void 0),qe([st()],oh.prototype,"rotationSensibility",void 0),qe([st()],oh.prototype,"radiusSensibility",void 0),Ql.FollowCameraKeyboardMoveInput=oh;class ah{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ms.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&we.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=.01*r*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=.01*r*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=.01*r*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ms.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}qe([st()],ah.prototype,"axisControlRadius",void 0),qe([st()],ah.prototype,"axisControlHeight",void 0),qe([st()],ah.prototype,"axisControlRotation",void 0),qe([st()],ah.prototype,"wheelPrecision",void 0),qe([st()],ah.prototype,"wheelDeltaPercentage",void 0),Ql.FollowCameraMouseWheelInput=ah;class lh extends Ul{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,s,r,n){if(0===i&&null===r)return;if(0===s&&null===n)return;let o=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&we.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&we.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&we.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}qe([st()],lh.prototype,"angularSensibilityX",void 0),qe([st()],lh.prototype,"angularSensibilityY",void 0),qe([st()],lh.prototype,"pinchPrecision",void 0),qe([st()],lh.prototype,"pinchDeltaPercentage",void 0),qe([st()],lh.prototype,"axisXControlRadius",void 0),qe([st()],lh.prototype,"axisXControlHeight",void 0),qe([st()],lh.prototype,"axisXControlRotation",void 0),qe([st()],lh.prototype,"axisYControlRadius",void 0),qe([st()],lh.prototype,"axisYControlHeight",void 0),qe([st()],lh.prototype,"axisYControlRotation",void 0),qe([st()],lh.prototype,"axisPinchControlRadius",void 0),qe([st()],lh.prototype,"axisPinchControlHeight",void 0),qe([st()],lh.prototype,"axisPinchControlRotation",void 0),Ql.FollowCameraPointersInput=lh;class hh{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===Ns.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const r=s.event,n="touch"===r.pointerType;if(!this.touchEnabled&&n)return;if(s.type!==Ms.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const o=r.target;if(s.type===Ms.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{o?.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===Ms.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o?.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===Ms.POINTERMOVE&&(this._activePointerId===r.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(r.clientX-this._previousPosition.x)*t,s=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=s/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:s}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),r=i.movementX*s;this.camera.cameraRotation.y+=r/this.angularSensibility;const n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ms.POINTERDOWN|Ms.POINTERUP|Ms.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}qe([st()],ch.prototype,"buttons",void 0),qe([st()],ch.prototype,"angularSensibility",void 0),Ql.FreeCameraMouseInput=ch,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(Gl||(Gl={}));class uh extends Vl{constructor(){super(...arguments),this._moveRelative=de.Zero(),this._rotateRelative=de.Zero(),this._moveScene=de.Zero(),this._wheelXAction=Gl.MoveRelative,this._wheelXActionCoordinate=hr.X,this._wheelYAction=Gl.MoveRelative,this._wheelYActionCoordinate=hr.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==Gl.MoveRelative||(this._wheelXAction=Gl.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Gl.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==Gl.MoveRelative||(this._wheelYAction=Gl.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Gl.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==Gl.MoveRelative||(this._wheelZAction=Gl.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Gl.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==Gl.RotateRelative||(this._wheelXAction=Gl.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Gl.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==Gl.RotateRelative||(this._wheelYAction=Gl.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Gl.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==Gl.RotateRelative||(this._wheelZAction=Gl.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Gl.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==Gl.MoveScene||(this._wheelXAction=Gl.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Gl.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==Gl.MoveScene||(this._wheelYAction=Gl.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Gl.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==Gl.MoveScene||(this._wheelZAction=Gl.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Gl.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=fe.Zero();this.camera.getViewMatrix().invertToRef(e);const t=de.Zero();de.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(0===e)return;if(null===t||null===i)return;let s=null;switch(t){case Gl.MoveRelative:s=this._moveRelative;break;case Gl.RotateRelative:s=this._rotateRelative;break;case Gl.MoveScene:s=this._moveScene}switch(i){case hr.X:s.set(e,0,0);break;case hr.Y:s.set(0,e,0);break;case hr.Z:s.set(0,0,e)}}}qe([st()],uh.prototype,"wheelXMoveRelative",null),qe([st()],uh.prototype,"wheelYMoveRelative",null),qe([st()],uh.prototype,"wheelZMoveRelative",null),qe([st()],uh.prototype,"wheelXRotateRelative",null),qe([st()],uh.prototype,"wheelYRotateRelative",null),qe([st()],uh.prototype,"wheelZRotateRelative",null),qe([st()],uh.prototype,"wheelXMoveScene",null),qe([st()],uh.prototype,"wheelYMoveScene",null),qe([st()],uh.prototype,"wheelZMoveScene",null),Ql.FreeCameraMouseWheelInput=uh;class dh{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=hs.IsSafari()}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r="mouse"===s.pointerType||this._isSafari&&void 0===s.pointerType;if(this.allowMouse||!r)if(i.type===Ms.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),1!==this._pointerPressed.length)return;t={x:s.clientX,y:s.clientY}}else if(i.type===Ms.POINTERUP){e||s.preventDefault();const i=this._pointerPressed.indexOf(s.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===Ms.POINTERMOVE){if(e||s.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(s.pointerId))return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ms.POINTERDOWN|Ms.POINTERUP|Ms.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new de(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);fe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(de.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}qe([st()],dh.prototype,"touchAngularSensibility",void 0),qe([st()],dh.prototype,"touchMoveSensibility",void 0),Ql.FreeCameraTouchInput=dh;class _h extends jl{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new hh),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new ch(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new uh,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new dh),this}clear(){super.clear(),this._mouseInput=null}}_h.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new ph,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class ph{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout((()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",r):hs.Warn("Permission not granted.")})).catch((e=>{hs.Error(e)})):window.addEventListener("deviceorientation",r)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new pe,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new X,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-hs.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?hs.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?hs.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?hs.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new pe(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new pe),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():hs.Warn("Permission not granted.")})).catch((e=>{hs.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(pe.RotationYawPitchRollToRef(hs.ToRadians(this._alpha),hs.ToRadians(this._beta),-hs.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Ql.FreeCameraDeviceOrientationInput=ph;class fh{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=fe.Identity(),this._deltaTransform=de.Zero(),this._vector3=de.Zero(),this._vector2=ue.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==$l.POSE_ENABLED&&(this.gamepad&&e.type!==$l.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType($l.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):fe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*s,0,-t.y*s),de.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}qe([st()],fh.prototype,"gamepadAngularSensibility",void 0),qe([st()],fh.prototype,"gamepadMoveSensibility",void 0),Ql.FreeCameraGamepadInput=fh,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(zl||(zl={}));class mh{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...mh._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,mh._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=zl.X,this._axisTargetedByUpAndDown=zl.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new ps,this.deltaPosition=de.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{mh._VJCanvasWidth=window.innerWidth,mh._VJCanvasHeight=window.innerHeight,mh.Canvas&&(mh.Canvas.width=mh._VJCanvasWidth,mh.Canvas.height=mh._VJCanvasHeight),mh._HalfWidth=mh._VJCanvasWidth/2},!mh.Canvas){window.addEventListener("resize",this._onResize,!1),mh.Canvas=document.createElement("canvas"),mh._VJCanvasWidth=window.innerWidth,mh._VJCanvasHeight=window.innerHeight,mh.Canvas.width=window.innerWidth,mh.Canvas.height=window.innerHeight,mh.Canvas.style.width="100%",mh.Canvas.style.height="100%",mh.Canvas.style.position="absolute",mh.Canvas.style.backgroundColor="transparent",mh.Canvas.style.top="0px",mh.Canvas.style.left="0px",mh.Canvas.style.zIndex="5",mh.Canvas.style.touchAction="none",mh.Canvas.setAttribute("touch-action","none");const e=mh.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");mh._VJCanvasContext=e,mh._VJCanvasContext.strokeStyle="#ffffff",mh._VJCanvasContext.lineWidth=2,document.body.appendChild(mh.Canvas)}mh._HalfWidth=mh.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&mh._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new ue(0,0),this._joystickPreviousPointerPos=new ue(0,0),this._joystickPointerStartPos=new ue(0,0),this._deltaJoystickVector=new ue(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},mh.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),mh.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),mh.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),mh.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),mh.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXmh._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):mh._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new ue(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?mh._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.strokeStyle=this._joystickColor,mh._VJCanvasContext.lineWidth=2,mh._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),mh._VJCanvasContext.stroke(),mh._VJCanvasContext.closePath(),mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.lineWidth=6,mh._VJCanvasContext.strokeStyle=this._joystickColor,mh._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),mh._VJCanvasContext.stroke(),mh._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?mh._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.strokeStyle=this._joystickColor,mh._VJCanvasContext.lineWidth=2,mh._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),mh._VJCanvasContext.stroke(),mh._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(mh._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.fillStyle="white",mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.strokeStyle="red",mh._VJCanvasContext.lineWidth=6,mh._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),mh._VJCanvasContext.stroke(),mh._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){mh.Canvas&&(mh.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),mh.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),mh.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),mh.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(mh.Canvas),mh.Canvas=null),this._released=!0}}mh._GlobalJoystickIndex=0,mh._AlwaysVisibleSticks=0,_h.prototype.addVirtualJoystick=function(){return this.add(new gh),this};class gh{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=fe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=de.TransformCoordinates(new de(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new mh(!0),this._leftjoystick.setAxisForUpDown(zl.Z),this._leftjoystick.setAxisForLeftRight(zl.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new mh(!1),this._rightjoystick.setAxisForUpDown(zl.X),this._rightjoystick.setAxisForLeftRight(zl.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Ql.FreeCameraVirtualJoystickInput=gh,Ct.AddNodeConstructor("TargetCamera",((e,t)=>()=>new vh(e,de.Zero(),t)));class vh extends Kr{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=de.Zero(),this._tmpTargetVector=de.Zero(),this.cameraDirection=new de(0,0,0),this.cameraRotation=new ue(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new pe,this.rotation=new de(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=de.Zero(),this._initialFocalDistance=1,this._viewMatrix=fe.Zero(),this._camMatrix=fe.Zero(),this._cameraTransformMatrix=fe.Zero(),this._cameraRotationMatrix=fe.Zero(),this._referencePoint=new de(0,0,1),this._transformedReferencePoint=de.Zero(),this._deferredPositionUpdate=new de,this._deferredRotationQuaternionUpdate=new pe,this._deferredRotationUpdate=new de,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=de.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new pe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=K),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),fe.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&pe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(ge.Matrix[0]),de.TransformNormalToRef(this.cameraDirection,ge.Matrix[0],ge.Vector3[0]),this._deferredPositionUpdate.addInPlace(ge.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(pe.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x){this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>gn.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new _h(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=hs.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new de(0,0,0),this.cameraRotation=new ue(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?de.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=de.Zero(),this._transformedDirection=de.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}qe([lt()],xh.prototype,"ellipsoid",void 0),qe([lt()],xh.prototype,"ellipsoidOffset",void 0),qe([st()],xh.prototype,"checkCollisions",void 0),qe([st()],xh.prototype,"applyGravity",void 0),Ct.AddNodeConstructor("TouchCamera",((e,t)=>()=>new bh(e,de.Zero(),t)));class bh extends xh{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}Ct.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new Th(e,0,0,1,de.Zero(),t)));class Th extends vh{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new fe,this._upToYMatrix=new fe,this._upVector=de.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){fe.RotationAlignToRef(de.UpReadOnly,this._upVector,this._yToUpMatrix),fe.RotationAlignToRef(this._upVector,de.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Qo,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new jo,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Yo,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,de.Zero(),n,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=de.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=ue.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new fe,this.panningAxis=new de(1,1,0),this._transformedDirection=new de,this.mapPanning=!1,this.onMeshTargetChangedObservable=new X,this.checkCollisions=!1,this.collisionRadius=new de(.5,.5,.5),this._previousPosition=de.Zero(),this._collisionVelocity=de.Zero(),this._newPosition=de.Zero(),this._computationVector=de.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*o,this.radius*n,this.radius*r*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=de.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new ih(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=ue.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)}attachControl(e,t,i=!0,s=2){const r=arguments;t=hs.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||de.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||de.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=bo.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(void 0===e.min){const t=e||this.getScene().meshes;i=bo.MinMax(t),s=de.Distance(i.min,i.max)}else i=e,s=e.distance;this._target=bo.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Kr.RIG_MODE_STEREOSCOPIC_INTERLACED:case Kr.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new Th(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Kr.RIG_MODE_STEREOSCOPIC_INTERLACED:case Kr.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=de.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),o=n*r,a=.5*s*i,l=a*Math.sqrt(1+1/(o*o)),h=a*Math.sqrt(1+1/(n*n));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}qe([st()],Th.prototype,"alpha",void 0),qe([st()],Th.prototype,"beta",void 0),qe([st()],Th.prototype,"radius",void 0),qe([st()],Th.prototype,"overrideCloneAlphaBetaRadius",void 0),qe([lt("target")],Th.prototype,"_target",void 0),qe([ht("targetHost")],Th.prototype,"_targetHost",void 0),qe([st()],Th.prototype,"inertialAlphaOffset",void 0),qe([st()],Th.prototype,"inertialBetaOffset",void 0),qe([st()],Th.prototype,"inertialRadiusOffset",void 0),qe([st()],Th.prototype,"lowerAlphaLimit",void 0),qe([st()],Th.prototype,"upperAlphaLimit",void 0),qe([st()],Th.prototype,"lowerBetaLimit",void 0),qe([st()],Th.prototype,"upperBetaLimit",void 0),qe([st()],Th.prototype,"lowerRadiusLimit",void 0),qe([st()],Th.prototype,"upperRadiusLimit",void 0),qe([st()],Th.prototype,"inertialPanningX",void 0),qe([st()],Th.prototype,"inertialPanningY",void 0),qe([st()],Th.prototype,"pinchToPanMaxDistance",void 0),qe([st()],Th.prototype,"panningDistanceLimit",void 0),qe([lt()],Th.prototype,"panningOriginTarget",void 0),qe([st()],Th.prototype,"panningInertia",void 0),qe([st()],Th.prototype,"zoomToMouseLocation",null),qe([st()],Th.prototype,"zoomOnFactor",void 0),qe([at()],Th.prototype,"targetScreenOffset",void 0),qe([st()],Th.prototype,"allowUpsideDown",void 0),qe([st()],Th.prototype,"useInputToRestoreState",void 0),Ct.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new yh(e,de.Zero(),t)));class yh extends xh{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new pe,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new pe,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new pe),pe.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=_r.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new pe),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class Sh extends jl{constructor(e){super(e)}addKeyboard(){return this.add(new rh),this}addMouse(){return this.add(new nh),this}}class Ch extends vh{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new de(1,1,1),this.ellipsoidOffset=new de(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=de.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=de.Zero(),this._diffPosition=de.Zero(),this._newPosition=de.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>gn.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new Sh(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=hs.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new de(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?de.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=de.Zero(),this._transformedDirection=de.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}qe([lt()],Ch.prototype,"ellipsoid",void 0),qe([lt()],Ch.prototype,"ellipsoidOffset",void 0),qe([st()],Ch.prototype,"checkCollisions",void 0),qe([st()],Ch.prototype,"applyGravity",void 0);class Eh extends jl{constructor(e){super(e)}addKeyboard(){return this.add(new oh),this}addMouseWheel(){return this.add(new ah),this}addPointers(){return this.add(new lh),this}addVRDeviceOrientation(){return we.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Ct.AddNodeConstructor("FollowCamera",((e,t)=>()=>new Ah(e,de.Zero(),t))),Ct.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new Ph(e,0,0,1,null,t)));class Ah extends vh{constructor(e,t,i,s=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=s,this.inputs=new Eh(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=ge.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=hs.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,a=n-this.position.x,l=r.y+this.heightOffset-this.position.y,h=o-this.position.z;let c=a*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new de(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(r)}attachControl(e,t){t=hs.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}qe([st()],Ah.prototype,"radius",void 0),qe([st()],Ah.prototype,"lowerRadiusLimit",void 0),qe([st()],Ah.prototype,"upperRadiusLimit",void 0),qe([st()],Ah.prototype,"rotationOffset",void 0),qe([st()],Ah.prototype,"lowerRotationOffsetLimit",void 0),qe([st()],Ah.prototype,"upperRotationOffsetLimit",void 0),qe([st()],Ah.prototype,"heightOffset",void 0),qe([st()],Ah.prototype,"lowerHeightOffsetLimit",void 0),qe([st()],Ah.prototype,"upperHeightOffsetLimit",void 0),qe([st()],Ah.prototype,"cameraAcceleration",void 0),qe([st()],Ah.prototype,"maxCameraSpeed",void 0),qe([ht("lockedTargetId")],Ah.prototype,"lockedTarget",void 0);class Ph extends vh{constructor(e,t,i,s,r,n){super(e,de.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=de.Zero(),this.setMeshTarget(r)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}!function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Wl||(Wl={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Hl||(Hl={}));class Rh extends $l{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new X,this.onButtonUpObservable=new X,this.onPadDownObservable=new X,this.onPadUpObservable=new X,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=$l.XBOX,this._isXboxOnePad=s}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,Wl.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,Wl.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,Wl.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,Wl.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Wl.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Wl.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Wl.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Wl.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Wl.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Wl.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Hl.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Hl.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Hl.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Hl.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Xl||(Xl={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Yl||(Yl={}));class Ih extends $l{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new X,this.onButtonUpObservable=new X,this.onPadDownObservable=new X,this.onPadUpObservable=new X,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=$l.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Xl.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Xl.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Xl.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Xl.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Xl.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Xl.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Xl.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Xl.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Xl.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Xl.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Yl.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Yl.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Yl.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Yl.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class Mh{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new X,Lt()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new X((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=$l.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),s=-1!==e.id.search("Xbox One");return t=s||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Rh(e.id,e.index,e,s):i?new Ih(e.id,e.index,e):new ql(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch{-1===this._loggedErrors.indexOf(t.index)&&(hs.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&gn.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new Dh(e,de.Zero(),t)));class Dh extends bh{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}Kr._CreateDefaultParsedCamera=(e,t)=>new Dh(e,de.Zero(),t),Ct.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new wh(e,de.Zero(),t)));class wh extends Dh{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}bi.ShadersStore.passCubePixelShader="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";class Nh extends qa{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,a)}static _Parse(e,t,i,s){return yt.Parse((()=>new Nh(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}ee("BABYLON.PassPostProcess",Nh);class Fh extends qa{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"passCube",null,null,t,i,s,r,n,"#define POSITIVEX",o,void 0,null,a),this._face=0}static _Parse(e,t,i,s){return yt.Parse((()=>new Fh(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}gn._RescalePostProcessFactory=e=>new Nh("rescale",1,null,2,e,!1,0);bi.ShadersStore.anaglyphPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}";class Bh extends qa{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function Lh(e){e._rigCameras[0]._rigPostProcess=new Nh(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Bh(e.name+"_anaglyph",1,e._rigCameras)}ee("BABYLON.AnaglyphPostProcess",Bh),Ct.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new kh(e,0,0,1,de.Zero(),i.interaxial_distance,t)));class kh extends Th{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=()=>Lh(this),this.interaxialDistance=n,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Ct.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new Vh(e,de.Zero(),i.interaxial_distance,t)));class Vh extends xh{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Lh(this),this.interaxialDistance=i,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Ct.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new Uh(e,de.Zero(),i.interaxial_distance,t)));class Uh extends wh{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Lh(this),this.interaxialDistance=i,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Ct.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new Gh(e,de.Zero(),i.interaxial_distance,t)));class Gh extends Dh{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Lh(this),this.interaxialDistance=i,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}bi.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";class zh extends qa{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new ue(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new ue(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}class Wh extends qa{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,s,r,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,r,n,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new ue(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new ue(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function Hh(e){const t=e.cameraRigMode===Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===Kr.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new Nh(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new zh(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new jr(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new jr(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}Ct.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new Xh(e,0,0,1,de.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Xh extends Th{constructor(e,t,i,s,r,n,o,a){super(e,t,i,s,r,a),this._setRigMode=()=>Hh(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Ct.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Yh(e,de.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Yh extends xh{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hh(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Ct.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new Qh(e,de.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Qh extends wh{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hh(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Ct.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new jh(e,de.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class jh extends Dh{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hh(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class Kh extends Dh{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,s=1,r=.065){super(e,t,i),this._distanceBetweenEyes=r,this._distanceToProjectionPlane=s,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=r}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new vh(e,de.Zero(),this.getScene()),i=new xn("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(fe.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new $h(e,de.Zero(),t)));class $h extends xh{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class qh{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return fe.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return fe.Translation(-e,0,0)}get leftPreViewMatrix(){return fe.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return fe.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new qh;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}bi.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";class Zh extends qa{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,Vo.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new ue(2,2/this.aspectRatio),this._scaleFactor=new ue(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new ue(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}bi.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";class Jh extends pl{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function ec(e,t){const i=new bs(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}gn.prototype.createMultiviewRenderTargetTexture=function(e,t,i,s){const r=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=r.createFramebuffer();const o=new Pi(this,Ai.Unknown,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,i),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.RGBA8,e,t,2)),n._colorTextureArray=i,s||(s=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,s),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=s,o.isReady=!0,n.setTextures(o),n._depthStencilTexture=o,n},gn.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},gn.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},Kr.prototype._useMultiviewToSingleView=!1,Kr.prototype._multiviewTexture=null,Kr.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Jh(this.getScene(),{width:e,height:t})):this._multiviewTexture=new Jh(this.getScene(),{width:e,height:t})};const tc=dr.prototype.createSceneUniformBuffer;dr.prototype._transformMatrixR=fe.Zero(),dr.prototype._multiviewSceneUbo=null,dr.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=ec(this.getEngine(),"scene_multiview")},dr.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?ec(this.getEngine(),e):tc.bind(this)(e)},dr.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,ge.Matrix[0]),sr.GetRightPlaneToRef(ge.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},dr.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",s._multiviewTexture)}))}}function sc(e,t){const i=t.vrCameraMetrics||qh.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new jr(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new fe,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new jr(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new fe,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new ic("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(we.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Zh("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Zh("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}Ct.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new rc(e,0,0,1,de.Zero(),t)));class rc extends Th{constructor(e,t,i,s,r,n,o=!0,a=qh.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=e=>sc(this,e),a.compensateDistortion=o,this.setCameraRigMode(Kr.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Ct.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new nc(e,de.Zero(),t)));class nc extends yh{constructor(e,t,i,s=!0,r=qh.GetDefault()){super(e,t,i),this._setRigMode=e=>sc(this,e),r.compensateDistortion=s,this.setCameraRigMode(Kr.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Ct.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new oc(e,de.Zero(),t)));class oc extends nc{constructor(e,t,i,s=!0,r=qh.GetDefault()){super(e,t,i,s,r),this._setRigMode=e=>sc(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class ac{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class lc{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,gn.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}}lc._DiffuseTextureEnabled=!0,lc._DetailTextureEnabled=!0,lc._DecalMapEnabled=!0,lc._AmbientTextureEnabled=!0,lc._OpacityTextureEnabled=!0,lc._ReflectionTextureEnabled=!0,lc._EmissiveTextureEnabled=!0,lc._SpecularTextureEnabled=!0,lc._BumpTextureEnabled=!0,lc._LightmapTextureEnabled=!0,lc._RefractionTextureEnabled=!0,lc._ColorGradingTextureEnabled=!0,lc._FresnelEnabled=!0,lc._ClearCoatTextureEnabled=!0,lc._ClearCoatBumpTextureEnabled=!0,lc._ClearCoatTintTextureEnabled=!0,lc._SheenTextureEnabled=!0,lc._AnisotropicTextureEnabled=!0,lc._ThicknessTextureEnabled=!0,lc._RefractionIntensityTextureEnabled=!0,lc._TranslucencyIntensityTextureEnabled=!0,lc._IridescenceTextureEnabled=!0;bi.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";bi.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";bi.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n";bi.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n";bi.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";bi.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";bi.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n";bi.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";bi.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";bi.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X};\n#endif\n#endif\n";bi.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";bi.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";bi.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n/* disable_uniformity_analysis */\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; ithis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[cc._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case En.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let t in r){let r="";for(const s of this._activePlugins){let o=s.getCustomCode(i)?.[t];if(o){if(s.resolveIncludes){if(null===n){const t=ui.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:bi.GetShadersRepository(t),includesShadersStore:bi.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,xi._ProcessIncludes(o,n,(e=>o=e))}r+=o+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=hc.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,n=new RegExp(t,e);let o=n.exec(i);for(;null!==o;){let e=r;for(let t=0;t{mc()}));const uc=[];let dc=!1,_c=null;function pc(e,t){dc||(_c=uo.OnEventObservable.add((e=>{for(const[,t]of uc)t(e)}),En.Created),dc=!0);const i=uc.filter((([t,i])=>t===e));i.length>0?i[0][1]=t:uc.push([e,t])}function fc(e){for(let t=0;t{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){yt.Clone((()=>e),this)}serialize(){return yt.Serialize(this)}parse(e,t,i){yt.Parse((()=>this),e,t,i)}}qe([st()],gc.prototype,"name",void 0),qe([st()],gc.prototype,"priority",void 0),qe([st()],gc.prototype,"resolveIncludes",void 0),qe([st()],gc.prototype,"registerForExtraEvents",void 0);class vc extends Oa{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class xc extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new vc,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=uo.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&lc.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&lc.DetailTextureEnabled&&this._isEnabled?(Un(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||this._texture&&lc.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Gn(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&lc.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}qe([rt("detailTexture"),it("_markAllSubMeshesAsTexturesDirty")],xc.prototype,"texture",void 0),qe([st()],xc.prototype,"diffuseBlendLevel",void 0),qe([st()],xc.prototype,"roughnessBlendLevel",void 0),qe([st()],xc.prototype,"bumpLevel",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],xc.prototype,"normalBlendMethod",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],xc.prototype,"isEnabled",void 0);const bc={effect:null,subMesh:null};class Tc extends Oa{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class yc extends Ra{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Ce(0,0,0),this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(1,1,1),this.emissiveColor=new Ce(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new ds(16),this._worldViewProjectionMatrix=fe.Zero(),this._globalAmbientColor=new Ce(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new xc(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new ac,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),yc.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),yc.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(yc.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(yc.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===uo.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==uo.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(En.GetDefineNames,this._eventInfo),t.materialDefines=new Tc(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();n._needNormals=Zn(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),no(r,n);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(ao(r,n,this.canRenderToMRT&&!a),oo(r,n,a),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let e=1;e<=6;++e)n["MAINUV"+e]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&yc.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Un(this._diffuseTexture,n,"DIFFUSE")}else n.DIFFUSE=!1;if(this._ambientTexture&&yc.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;Un(this._ambientTexture,n,"AMBIENT")}else n.AMBIENT=!1;if(this._opacityTexture&&yc.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;Un(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else n.OPACITY=!1;if(this._reflectionTexture&&yc.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Vo.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Vo.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Vo.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Vo.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Vo.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Vo.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Vo.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Vo.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Vo.CUBIC_MODE:case Vo.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC")}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&yc.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;Un(this._emissiveTexture,n,"EMISSIVE")}else n.EMISSIVE=!1;if(this._lightmapTexture&&yc.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;Un(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else n.LIGHTMAP=!1;if(this._specularTexture&&yc.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;Un(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&yc.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;Un(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&yc.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,n.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(yc.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),qn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),eo(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ro(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(n.isDirty){const i=n._areLightsDisposed;n.markAsProcessed();const s=new ja;n.REFLECTION&&s.addFallback(0,"REFLECTION"),n.SPECULAR&&s.addFallback(0,"SPECULAR"),n.BUMP&&s.addFallback(0,"BUMP"),n.PARALLAX&&s.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&s.addFallback(1,"FOG"),n.POINTSIZE&&s.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),Kn(n,s,this._maxSimultaneousLights),n.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&s.addFallback(4,"FRESNEL"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const a=[ys.PositionKind];n.NORMAL&&a.push(ys.NormalKind),n.TANGENT&&a.push(ys.TangentKind);for(let e=1;e<=6;++e)n["UV"+e]&&a.push(`uv${1===e?"":e}`);n.VERTEXCOLOR&&a.push(ys.ColorKind),Qn(a,e,n,s),jn(a,n),Bn(a,e,n),zn(a,0,n);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=c,this._eventInfo.attributes=a,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(En.PrepareEffect,this._eventInfo),ac.AddUniforms(c),ac.AddSamplers(u),xs&&(xs.PrepareUniforms(c,n),xs.PrepareSamplers(u,n)),co({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),An(c);const p={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,n,a,p));const f=n.toString(),m=t.effect;let g=r.getEngine().createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:_,processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},o);if(this._eventInfo.customCode=void 0,g)if(this._onEffectCreatedObservable&&(bc.effect=g,bc.subMesh=t,this._onEffectCreatedObservable.notifyObservers(bc)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,n.markAsUnprocessed(),l=this.isFrozen,i)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!l,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,n,i,t.visibility);Wn(t,n);const a=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!a.useUbo||!this.isFrozen||!a.isSync||i._drawWrapper._forceRebindOnNextCall){if(yc.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(a.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),a.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&a.updateColor4("opacityParts",new Ce(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(a.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),a.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(a.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),a.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(a.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),a.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&yc.DiffuseTextureEnabled&&(a.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Gn(this._diffuseTexture,a,"diffuse")),this._ambientTexture&&yc.AmbientTextureEnabled&&(a.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Gn(this._ambientTexture,a,"ambient")),this._opacityTexture&&yc.OpacityTextureEnabled&&(a.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Gn(this._opacityTexture,a,"opacity")),this._hasAlphaChannel()&&a.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&yc.ReflectionTextureEnabled&&(a.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),a.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;a.updateVector3("vReflectionPosition",e.boundingBoxPosition),a.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&yc.EmissiveTextureEnabled&&(a.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Gn(this._emissiveTexture,a,"emissive")),this._lightmapTexture&&yc.LightmapTextureEnabled&&(a.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Gn(this._lightmapTexture,a,"lightmap")),this._specularTexture&&yc.SpecularTextureEnabled&&(a.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Gn(this._specularTexture,a,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&yc.BumpTextureEnabled&&(a.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Gn(this._bumpTexture,a,"bump"),s._mirroredCameraPosition?a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&yc.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(a.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),a.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;a.updateVector3("vRefractionPosition",e.boundingBoxPosition),a.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&a.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&a.updateColor4("vSpecularColor",this.specularColor,this.specularPower),a.updateColor3("vEmissiveColor",yc.EmissiveTextureEnabled?this.emissiveColor:Ce.BlackReadOnly),a.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),a.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&yc.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&yc.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&yc.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&yc.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&yc.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&yc.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&yc.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&yc.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&yc.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),In(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&Yn(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Nn(s,t,n),r.NUM_MORPH_INFLUENCERS&&kn(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this.useLogarithmicDepth&&wn(r,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),a.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=yt.Clone((()=>new yc(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=yt.Parse((()=>new yc(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),uo._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return lc.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){lc.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return lc.DetailTextureEnabled}static set DetailTextureEnabled(e){lc.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return lc.AmbientTextureEnabled}static set AmbientTextureEnabled(e){lc.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return lc.OpacityTextureEnabled}static set OpacityTextureEnabled(e){lc.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return lc.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){lc.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return lc.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){lc.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return lc.SpecularTextureEnabled}static set SpecularTextureEnabled(e){lc.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return lc.BumpTextureEnabled}static set BumpTextureEnabled(e){lc.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return lc.LightmapTextureEnabled}static set LightmapTextureEnabled(e){lc.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return lc.RefractionTextureEnabled}static set RefractionTextureEnabled(e){lc.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return lc.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){lc.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return lc.FresnelEnabled}static set FresnelEnabled(e){lc.FresnelEnabled=e}}qe([rt("diffuseTexture")],yc.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesAndMiscDirty")],yc.prototype,"diffuseTexture",void 0),qe([rt("ambientTexture")],yc.prototype,"_ambientTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"ambientTexture",void 0),qe([rt("opacityTexture")],yc.prototype,"_opacityTexture",void 0),qe([it("_markAllSubMeshesAsTexturesAndMiscDirty")],yc.prototype,"opacityTexture",void 0),qe([rt("reflectionTexture")],yc.prototype,"_reflectionTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"reflectionTexture",void 0),qe([rt("emissiveTexture")],yc.prototype,"_emissiveTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"emissiveTexture",void 0),qe([rt("specularTexture")],yc.prototype,"_specularTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"specularTexture",void 0),qe([rt("bumpTexture")],yc.prototype,"_bumpTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"bumpTexture",void 0),qe([rt("lightmapTexture")],yc.prototype,"_lightmapTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"lightmapTexture",void 0),qe([rt("refractionTexture")],yc.prototype,"_refractionTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"refractionTexture",void 0),qe([nt("ambient")],yc.prototype,"ambientColor",void 0),qe([nt("diffuse")],yc.prototype,"diffuseColor",void 0),qe([nt("specular")],yc.prototype,"specularColor",void 0),qe([nt("emissive")],yc.prototype,"emissiveColor",void 0),qe([st()],yc.prototype,"specularPower",void 0),qe([st("useAlphaFromDiffuseTexture")],yc.prototype,"_useAlphaFromDiffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesAndMiscDirty")],yc.prototype,"useAlphaFromDiffuseTexture",void 0),qe([st("useEmissiveAsIllumination")],yc.prototype,"_useEmissiveAsIllumination",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useEmissiveAsIllumination",void 0),qe([st("linkEmissiveWithDiffuse")],yc.prototype,"_linkEmissiveWithDiffuse",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"linkEmissiveWithDiffuse",void 0),qe([st("useSpecularOverAlpha")],yc.prototype,"_useSpecularOverAlpha",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useSpecularOverAlpha",void 0),qe([st("useReflectionOverAlpha")],yc.prototype,"_useReflectionOverAlpha",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useReflectionOverAlpha",void 0),qe([st("disableLighting")],yc.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],yc.prototype,"disableLighting",void 0),qe([st("useObjectSpaceNormalMap")],yc.prototype,"_useObjectSpaceNormalMap",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useObjectSpaceNormalMap",void 0),qe([st("useParallax")],yc.prototype,"_useParallax",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useParallax",void 0),qe([st("useParallaxOcclusion")],yc.prototype,"_useParallaxOcclusion",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useParallaxOcclusion",void 0),qe([st()],yc.prototype,"parallaxScaleBias",void 0),qe([st("roughness")],yc.prototype,"_roughness",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"roughness",void 0),qe([st()],yc.prototype,"indexOfRefraction",void 0),qe([st()],yc.prototype,"invertRefractionY",void 0),qe([st()],yc.prototype,"alphaCutOff",void 0),qe([st("useLightmapAsShadowmap")],yc.prototype,"_useLightmapAsShadowmap",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useLightmapAsShadowmap",void 0),qe([ot("diffuseFresnelParameters")],yc.prototype,"_diffuseFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"diffuseFresnelParameters",void 0),qe([ot("opacityFresnelParameters")],yc.prototype,"_opacityFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelAndMiscDirty")],yc.prototype,"opacityFresnelParameters",void 0),qe([ot("reflectionFresnelParameters")],yc.prototype,"_reflectionFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"reflectionFresnelParameters",void 0),qe([ot("refractionFresnelParameters")],yc.prototype,"_refractionFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"refractionFresnelParameters",void 0),qe([ot("emissiveFresnelParameters")],yc.prototype,"_emissiveFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"emissiveFresnelParameters",void 0),qe([st("useReflectionFresnelFromSpecular")],yc.prototype,"_useReflectionFresnelFromSpecular",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"useReflectionFresnelFromSpecular",void 0),qe([st("useGlossinessFromSpecularMapAlpha")],yc.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useGlossinessFromSpecularMapAlpha",void 0),qe([st("maxSimultaneousLights")],yc.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],yc.prototype,"maxSimultaneousLights",void 0),qe([st("invertNormalMapX")],yc.prototype,"_invertNormalMapX",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"invertNormalMapX",void 0),qe([st("invertNormalMapY")],yc.prototype,"_invertNormalMapY",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"invertNormalMapY",void 0),qe([st("twoSidedLighting")],yc.prototype,"_twoSidedLighting",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"twoSidedLighting",void 0),qe([st("applyDecalMapAfterDetailMap")],yc.prototype,"_applyDecalMapAfterDetailMap",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],yc.prototype,"applyDecalMapAfterDetailMap",void 0),ee("BABYLON.StandardMaterial",yc),dr.DefaultMaterialFactory=e=>new yc("default material",e),ki.prototype.createDynamicTexture=function(e,t,i,s){const r=new Pi(this,Ai.Dynamic);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?ki.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?ki.GetExponentOfTwo(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=s,this.updateTextureSamplingMode(s,r),this._internalTexturesCache.push(r),r},ki.prototype.updateDynamicTexture=function(e,t,i,s=!1,r,n=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(r||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(e.format=r),e._dynamicTextureSource=t,e._premulAlpha=s,e.invertY=i||!1,e.isReady=!0};class Sc extends Vo{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=Vo.CLAMP_ADDRESSMODE,this.wrapV=Vo.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const a=this._getEngine();if(!a)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=a.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=a.createCanvas(1,1),this._ownCanvas=!0,t.width||0===t.width?this._texture=a.createDynamicTexture(t.width,t.height,s,r):this._texture=a.createDynamicTexture(t,t,s,r));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,r,n,o,a=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=s,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(s.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),a&&this.update(o)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Sc(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&we.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Sc._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class Cc{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this._createRenderTargetTextureProvider=r,this._rttWrapper=null}}class Ec{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Pi(this._engine,Ai.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Ni(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=n?new Jh(this._scene,o):new pl("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&s||(l._framebuffer=i),s)if(n)l._colorTextureArray=s;else{const e=this._createInternalTexture(o,s);l.setTexture(e,0),a._texture=e}return r&&(n?l._depthStencilTextureArray=r:l._depthStencilTexture=this._createInternalTexture(o,r)),a.disableRescaling(),this._renderTargetTextures.push(a),a}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class Ac extends Cc{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Pc(e.scene,this))),this.layer=e}}class Pc extends Ec{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&s===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class Rc{static GetDefaults(e){const t=new Rc;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class Ic{constructor(e,t=Rc.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new X,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()}))}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new Ac(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{}),(()=>{hs.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t())):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class Mc extends Cc{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Oc(e,this))),this.layer=e}}class Oc extends Ec{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class Dc{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class wc{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new X,this.onXRReferenceSpaceChanged=new X,this.onXRSessionEnded=new X,this.onXRSessionInit=new X,this.onXRReferenceSpaceInitialized=new X,this.onXRReady=new X,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new X(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{we.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){return this._baseLayerRTTProvider?.trySetViewportForView(e,t)||!1}getRenderTargetTextureForEye(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(e)||null}getRenderTargetTextureForView(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForView(e)||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new Dc(this):((e=e||Rc.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new Ic(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(t),this.session.addEventListener("end",(()=>{this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return wc.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{if(this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t)){this.inXRFrameLoop=!0;const e=this._baseLayerRTTProvider?.getFramebufferDimensions()||null;this._engine.framebufferDimensionsObject!==e&&(this._engine.framebufferDimensionsObject=e),this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=this._baseLayerRTTProvider?.getFramebufferDimensions()||null,this.onXRFrameObservable.addOnce((()=>{this.onXRReady.notifyObservers(this)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(we.Error("XR.requestReferenceSpace failed for the following reason: "),we.Error(e),we.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw we.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.onXRReferenceSpaceInitialized.notifyObservers(e),this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerWrapper=e,this._baseLayerRTTProvider=this._baseLayerWrapper?.createRenderTargetTextureProvider(this)||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Mc(e.baseLayer):new Ac(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(we.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){return this.session?.frameRate}get supportedFrameRates(){return this.session?.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){return this._baseLayerWrapper?.isFixedFoveationSupported||!1}get fixedFoveation(){return this._baseLayerWrapper?.fixedFoveation||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){return this.session?.enabledFeatures??null}}var Nc,Fc;!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(Nc||(Nc={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(Fc||(Fc={})),bo._GroundMeshParser=(e,t)=>Bc.Parse(e,t);class Bc extends bo{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=ge.Matrix[5];i.invertToRef(s);const r=ge.Vector3[8];if(de.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return de.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new de(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=ge.Matrix[5];s.invertToRef(r);const n=ge.Vector3[8];if(de.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return de.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return n=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new de(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,_=e.buffer[c+2]/255;const p=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,_=1-_);const f=u*a.r+d*a.g+_*a.b;t.y=p>=l?e.minHeight+(e.maxHeight-e.minHeight)*f:e.minHeight-K,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),r.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*r+1]>=e.minHeight,u=i[3*a+1]>=e.minHeight;h&&c&&u&&(t.push(s),t.push(r),t.push(a)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(s),t.push(a))}cn.ComputeNormals(i,t,s);const c=new cn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Uc(e,t={},i){const s=new Bc(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,Lc(t).applyToMesh(s,t.updatable),s._setReady(!0),s}function Gc(e,t,i=null){const s=new bo(e,i);return kc(t).applyToMesh(s,t.updatable),s}function zc(e,t,i={},s=null){const r=i.width||10,n=i.height||10,o=i.subdivisions||1,a=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new Ce(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;s=s||se.LastCreatedScene;const _=new Bc(e,s);let p;_._subdivisionsX=o,_._subdivisionsY=o,_._width=r,_._height=n,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((o+1)*(o+1)));const f=(e,t,i)=>{Vc({width:r,height:n,subdivisions:o,minHeight:a,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:p}).applyToMesh(_,u),d&&d(_,p),_._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const r=s?.getEngine().resizeImageBitmap(e,t,i);f(r,t,i)};hs.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else f(t.data,t.width,t.height);return _}const Wc={CreateGround:Uc,CreateGroundFromHeightMap:zc,CreateTiledGround:Gc};function Hc(e){const t=[],i=[],s=[],r=[],n=e.diameter||1,o=e.thickness||.5,a=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,h=a+1;for(let e=0;e<=a;e++){const l=e/a,c=e*Math.PI*2/a-Math.PI/2,u=fe.Translation(n/2,0,0).multiply(fe.RotationY(c));for(let n=0;n<=a;n++){const c=1-n/a,d=n*Math.PI*2/a+Math.PI,_=Math.cos(d),p=Math.sin(d);let f=new de(_,p,0),m=f.scale(o/2);const g=new ue(l,c);m=de.TransformCoordinates(m,u),f=de.TransformNormal(f,u),i.push(m.x,m.y,m.z),s.push(f.x,f.y,f.z),r.push(g.x,dn.UseOpenGLOrientationForUV?1-g.y:g.y);const v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}cn._ComputeSides(l,i,t,s,r,e.frontUVs,e.backUVs);const c=new cn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Xc(e,t={},i){const s=new bo(e,i);return t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Hc(t).applyToMesh(s,t.updatable),s}cn.CreateGround=Lc,cn.CreateTiledGround=kc,cn.CreateGroundFromHeightMap=Vc,bo.CreateGround=(e,t,i,s,r,n)=>Uc(e,{width:t,height:i,subdivisions:s,updatable:n},r),bo.CreateTiledGround=(e,t,i,s,r,n,o,a,l)=>Gc(e,{xmin:t,zmin:i,xmax:s,zmax:r,subdivisions:n,precision:o,updatable:l},a),bo.CreateGroundFromHeightMap=(e,t,i,s,r,n,o,a,l,h,c)=>zc(e,t,{width:i,height:s,subdivisions:r,minHeight:n,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a);const Yc={CreateTorus:Xc};cn.CreateTorus=Hc,bo.CreateTorus=(e,t,i,s,r,n,o)=>Xc(e,{diameter:t,thickness:i,tessellation:s,sideOrientation:o,updatable:n},r);class Qc{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=Qc._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=Xc("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new yc("targetMat",e);t.specularColor=Ce.Black(),t.emissiveColor=new Ce(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new Zo(de.Zero(),new de(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}Qc._IdCounter=0;class jc extends Qc{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Zo(de.Zero(),de.Forward())}}class Kc{}class $c{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new X,this.onAfterEnteringVRObservable=new X,this.onExitingVRObservable=new X,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=$c.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new de(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new de(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Ce(.2,.2,1),this._pickedGazeColor=new Ce(0,0,1),this.onNewMeshSelected=new X,this.onNewMeshPicked=new X,this.onBeforeCameraTeleport=new X,this.onAfterCameraTeleport=new X,this.onSelectedMeshUnselected=new X,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==$l.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===$l.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===Wl.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===Wl.A&&this._cameraGazer._selectionPointerUp()}))))},this._workingVector=de.Zero(),this._workingQuaternion=pe.Identity(),this._workingMatrix=fe.Identity(),we.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new de(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new yh("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof vh&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(pe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?wc.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(we.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new jc((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case Nc.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Nc.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Nc.IN_XR:this._hasEnteredVR=!0;break;case Nc.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new nc("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new jc((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode||this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),Ms.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((()=>{this.dispose()})),this._updateButtonVisibility(),this._circleEase=new Cr,this._circleEase.setEasingMode(Sr.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===Ms.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===Ms.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Nc.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){we.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=pe.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){we.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr)return void(this.xr.baseExperience.state===Nc.IN_XR&&this.xr.pointerSelection.attach());this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);const t=new xs;t.vignetteColor=new Ee(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const e=pe.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,pe.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),de.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const s=new Zo(i,this._workingVector),r=this._scene.pickWithRay(s,this._raySelectionPredicate);r&&r.pickedPoint&&r.pickedMesh&&this._isTeleportationFloor(r.pickedMesh)&&r.distance<5&&this.teleportCamera(r.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=Uc("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new Sc("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new yc("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const s=Xc("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);s.isPickable=!1,s.parent=this._teleportationTarget;const r=new Nt("animationInnerCircle","position.y",30,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new Nr;o.setEasingMode(Sr.EASINGMODE_EASEINOUT),r.setEasingFunction(o),s.animations=[],s.animations.push(r),this._scene.beginAnimation(s,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof xh))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=pe.FromRotationMatrix(fe.RotationY(Math.PI/4*this._rotationAngle)),i=new Nt("animationRotation","rotationQuaternion",90,Nt.ANIMATIONTYPE_QUATERNION,Nt.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new Nt("animationPP","vignetteWeight",90,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new Nt("animationPP2","vignetteStretch",90,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:10}),a.push({frame:6,value:0}),o.setKeys(a),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof xh))return;let t,i;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==$c.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=de.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const s=new Nt("animationCameraTeleportation","position",90,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT),r=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];s.setKeys(r),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];const n=Math.round(i/2),o=new Nt("animationPP","vignetteWeight",90,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:n,value:8}),a.push({frame:i,value:0}),o.setKeys(a),this._postProcessMove.animations.push(o);const l=new Nt("animationPP2","vignetteStretch",90,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}$c.TELEPORTATIONMODE_CONSTANTTIME=0,$c.TELEPORTATIONMODE_CONSTANTSPEED=1;const qc=function(){const e={root:0,found:!1};return function(t,i,s,r){e.root=0,e.found=!1;const n=i*i-4*t*s;if(n<0)return e;const o=Math.sqrt(n);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,s){const r=de.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!((e,t,i,s)=>!(e.x>i.x+s||i.x-s>t.x||e.y>i.y+s||i.y-s>t.y||e.z>i.z+s||i.z-s>t.z))(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let a,l=!1;t||(t=[]),t[e]||(t[e]=new ir(0,0,0,0),t[e].copyFromPoints(i,s,r));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const c=h.signedDistanceTo(this._basePoint),u=de.Dot(h.normal,this._velocity);if(Zc.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,a=0}else{a=(-1-c)/u;let e=(1-c)/u;if(a>e){const t=e;e=a,a=t}if(a>1||e<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,_=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,h.normal)&&(d=!0,_=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*de.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=qc(e,t,n,_);o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),t=2*de.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=qc(e,t,n,_),o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),t=2*de.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=qc(e,t,n,_),o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let a=this._edge.lengthSquared(),l=de.Dot(this._edge,this._velocity),h=de.Dot(this._edge,this._baseToVertex);if(e=a*-this._velocitySquaredLength+l*l,t=2*(a*de.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=qc(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=de.Dot(this._edge,this._velocity),h=de.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*de.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=qc(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=de.Dot(this._edge,this._velocity),h=de.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*de.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=qc(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}}if(d){const e=_*_*this._velocitySquaredLength;(!this.collisionFound||e=s)return void r.copyFrom(e);const a=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew Jc;class eu{constructor(e,t,i,s=""){let r;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new X,this.onErrorObservable=new X,this.onBindObservable=new X,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=ui.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=eu._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=bi.GetShadersStore(this._shaderLanguage),this._shaderRepository=bi.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=bi.GetIncludesShadersStore(this._shaderLanguage);const n=Lt()?this._engine.getHostDocument():null;r="string"==typeof e?e:e.computeSource?"source:"+e.computeSource:e.computeElement?n?.getElementById(e.computeElement)||e.computeElement:e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(r,"Compute","",(i=>{xi.Initialize(o),xi.PreProcess(i,o,(s=>{this._rawComputeSourceCode=i,t.processFinalCode&&(s=t.processFinalCode(s));const r=xi.Finalize(s,"",o);this._useFinalCode(r.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Ut(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));if(this._shaderStore[e+t+"Shader"])return void s(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void s(this._shaderStore[e+i+"Shader"]);let r;r="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){return this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._pipelineContext?._getComputeShaderCode()??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,(e=>{e&&e.numErrors>0?this._processCompilationErrors(e,t):(this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t))})),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_processCompilationErrors(e,t=null){if(this._compilationError="",we.Error("Unable to compile compute effect:"),this.defines&&we.Error("Defines:\n"+this.defines),eu.LogShaderCodeOnCompilationError){const e=this._pipelineContext?._getComputeShaderCode();e&&(we.Error("Compute code:"),we.Error(e))}if("string"==typeof e)this._compilationError=e,we.Error("Error: "+this._compilationError);else for(const t of e.messages){let e="";void 0!==t.line&&(e+="Line "+t.line+", "),void 0!==t.offset&&(e+="Offset "+t.offset+", "),void 0!==t.length&&(e+="Length "+t.length+", "),e+=t.type+": "+t.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=e,we.Error(e)}t&&(this._pipelineContext=t,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){bi.GetShadersStore(ui.WGSL)[`${e}ComputeShader`]=t}}var tu;eu._UniqueIdSeed=0,eu.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(tu||(tu={})),ki.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},ki.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},ki.prototype.createComputeContext=function(){},ki.prototype.computeDispatch=function(e,t,i,s,r,n,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},ki.prototype.areAllComputeEffectsReady=function(){return!0},ki.prototype.releaseComputeEffects=function(){},ki.prototype._prepareComputePipelineContext=function(e,t,i,s,r){},ki.prototype._rebuildComputeEffects=function(){},ki.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},ki.prototype._releaseComputeEffect=function(e){},ki.prototype._deleteComputePipelineContext=function(e){};class iu{constructor(){this._gpuTimeInFrameId=-1,this.counter=new tr}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()}))}serialize(){const e=yt.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],s=i.object;switch(i.type){case tu.Texture:case tu.TextureWithoutSampler:case tu.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case tu.UniformBuffer:}}return e}static Parse(e,t,i){const s=yt.Parse((()=>new su(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=Vo.Parse(e.textures[r],t,i);n.type===tu.Texture?s.setTexture(r,o):n.type===tu.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}static _BufferIsDataBuffer(e){return void 0!==e.underlyingResource}}qe([st()],su.prototype,"name",void 0),qe([st()],su.prototype,"fastMode",void 0),ee("BABYLON.ComputeShader",su);class ru{constructor(e,t,i,s,r,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},nu.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},dr.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(Rs.NAME_OCTREE);i||(i=new ou(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new nu(nu.CreationFuncForMeshes,e,t));const s=this.getWorldExtends();return this._selectionOctree.update(s.min,s.max,this.meshes),this._selectionOctree},Object.defineProperty(dr.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Sn.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let s=i._getComponent(Rs.NAME_OCTREE);s||(s=new ou(i),i._addComponent(s)),this._submeshesOctree||(this._submeshesOctree=new nu(nu.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class ou{constructor(e){this.name=Rs.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Zo(de.Zero(),new de(1,1,1)),(e=e||se.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){return this.scene._selectionOctree?.select(this.scene.frustumPlanes)||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(Zo.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function au(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,s=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,s=s||1e-5;const r=0|(e.tessellation||24),n=0|(e.subdivisions||1),o=!!e.hasRings,a=!!e.enclose,l=0===e.cap?0:e.cap||bo.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,_=2+(1+(1!==h&&a?2:0))*(o?n:1);let p;for(p=0;p<_;p++)d&&void 0===d[p]&&(d[p]=new Ee(1,1,1,1));for(p=0;p<_;p++)u&&void 0===u[p]&&(u[p]=new _e(0,0,1,1));const f=[],m=[],g=[],v=[],x=[],b=2*Math.PI*h/r;let T,y,S;const C=(s-i)/2/t,E=de.Zero(),A=de.Zero(),P=de.Zero(),R=de.Zero(),I=de.Zero(),M=_r.Y;let O,D,w,N=1,F=1,B=0,L=0;for(O=0;O<=n;O++)for(y=O/n,S=(y*(i-s)+s)/2,N=o&&0!==O&&O!==n?2:1,w=0;w{const n=e?i/2:s/2;if(0===n)return;let o,a,l;const c=e?u[_-1]:u[0];let p=null;d&&(p=e?d[_-1]:d[0]);const b=m.length/3,T=e?t/2:-t/2,y=new de(0,T,0);m.push(y.x,y.y,y.z),g.push(0,e?1:-1,0);const S=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),dn.UseOpenGLOrientationForUV?1-S:S),p&&x.push(p.r,p.g,p.b,p.a);const C=new ue(.5,.5);for(l=0;l<=r;l++){o=2*Math.PI*l*h/r;const t=Math.cos(-o),i=Math.sin(-o);a=new de(t*n,T,i*n);const s=new ue(t*C.x+.5,i*C.y+.5);m.push(a.x,a.y,a.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*s.y;v.push(c.x+(c.z-c.x)*s.x,dn.UseOpenGLOrientationForUV?1-u:u),p&&x.push(p.r,p.g,p.b,p.a)}for(l=0;l(void 0!==o&&o instanceof dr||(void 0!==o&&(l=a||bo.DEFAULTSIDE,a=o),o=n,n=1),lu(e,{height:t,diameterTop:i,diameterBottom:s,tessellation:r,subdivisions:n,sideOrientation:l,updatable:a},o)),Ct.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new cu(e,de.Zero(),t)));class cu extends yo{constructor(e,t,i){super(e,i),this.groundColor=new Ce(0,0,0),this.direction=t||de.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=de.Normalize(e.subtract(de.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=de.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=de.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=fe.Identity()),this._worldMatrix}getTypeID(){return yo.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}qe([nt()],cu.prototype,"groundColor",void 0),qe([lt()],cu.prototype,"direction",void 0);class uu{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new cu("shared gizmo light",new de(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Ce.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==uu._DefaultUtilityLayer?uu._CreateDefaultUtilityLayerFromScene(se.LastCreatedScene):uu._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return uu._DefaultUtilityLayer=new uu(e),uu._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{uu._DefaultUtilityLayer=null})),uu._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==uu._DefaultKeepDepthUtilityLayer&&(uu._DefaultKeepDepthUtilityLayer=new uu(se.LastCreatedScene),uu._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,uu._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{uu._DefaultKeepDepthUtilityLayer=null}))),uu._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new X,this.utilityLayerScene=new dr(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==Ms.POINTERMOVE&&t.type!==Ms.POINTERUP&&t.type!==Ms.POINTERDOWN&&t.type!==Ms.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const s=i=>{let s=null;if(t.nearInteractionPickingInfo)s=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new Ss;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)s=t.originalPickingInfo;else{let r=null;this._renderCamera&&(r=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),s=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),r&&(i._activeCamera=r)}return s},r=s(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=Ms.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ws(t.type,t.event,r),t.type),void(t.type===Ms.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ws(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{const i=s(e),n=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===Ms.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:t.type!==Ms.POINTERMOVE&&t.type!==Ms.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(r.distance0)):!this._pointerCaptures[n.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):(t.type!==Ms.POINTERMOVE&&t.type!==Ms.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,r,n))),t.type===Ms.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new ws(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}var du,_u,pu;uu._DefaultUtilityLayer=null,uu._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(du||(du={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(_u||(_u={}));class fu{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==_u.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=uu.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=du.Origin,this._updateScale=!0,this._coordinatesMode=_u.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=fe.RotationY(Math.PI),this._rootMesh=new bo("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=pe.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==du.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new de(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,fu.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,ge.Vector3[0]);let s=this.scaleRatio;if(t.mode==Kr.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(s*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?de.RightHandedForwardReadOnly:de.LeftHandedForwardReadOnly,i=t.getDirection(e);s*=de.Dot(ge.Vector3[0],i)}this._rootMesh.scaling.setAll(s),e._getWorldMatrixDeterminant()<0&&!fu.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),ge.Matrix[0]),ge.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(ge.Matrix[5]),void ge.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=ge.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,ge.Matrix[0]),t=ge.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,ge.Matrix[1]),i=ge.Matrix[1]):i=t,i.decompose(ge.Vector3[1],ge.Quaternion[0],ge.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=ge.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(ge.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(ge.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=ge.Matrix[0],i=ge.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const s=ge.Matrix[4];if(this._handlePivotMatrixInverse(e,i,s),s.decompose(ge.Vector3[0],ge.Quaternion[0],e.position,fu.PreserveScaling?e:void 0,fu.UseAbsoluteScaling),ge.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const t=ge.Quaternion[1];pe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);const i=ge.Matrix[2];fe.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);const s=ge.Matrix[2];t.toRotationMatrix(s);const r=e.getPivotMatrix(),n=ge.Matrix[3];r.invertToRef(n),r.multiplyToRef(i,ge.Matrix[4]),ge.Matrix[4].multiplyToRef(s,ge.Matrix[5]),ge.Matrix[5].multiplyToRef(n,ge.Matrix[6]),ge.Matrix[6].getTranslationToRef(ge.Vector3[1]),e.position.subtractInPlace(ge.Vector3[1])}}else{const t=ge.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(ge.Vector3[0],ge.Quaternion[0],e.position,fu.PreserveScaling?e:void 0,fu.UseAbsoluteScaling)}ge.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(ge.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(ge.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=ge.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=ge.Matrix[0],s=ge.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,s),e.getLocalMatrix().copyFrom(s)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===yo.LIGHTTYPEID_DIRECTIONALLIGHT||t===yo.LIGHTTYPEID_SPOTLIGHT||t===yo.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=ge.Matrix[0],s=ge.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,s),s.decompose(void 0,ge.Quaternion[0],ge.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,ge.Quaternion[0],ge.Vector3[0]);e.position=new de(ge.Vector3[0].x,ge.Vector3[0].y,ge.Vector3[0].z),e.direction&&(e.direction=new de(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{if(e.pickInfo){if(e.type===Ms.POINTERMOVE){if(i)return;t.forEach((t=>{if(t.colliderMeshes&&t.gizmoMeshes){const i=-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh),s=t.dragBehavior.enabled?i||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}}))}e.type===Ms.POINTERDOWN&&t.has(e.pickInfo.pickedMesh?.parent)&&(i=!0,t.get(e.pickInfo.pickedMesh?.parent).active=!0,t.forEach((t=>{const i=(-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh)||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=i,e.color&&(e.color=i.diffuseColor)}))}))),e.type===Ms.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}fu.PreserveScaling=!1,fu.UseAbsoluteScaling=!0;class mu extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,s=!1){const r=new xn("arrow",e),n=lu("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=lu("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return n.parent=r,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,o.parent=r,o.material=t,o.position.z+=.1375,o.rotation.x=Math.PI/2,s&&(o.visibility=0,n.visibility=0),r}static _CreateArrowInstance(e,t){const i=new xn("arrow",e);for(const e of t.getChildMeshes())e.createInstance(e.name).parent=i;return i}constructor(e,t=Ce.Gray(),i=uu.DefaultUtilityLayer,s=null,r=1,n=Ce.Yellow(),o=Ce.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new X,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new yc("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ce(.1,.1,.1)),this._hoverMaterial=new yc("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new yc("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const a=mu._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r),l=mu._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r+4,!0);this._gizmoMesh=new bo("",i.utilityLayerScene),this._gizmoMesh.addChild(a),this._gizmoMesh.addChild(l),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let h=0;const c={snapDistance:0};this.dragBehavior=new sa({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){let t=!1;if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(ge.Vector3[2]),ge.Vector3[2].addInPlace(e.delta),this.dragBehavior.validateDrag(ge.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.updateCache(),t=!0);else if(h+=e.dragDistance,Math.abs(h)>this.snapDistance){const i=Math.floor(Math.abs(h)/this.snapDistance);h%=this.snapDistance,e.delta.normalizeToRef(ge.Vector3[1]),ge.Vector3[1].scaleInPlace(this.snapDistance*i),this.attachedNode.getWorldMatrix().getTranslationToRef(ge.Vector3[2]),ge.Vector3[2].addInPlace(ge.Vector3[1]),this.dragBehavior.validateDrag(ge.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(ge.Vector3[1].x,ge.Vector3[1].y,ge.Vector3[1].z),this.attachedNode.updateCache(),c.snapDistance=this.snapDistance*i*Math.sign(h),this.onSnapObservable.notifyObservers(c),t=!0)}t&&this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const d={gizmoMeshes:a.getChildMeshes(),colliderMeshes:l.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(l,d),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==d.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(d.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(d.gizmoMeshes,e?d.material:d.disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}class gu{get scaleLines(){return this._scaleLines}set scaleLines(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)}get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,s,r,n,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||se.LastCreatedScene){if(!s){const t=new yc("xAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ce.Red().scale(.5),s=mu._CreateArrow(e,t,o)}if(!r){const t=new yc("yAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ce.Green().scale(.5),r=mu._CreateArrow(e,t,o)}if(!n){const t=new yc("zAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ce.Blue().scale(.5),n=mu._CreateArrow(e,t,o)}this._xAxis=s,this._yAxis=r,this._zAxis=n,this.scaleLines=t,null!=i&&(gu._SetRenderingGroupId(this._xAxis,i),gu._SetRenderingGroupId(this._yAxis,i),gu._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new de,de.Right(),de.Up(),de.Forward())}}update(e,t,i,s){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(s)}createInstance(){const e=mu._CreateArrowInstance(this.scene,this._xAxis),t=mu._CreateArrowInstance(this.scene,this._yAxis),i=mu._CreateArrowInstance(this.scene,this._zAxis),s=new gu(this.scene,this.scaleLines,null,e,t,i);return s._instanced=!0,s}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach((e=>{e.renderingGroupId=t}))}}class vu extends gu{constructor(e,t,i,s=1){super(e,s),this.pos=de.Zero(),this.xaxis=de.Zero(),this.yaxis=de.Zero(),this.zaxis=de.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef(_r.X,this.mesh,this.xaxis),e.getDirectionToRef(_r.Y,this.mesh,this.yaxis),e.getDirectionToRef(_r.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(dr.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new xu(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(pu||(pu={}));class xu{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new X),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new X),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||se.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()}))}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...xu.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:xu.InspectorURL;hs.LoadBabylonScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function bu(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[];let r=[];const n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const s=[17,18,19,16],r=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),s.unshift(s.pop()),u--;for(;d>0;)i.unshift(i.pop()),r.unshift(r.pop()),d--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(s[0],s[2],s[3],s[0],s[1],s[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const p=[n/2,o/2,a/2];r=_.reduce(((e,t,i)=>e.concat(t*p[i%3])),[]);const f=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new _e(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new Ee(1,1,1,1));for(let e=0;e<6;e++)if(s.push(m[e].z,dn.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,dn.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,dn.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),s.push(m[e].z,dn.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);cn._ComputeSides(f,r,t,i,s,e.frontUVs,e.backUVs);const x=new cn;if(x.indices=t,x.positions=r,x.normals=i,x.uvs=s,g){const e=f===cn.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function Tu(e){const t=e.width||e.size||1,i=e.height||e.size||1,s=e.depth||e.size||1,r=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),o=0|(e.depthSegments||e.segments||1),a=new fe,l=new fe,h=new fe,c=Lc({width:t,height:s,subdivisionsX:r,subdivisionsY:o});fe.TranslationToRef(0,-i/2,0,l),fe.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=Lc({width:t,height:s,subdivisionsX:r,subdivisionsY:o});fe.TranslationToRef(0,i/2,0,h),u.transform(h);const d=Lc({width:i,height:s,subdivisionsX:n,subdivisionsY:o});fe.TranslationToRef(-t/2,0,0,l),fe.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const _=Lc({width:i,height:s,subdivisionsX:n,subdivisionsY:o});fe.TranslationToRef(t/2,0,0,l),fe.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h);const p=Lc({width:t,height:i,subdivisionsX:r,subdivisionsY:n});fe.TranslationToRef(0,0,-s/2,l),fe.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const f=Lc({width:t,height:i,subdivisionsX:r,subdivisionsY:n});return fe.TranslationToRef(0,0,s/2,l),fe.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h),c.merge([u,_,d,p,f],!0),c}function yu(e,t={},i=null){const s=new bo(e,i);return t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,bu(t).applyToMesh(s,t.updatable),s}xu.InspectorURL=`${hs._DefaultCdnUrl}/v${gn.Version}/inspector/babylon.inspector.bundle.js`,xu.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};const Su={CreateBox:yu};function Cu(e){const t=0|(e.segments||32),i=e.diameterX||e.diameter||1,s=e.diameterY||e.diameter||1,r=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,o=e.slice&&e.slice<=0?1:e.slice||1,a=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new de(i/2,s/2,r/2),c=2+t,u=2*c,d=[],_=[],p=[],f=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*o;for(let e=0;e<=u;e++){const s=e/u,r=s*Math.PI*2*n,o=fe.RotationZ(-i),a=fe.RotationY(r),l=de.TransformCoordinates(de.Up(),o),c=de.TransformCoordinates(l,a),d=c.multiply(h),m=c.divide(h).normalize();_.push(d.x,d.y,d.z),p.push(m.x,m.y,m.z),f.push(s,dn.UseOpenGLOrientationForUV?1-t:t)}if(e>0){const t=_.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(eyu(e,{size:t,sideOrientation:r,updatable:s},i);const Au={CreateSphere:Eu};function Pu(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=0|Math.max(e.subdivisions?e.subdivisions:2,1),i=0|Math.max(e.tessellation?e.tessellation:16,3),s=Math.max(e.height?e.height:1,0),r=Math.max(e.radius?e.radius:.25,0),n=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),o=i,a=t,l=Math.max(e.radiusTop?e.radiusTop:r,0),h=Math.max(e.radiusBottom?e.radiusBottom:r,0),c=s-(l+h),u=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:n,1),_=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:n,1),p=Math.acos((h-l)/s);let f=[];const m=[],g=[],v=[];let x=0;const b=[],T=.5*c,y=.5*Math.PI;let S,C;const E=de.Zero(),A=de.Zero(),P=Math.cos(p),R=Math.sin(p),I=new ue(l*R,T+l*P).subtract(new ue(h*R,h*P-T)).length(),M=l*p+I+h*(y-p);let O=0;for(C=0;C<=d;C++){const e=[],t=y-p*(C/d);O+=l*p/d;const i=Math.cos(t),s=Math.sin(t),r=i*l;for(S=0;S<=o;S++){const t=S/o,n=t*u+0,a=Math.sin(n),h=Math.cos(n);A.x=r*a,A.y=T+s*l,A.z=r*h,m.push(A.x,A.y,A.z),E.set(i*a,s,i*h),g.push(E.x,E.y,E.z),v.push(t,dn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}const D=s-l-h+P*l-P*h,w=R*(h-l)/D;for(C=1;C<=a;C++){const e=[];O+=I/a;const t=R*(C*(h-l)/a+l);for(S=0;S<=o;S++){const i=S/o,s=i*u+0,r=Math.sin(s),n=Math.cos(s);A.x=t*r,A.y=T+P*l-C*D/a,A.z=t*n,m.push(A.x,A.y,A.z),E.set(r,w,n).normalize(),g.push(E.x,E.y,E.z),v.push(i,dn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}for(C=1;C<=_;C++){const e=[],t=y-p-(Math.PI-p)*(C/_);O+=h*p/_;const i=Math.cos(t),s=Math.sin(t),r=i*h;for(S=0;S<=o;S++){const t=S/o,n=t*u+0,a=Math.sin(n),l=Math.cos(n);A.x=r*a,A.y=s*h-T,A.z=r*l,m.push(A.x,A.y,A.z),E.set(i*a,s,i*l),g.push(E.x,E.y,E.z),v.push(t,dn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}for(S=0;SEu(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:r},s);const Iu={CreateCapsule:Ru};function Mu(e){let t=e.pathArray;const i=e.closeArray||!1,s=e.closePath||!1,r=e.invertUV||!1,n=Math.floor(t[0].length/2);let o=e.offset||n;o=o>n?n:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],_=[],p=[],f=[],m=[],g=[];let v;const x=[],b=[];let T,y,S;if(t.length<2){const e=[],i=[];for(y=0;y0&&(I=P[S].subtract(P[S-1]).length(),M=I+m[T],p[T].push(M),m[T]=M),S++;s&&(S--,c.push(P[0].x,P[0].y,P[0].z),I=P[S].subtract(P[0]).length(),M=I+m[T],p[T].push(M),m[T]=M),x[T]=R+E,b[T]=C,C+=R+E}let w,N,F=null,B=null;for(y=0;y{let r=s[0].length;const n=a;let o=0;const l=n._originalBuilderSideOrientation===bo.DOUBLESIDE?2:1;for(let a=1;a<=l;++a)for(let a=0;aRu(e,t,i),cn.CreateCapsule=Pu;const Du={CreateRibbon:Ou};function wu(e){const t=[],i=[],s=[],r=[],n=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE;t.push(0,0,0),r.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;eOu(e,{pathArray:t,closeArray:i,closePath:s,offset:r,updatable:o,sideOrientation:a,instance:l},n);const Fu={CreateDisc:Nu};function Bu(e){const t=e.pattern||bo.NO_FLIP,i=e.tileWidth||e.tileSize||1,s=e.tileHeight||e.tileSize||1,r=e.alignHorizontal||0,n=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/s);let u=h-c*s;const d=i*a/2,_=s*c/2;let p=0,f=0,m=0,g=0,v=0,x=0;if(l>0||u>0){switch(m=-d,g=-_,v=d,x=_,r){case bo.CENTER:l/=2,m-=l,v+=l;break;case bo.LEFT:v+=l,p=-l/2;break;case bo.RIGHT:m-=l,p=l/2}switch(n){case bo.CENTER:u/=2,g-=u,x+=u;break;case bo.BOTTOM:x+=u,f=-u/2;break;case bo.TOP:g-=u,f=u/2}}const b=[],T=[],y=[];y[0]=[0,0,1,0,1,1,0,1],y[1]=[0,0,1,0,1,1,0,1],t!==bo.ROTATE_TILE&&t!==bo.ROTATE_ROW||(y[1]=[1,1,0,1,0,0,1,0]),t!==bo.FLIP_TILE&&t!==bo.FLIP_ROW||(y[1]=[1,0,0,0,0,1,1,1]),t!==bo.FLIP_N_ROTATE_TILE&&t!==bo.FLIP_N_ROTATE_ROW||(y[1]=[0,1,1,1,1,0,0,0]);let S=[];const C=[],E=[];let A=0;for(let e=0;e0||u>0){const e=u>0&&(n===bo.CENTER||n===bo.TOP),o=u>0&&(n===bo.CENTER||n===bo.BOTTOM),h=l>0&&(r===bo.CENTER||r===bo.RIGHT),y=l>0&&(r===bo.CENTER||r===bo.LEFT);let P,R,I,M,O=[];if(e&&h&&(b.push(m+p,g+f,0),b.push(-d+p,g+f,0),b.push(-d+p,g+u+f,0),b.push(m+p,g+u+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,R=1-u/s,I=1,M=1,O=[P,R,I,R,I,M,P,M],t===bo.ROTATE_ROW&&(O=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),t===bo.FLIP_ROW&&(O=[1-P,R,1-I,R,1-I,M,1-P,M]),t===bo.FLIP_N_ROTATE_ROW&&(O=[P,1-R,I,1-R,I,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&y&&(b.push(d+p,g+f,0),b.push(v+p,g+f,0),b.push(v+p,g+u+f,0),b.push(d+p,g+u+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,R=1-u/s,I=l/i,M=1,O=[P,R,I,R,I,M,P,M],(t===bo.ROTATE_ROW||t===bo.ROTATE_TILE&&a%2==0)&&(O=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),(t===bo.FLIP_ROW||t===bo.FLIP_TILE&&a%2==0)&&(O=[1-P,R,1-I,R,1-I,M,1-P,M]),(t===bo.FLIP_N_ROTATE_ROW||t===bo.FLIP_N_ROTATE_TILE&&a%2==0)&&(O=[P,1-R,I,1-R,I,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(b.push(m+p,_+f,0),b.push(-d+p,_+f,0),b.push(-d+p,x+f,0),b.push(m+p,x+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,R=0,I=1,M=u/s,O=[P,R,I,R,I,M,P,M],(t===bo.ROTATE_ROW&&c%2==1||t===bo.ROTATE_TILE&&c%1==0)&&(O=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),(t===bo.FLIP_ROW&&c%2==1||t===bo.FLIP_TILE&&c%2==0)&&(O=[1-P,R,1-I,R,1-I,M,1-P,M]),(t===bo.FLIP_N_ROTATE_ROW&&c%2==1||t===bo.FLIP_N_ROTATE_TILE&&c%2==0)&&(O=[P,1-R,I,1-R,I,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&y&&(b.push(d+p,_+f,0),b.push(v+p,_+f,0),b.push(v+p,x+f,0),b.push(d+p,x+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,R=0,I=l/i,M=u/s,O=[P,R,I,R,I,M,P,M],(t===bo.ROTATE_ROW&&c%2==1||t===bo.ROTATE_TILE&&(c+a)%2==1)&&(O=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),(t===bo.FLIP_ROW&&c%2==1||t===bo.FLIP_TILE&&(c+a)%2==1)&&(O=[1-P,R,1-I,R,1-I,M,1-P,M]),(t===bo.FLIP_N_ROTATE_ROW&&c%2==1||t===bo.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(O=[P,1-R,I,1-R,I,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];P=0,R=1-u/s,I=1,M=1,e[0]=[P,R,I,R,I,M,P,M],e[1]=[P,R,I,R,I,M,P,M],t!==bo.ROTATE_TILE&&t!==bo.ROTATE_ROW||(e[1]=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),t!==bo.FLIP_TILE&&t!==bo.FLIP_ROW||(e[1]=[1-P,R,1-I,R,1-I,M,1-P,M]),t!==bo.FLIP_N_ROTATE_TILE&&t!==bo.FLIP_N_ROTATE_ROW||(e[1]=[P,1-R,I,1-R,I,1-M,P,1-M]);for(let s=0;sNu(e,{radius:t,tessellation:i,sideOrientation:n,updatable:r},s);const ku={CreateTiledPlane:Lu};function Vu(e){const t=e.faceUV||new Array(6),i=e.faceColors,s=e.pattern||bo.NO_FLIP,r=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,a=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new _e(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new Ee(1,1,1,1));const d=r/2,_=n/2,p=o/2,f=[];for(let e=0;e<2;e++)f[e]=Bu({pattern:s,tileWidth:a,tileHeight:l,width:r,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)f[e]=Bu({pattern:s,tileWidth:a,tileHeight:l,width:o,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});let m=c;c===bo.BOTTOM?m=bo.TOP:c===bo.TOP&&(m=bo.BOTTOM);for(let e=4;e<6;e++)f[e]=Bu({pattern:s,tileWidth:a,tileHeight:l,width:r,height:o,alignVertical:m,alignHorizontal:h,sideOrientation:u});let g=[],v=[],x=[],b=[];const T=[],y=[],S=[],C=[];let E=0,A=0;for(let e=0;e<6;e++){const s=f[e].positions.length;y[e]=[],S[e]=[];for(let t=0;te+A))),A+=y[e].length,i)for(let t=0;t<4;t++)T.push(i[e].r,i[e].g,i[e].b,i[e].a)}const P=new de(0,0,p),R=fe.RotationY(Math.PI);g=y[0].map((e=>de.TransformNormal(e,R).add(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),v=S[0].map((e=>de.TransformNormal(e,R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),g=g.concat(y[1].map((e=>e.subtract(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const I=new de(d,0,0),M=fe.RotationY(-Math.PI/2);g=g.concat(y[2].map((e=>de.TransformNormal(e,M).add(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[2].map((e=>de.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=fe.RotationY(Math.PI/2);g=g.concat(y[3].map((e=>de.TransformNormal(e,O).subtract(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[3].map((e=>de.TransformNormal(e,O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=new de(0,_,0),w=fe.RotationX(Math.PI/2);g=g.concat(y[4].map((e=>de.TransformNormal(e,w).add(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[4].map((e=>de.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=fe.RotationX(-Math.PI/2);g=g.concat(y[5].map((e=>de.TransformNormal(e,N).subtract(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[5].map((e=>de.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),cn._ComputeSides(u,g,b,v,x);const F=new cn;if(F.indices=b,F.positions=g,F.normals=v,F.uvs=x,i){const e=u===cn.DOUBLESIDE?T.concat(T):T;F.colors=e}return F}function Uu(e,t,i=null){const s=new bo(e,i);return t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Vu(t).applyToMesh(s,t.updatable),s}cn.CreateTiledPlane=Bu;const Gu={CreateTiledBox:Uu};function zu(e){const t=[],i=[],s=[],r=[],n=e.radius||2,o=e.tube||.5,a=e.radialSegments||32,l=e.tubularSegments||32,h=e.p||2,c=e.q||3,u=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,d=e=>{const t=Math.cos(e),i=Math.sin(e),s=c/h*e,r=Math.cos(s),o=n*(2+r)*.5*t,a=n*(2+r)*i*.5,l=n*Math.sin(s)*.5;return new de(o,a,l)};let _,p;for(_=0;_<=a;_++){const e=_%a/a*2*h*Math.PI,t=d(e),s=d(e+.01),n=s.subtract(t);let c=s.add(t);const u=de.Cross(n,c);for(c=de.Cross(u,n),u.normalize(),c.normalize(),p=0;pWu(e,{radius:t,tube:i,radialSegments:s,tubularSegments:r,p:n,q:o,sideOrientation:h,updatable:l},a);const Xu={effect:null,subMesh:null};class Yu extends Ra{constructor(e,t,i,s={},r=!0){super(e,t,r),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new fe,this._cachedWorldViewProjectionMatrix=new fe,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...s}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return s>=0&&this.options.defines.splice(s,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=s?i._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),o=[],a=[],l=new ja;let h=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(a.push(ys.MatricesIndicesExtraKind),a.push(ys.MatricesWeightsExtraKind));const t=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let _=0;const p=e?e.morphTargetManager:null;if(p){const e=p.supportsUVs&&-1!==o.indexOf("#define UV1"),t=p.supportsTangents&&-1!==o.indexOf("#define TANGENT"),i=p.supportsNormals&&-1!==o.indexOf("#define NORMAL");_=p.numMaxInfluencers||p.numInfluencers,e&&o.push("#define MORPHTARGETS_UV"),t&&o.push("#define MORPHTARGETS_TANGENT"),i&&o.push("#define MORPHTARGETS_NORMAL"),_>0&&o.push("#define MORPHTARGETS"),p.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+_);for(let s=0;s<_;s++)a.push(ys.PositionKind+s),i&&a.push(ys.NormalKind+s),t&&a.push(ys.TangentKind+s),e&&a.push(ys.UVKind+"_"+s);_>0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),zn(a,0,o)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(An(c),Pn(this,r,o)),r.fogEnabled&&e?.applyFog&&r.fogMode!==dr.FOGMODE_NONE&&(o.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),h=this.customShaderNameResolve(this.name,c,u,d,o,a));const f=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=f?.effect??null,g=f?.defines??null,v=o.join("\n");let x=m;return g!==v&&(x=n.createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:v,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(x,v,this._materialContext):f&&f.setEffect(x,v),this._onEffectCreatedObservable&&(Xu.effect=x,Xu.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(Xu))),f._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(m!==x&&r.resetCachedMaterial(),f._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(-1!==this._options.uniforms.indexOf("world")&&s.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(n&&a&&a.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&kn(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew Yu(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew Yu(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,Vo.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Ce.FromArray(e)));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,Ee.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Ee.FromArray(e)));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,ue.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,de.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,_e.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,pe.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,fe.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise(((r,n)=>{const o=new At;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=this.Parse(t,i||se.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((s,r)=>{const n=new At;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.shaderMaterial),a=this.Parse(o,t||se.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Yu.SnippetUrl="https://snippet.babylonjs.com",Yu.CreateFromSnippetAsync=Yu.ParseFromSnippetAsync,ee("BABYLON.ShaderMaterial",Yu);bi.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",bo._LinesMeshParser=(e,t)=>Qu.Parse(e,t);class Qu extends bo{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,s=null,r,n,o,a){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new Ce(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const l={attributes:[ys.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===o?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(ys.ColorKind)):(l.uniforms.push("color"),this._color4=new Ee),a?this.material=a:(this.material=new Yu("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=uo.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(uo.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(uo.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new Qu(e,this.getScene(),t,this,i)}createInstance(e){const t=new ju(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Qu(e.name,t);return i.color=Ce.FromArray(e.color),i.alpha=e.alpha,i}}class ju extends To{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Ku(e){const t=[],i=[],s=e.lines,r=e.colors,n=[];let o=0;for(let e=0;e0&&(t.push(o-1),t.push(o)),o++}}const a=new cn;return a.indices=t,a.positions=i,r&&(a.colors=n),a}function $u(e){const t=e.dashSize||3,i=e.gapSize||1,s=e.dashNb||200,r=e.points,n=[],o=[],a=de.Zero();let l=0,h=0,c=0,u=0,d=0,_=0,p=0;for(p=0;p{const t=de.Zero(),i=e.length/6;let n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0;for(u=0;uZu(e,{points:t,updatable:s,instance:r},i),bo.CreateDashedLines=(e,t,i,s,r,n=null,o,a)=>Ju(e,{points:t,dashSize:i,gapSize:s,dashNb:r,updatable:o,instance:a},n);class td extends ue{constructor(e,t){super(e.x,e.y),this.index=t}}class id{constructor(){this.elements=[]}add(e){const t=[];return e.forEach((e=>{const i=new td(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new ue(this.elements[0].x,this.elements[0].y),t=new ue(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class sd{static Rectangle(e,t,i,s){return[new ue(e,t),new ue(i,t),new ue(i,s),new ue(e,s)]}static Circle(e,t=0,i=0,s=32){const r=[];let n=0;const o=2*Math.PI/s;for(let a=0;a!isNaN(e)));let i;const s=[];for(i=0;i<(2147483646&t.length);i+=2)s.push(new ue(t[i],t[i+1]));return s}static StartingAt(e,t){return br.StartingAt(e,t)}}class rd{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){let r;this._points=new id,this._outlinepoints=new id,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||se.LastCreatedScene,r=t instanceof br?t.getPoints():t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),void 0===this.bjsEarcut&&we.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new id;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new bo(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(ys.PositionKind,r.positions,e),s.setVerticesData(ys.NormalKind,r.normals,e),s.setVerticesData(ys.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new cn,s=[],r=[],n=[],o=this._points.computeBounds();this._points.elements.forEach((e=>{s.push(0,1,0),r.push(e.x,0,e.y),n.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){const i=r.length/3;this._points.elements.forEach((t=>{s.push(0,-1,0),r.push(t.x,-e,t.y),n.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(r,s,n,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,a,l){let h=e.length/3,c=0;for(let u=0;ul?yl?S1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||bo.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return ud(e,r,s,null,null,n,o,a,l,h,!0,i,!!c,bo._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function ud(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x){const b=(e,t,i,s,r,n,o,a,l,h,c)=>{const u=i.getTangents(),d=i.getNormals(),_=i.getBinormals(),p=i.getDistances();if(c)for(let e=0;e0){let t=u[e-1];de.Dot(t,u[e])<0&&u[e].scaleInPlace(-1),t=d[e-1],de.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=_[e-1],de.Dot(t,_[e])<0&&_[e].scaleInPlace(-1)}let f=0;const m=h&&a?a:()=>null!==n?n:0,g=h&&o?o:()=>null!==r?r:1;let v=l===bo.NO_CAP||l===bo.CAP_END?0:2;const x=ge.Matrix[0];for(let i=0;i{const t=Array(),i=de.Zero();let s;for(s=0;s3?0:h,c,x);const S=Ou(e,{pathArray:y,closeArray:a,closePath:l,updatable:d,sideOrientation:_,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},u);return S._creationDataStorage.pathArray=y,S._creationDataStorage.path3D=T,S._creationDataStorage.cap=h,S}cn.CreatePolygon=nd,bo.CreatePolygon=(e,t,i,s,r,n,o=earcut)=>od(e,{shape:t,holes:s,updatable:r,sideOrientation:n},i,o),bo.ExtrudePolygon=(e,t,i,s,r,n,o,a=earcut)=>ad(e,{shape:t,holes:r,depth:i,updatable:n,sideOrientation:o},s,a);const dd={ExtrudeShape:hd,ExtrudeShapeCustom:cd};function _d(e,t,i=null){const s=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,r=void 0===t.closed||t.closed,n=t.shape,o=t.radius||1,a=t.tessellation||64,l=t.clip||0,h=t.updatable,c=bo._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||bo.NO_CAP,d=2*Math.PI,_=[],p=t.invertUV||!1;let f=0,m=0;const g=d/a*s;let v,x;for(f=0;f<=a-l;f++){for(x=[],u!=bo.CAP_START&&u!=bo.CAP_ALL||(x.push(new de(0,n[0].y,0)),x.push(new de(Math.cos(f*g)*n[0].x*o,n[0].y,Math.sin(f*g)*n[0].x*o))),m=0;mhd(e,{shape:t,path:i,scale:s,rotation:r,cap:0===n?0:n||bo.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),bo.ExtrudeShapeCustom=(e,t,i,s,r,n,o,a,l,h,c,u)=>cd(e,{shape:t,path:i,scaleFunction:s,rotationFunction:r,ribbonCloseArray:n,ribbonClosePath:o,cap:0===a?0:a||bo.NO_CAP,sideOrientation:c,instance:u,updatable:h},l);const pd={CreateLathe:_d};function fd(e,t,i=null){const s=t.path;let r=t.instance,n=1;void 0!==t.radius?n=t.radius:r&&(n=r._creationDataStorage.radius);const o=t.tessellation||64,a=t.radiusFunction||null;let l=t.cap||bo.NO_CAP;const h=t.invertUV||!1,c=t.updatable,u=bo._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const d=(e,t,i,s,r,n,o,a)=>{const l=t.getTangents(),h=t.getNormals(),c=t.getDistances(),u=2*Math.PI/r*a,d=n||(()=>s);let _,p,f,m;const g=ge.Matrix[0];let v=o===bo.NO_CAP||o===bo.CAP_END?0:2;for(let t=0;t{const s=Array();for(let r=0;r3?0:l,p=d(s,_,new Array,n,o,a,l,t.arc);const f=Ou(e,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return f._creationDataStorage.pathArray=p,f._creationDataStorage.path3D=_,f._creationDataStorage.tessellation=o,f._creationDataStorage.cap=l,f._creationDataStorage.arc=t.arc,f._creationDataStorage.radius=n,f}bo.CreateLathe=(e,t,i,s,r,n,o)=>_d(e,{shape:t,radius:i,tessellation:s,sideOrientation:o,updatable:n},r);const md={CreateTube:fd};function gd(e){const t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,s=e.size,r=e.sizeX||s||1,n=e.sizeY||s||1,o=e.sizeZ||s||1,a=e.custom||t[i],l=a.face.length,h=e.faceUV||new Array(l),c=e.faceColors,u=void 0===e.flat||e.flat,d=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,_=[],p=[],f=[],m=[],g=[];let v=0,x=0;const b=[];let T,y,S,C,E,A,P=0,R=0;if(u)for(R=0;Rfd(e,{path:t,radius:i,tessellation:s,radiusFunction:r,arc:1,cap:n,updatable:a,sideOrientation:l,instance:h},o);const xd={CreatePolyhedron:vd};cn.CreatePolyhedron=gd,bo.CreatePolyhedron=(e,t,i)=>vd(e,t,i);const bd=new de(1,0,0),Td=new de(-1,0,0),yd=new de(0,1,0),Sd=new de(0,-1,0),Cd=new de(0,0,1),Ed=new de(0,0,-1);class Ad{constructor(e=de.Zero(),t=de.Up(),i=ue.Zero(),s=0,r=0,n=null,o=null,a=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=a,this.matrixWeightsOverride=l}clone(){return new Ad(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}function Pd(e,t,i){const s=!!t.skeleton,r=i.localMode||s,n=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,o=t.getIndices(),a=s?t.getPositionData(!0,!0):t.getVerticesData(ys.PositionKind),l=s?t.getNormalsData(!0,!0):t.getVerticesData(ys.NormalKind),h=r?s?t.getVerticesData(ys.PositionKind):a:null,c=r?s?t.getVerticesData(ys.NormalKind):l:null,u=t.getVerticesData(ys.UVKind),d=s?t.getVerticesData(ys.MatricesIndicesKind):null,_=s?t.getVerticesData(ys.MatricesWeightsKind):null,p=s?t.getVerticesData(ys.MatricesIndicesExtraKind):null,f=s?t.getVerticesData(ys.MatricesWeightsExtraKind):null,m=i.position||de.Zero();let g=i.normal||de.Up();const v=i.size||de.One(),x=i.angle||0;if(!g){const e=new de(0,0,1),i=t.getScene().activeCamera,s=de.TransformCoordinates(e,i.getWorldMatrix());g=i.globalPosition.subtract(s)}const b=-Math.atan2(g.z,g.x)-Math.PI/2,T=Math.sqrt(g.x*g.x+g.z*g.z),y=Math.atan2(g.y,T),S=new cn;S.indices=[],S.positions=[],S.normals=[],S.uvs=[],S.matricesIndices=s?[]:null,S.matricesWeights=s?[]:null,S.matricesIndicesExtra=p?[]:null,S.matricesWeightsExtra=f?[]:null;let C=0;const E=(e,t)=>{const s=new Ad;if(!o||!a||!l)return s;const r=o[e];if(s.vertexIdx=3*r,s.vertexIdxForBones=4*r,s.position=new de(a[3*r],a[3*r+1],a[3*r+2]),de.TransformCoordinatesToRef(s.position,t,s.position),s.normal=new de(l[3*r],l[3*r+1],l[3*r+2]),de.TransformNormalToRef(s.normal,t,s.normal),i.captureUVS&&u){const e=u[2*r+1];s.uv=new ue(u[2*r],dn.UseOpenGLOrientationForUV?1-e:e)}return s},A=[0,0,0,0],P=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(de.Dot(v,t)),s=(e,t,i,s)=>{for(let r=0;r{const n=de.GetClipFactor(e.position,r.position,t,i);let o=A,a=A;if(d&&_){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=e.matrixIndicesOverride??d,l=e.matrixWeightsOverride??_,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,c=r.matrixIndicesOverride??d,u=r.matrixWeightsOverride??_;o=[0,0,0,0],a=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(l[t+e]>0){const r=s(c,i[t+e],h,4);o[p]=i[t+e],a[p]=xe.Lerp(l[t+e],r>=0?u[r]:0,n),p++}for(let e=0;e<4&&p<4;++e){const r=c[h+e];-1===s(i,r,t,4)&&(o[p]=r,a[p]=xe.Lerp(0,u[h+e],n),p++)}const f=a[0]+a[1]+a[2]+a[3];a[0]/=f,a[1]/=f,a[2]/=f,a[3]/=f}const l=e.localPositionOverride?e.localPositionOverride[0]:h?.[e.vertexIdx]??0,u=e.localPositionOverride?e.localPositionOverride[1]:h?.[e.vertexIdx+1]??0,p=e.localPositionOverride?e.localPositionOverride[2]:h?.[e.vertexIdx+2]??0,f=r.localPositionOverride?r.localPositionOverride[0]:h?.[r.vertexIdx]??0,m=r.localPositionOverride?r.localPositionOverride[1]:h?.[r.vertexIdx+1]??0,g=r.localPositionOverride?r.localPositionOverride[2]:h?.[r.vertexIdx+2]??0,v=e.localNormalOverride?e.localNormalOverride[0]:c?.[e.vertexIdx]??0,x=e.localNormalOverride?e.localNormalOverride[1]:c?.[e.vertexIdx+1]??0,b=e.localNormalOverride?e.localNormalOverride[2]:c?.[e.vertexIdx+2]??0,T=v+((r.localNormalOverride?r.localNormalOverride[0]:c?.[r.vertexIdx]??0)-v)*n,y=x+((r.localNormalOverride?r.localNormalOverride[1]:c?.[r.vertexIdx+1]??0)-x)*n,S=b+((r.localNormalOverride?r.localNormalOverride[2]:c?.[r.vertexIdx+2]??0)-b)*n,C=Math.sqrt(T*T+y*y+S*S);return new Ad(de.Lerp(e.position,r.position,n),de.Lerp(e.normal,r.normal,n).normalize(),ue.Lerp(e.uv,r.uv,n),-1,-1,h?[l+(f-l)*n,u+(m-u)*n,p+(g-p)*n]:null,c?[T/C,y/C,S/C]:null,o,a)};let n=null;e.length>3&&(n=[]);for(let s=0;s0,d=de.Dot(e[s+1].position,t)-i>0,_=de.Dot(e[s+2].position,t)-i>0;switch(o=(u?1:0)+(d?1:0)+(_?1:0),o){case 0:e.length>3?(n.push(e[s]),n.push(e[s+1]),n.push(e[s+2])):n=e;break;case 1:if(n=n??new Array,u&&(a=e[s+1],l=e[s+2],h=r(e[s],a),c=r(e[s],l)),d){a=e[s],l=e[s+2],h=r(e[s+1],a),c=r(e[s+1],l),n.push(h),n.push(l.clone()),n.push(a.clone()),n.push(l.clone()),n.push(h.clone()),n.push(c);break}_&&(a=e[s],l=e[s+1],h=r(e[s+2],a),c=r(e[s+2],l)),a&&l&&h&&c&&(n.push(a.clone()),n.push(l.clone()),n.push(h),n.push(c),n.push(h.clone()),n.push(l.clone()));break;case 2:n=n??new Array,u||(a=e[s].clone(),l=r(a,e[s+1]),h=r(a,e[s+2]),n.push(a),n.push(l),n.push(h)),d||(a=e[s+1].clone(),l=r(a,e[s+2]),h=r(a,e[s]),n.push(a),n.push(l),n.push(h)),_||(a=e[s+2].clone(),l=r(a,e[s]),h=r(a,e[s+1]),n.push(a),n.push(l),n.push(h))}}return n},R=t instanceof bo?t:null,I=R?._thinInstanceDataStorage.matrixData,M=R?.thinInstanceCount||1,O=ge.Matrix[0];O.copyFrom(fe.IdentityReadOnly);for(let e=0;ePd(e,t,{position:i,normal:s,size:r,angle:n});class Id{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(Math.floor(e),we.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(Math.floor(t),we.Warn("y is not an integer, floor(y) used"))}clone(){return new Id(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(Math.floor(e),we.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),we.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(Math.floor(e),we.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),we.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=de.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new Id(0,0)}}class Md{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Od("icosahedron","Regular",[[0,j,-1],[-j,1,0],[-1,0,-j],[1,0,-j],[j,1,0],[0,j,1],[-1,0,j],[-j,-1,0],[0,-j,-1],[j,-1,0],[1,0,j],[0,-j,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,s=this.n;let r,n,o,a,l,h=i,c=1,u=0;0!==s&&(h=xe.HCF(i,s)),c=i/h,u=s/h;const d=Id.Zero(),_=new Id(i,s),p=new Id(-s,i+s),f=Id.Zero(),m=Id.Zero(),g=Id.Zero();let v,x,b,T,y=[];const S=[],C=this.vertByDist,E=(i,s,r,n)=>{v=i+"|"+r,x=s+"|"+n,v in t||x in t?v in t&&!(x in t)?t[x]=t[v]:x in t&&!(v in t)&&(t[v]=t[x]):(t[v]=e,t[x]=e,e++),C[r][0]>2?S[t[v]]=[-C[r][0],C[r][1],t[v]]:S[t[v]]=[y[C[r][0]],C[r][1],t[v]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let x=0;x<20;x++){if(y=this.IDATA.face[x],o=y[2],a=y[1],l=y[0],b=d.x+"|"+d.y,v=x+"|"+b,v in t||(t[v]=o,S[o]=[y[C[b][0]],C[b][1]]),b=_.x+"|"+_.y,v=x+"|"+b,v in t||(t[v]=a,S[a]=[y[C[b][0]],C[b][1]]),b=p.x+"|"+p.y,v=x+"|"+b,v in t||(t[v]=l,S[l]=[y[C[b][0]],C[b][1]]),r=this.IDATA.edgematch[x][0],n=this.IDATA.edgematch[x][1],"B"===n)for(let e=1;e2?S[t[v]]=[-C[b][0],C[b][1],t[v]]:S[t[v]]=[y[C[b][0]],C[b][1],t[v]])}this.closestTo=S,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&e0){const s=xe.HCF(e,t),r=e/s,n=t/s;for(let o=1;oe.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let e=0;e{const r=i.clone();return"A"===s&&r.rotateNeg120(e,t),"B"===s&&r.rotate120(e,t),r.x<0?r.y:r.x+r.y},d=[],_=[],p=[],f=[],m={},g=[];let v=-1,x=-1;for(let e=0;ee[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let e=0;et.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);const s=[];for(let e=0;e<12;e++)s[e]=e;let r=12;for(let e=0;e<12;e++){t[e].sort(((e,t)=>e[1]-t[1]));for(let i=0;ie[3]-t[3]));for(let e=0;e0;)r=t[a],this.face[r].indexOf(o)>-1?(n=(this.face[r].indexOf(o)+1)%3,o=this.face[r][n],i.push(o),s.push(r),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new Od("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let e=0;e{s=0,r=0,n=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],s+=a[0],r+=a[1],n+=a[2];e.vertex[t]=[s/3,r/3,n/3]}));return e}static BuildGeodesicData(e){const t=new Dd("Geodesic-m-n","Geodesic",[[0,j,-1],[-j,1,0],[-1,0,-j],[1,0,-j],[j,1,0],[0,j,1],[-1,0,j],[-j,-1,0],[0,-j,-1],[j,-1,0],[1,0,j],[0,-j,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;is){const e=r;r=s,s=e,we.Warn("n > m therefore m and n swapped")}const n=new Md;return n.build(s,r),vd(e,{custom:Dd.BuildGeodesicData(n),size:t.size,sizeX:t.sizeX,sizeY:t.sizeY,sizeZ:t.sizeZ,faceUV:t.faceUV,faceColors:t.faceColors,flat:t.flat,updatable:t.updatable,sideOrientation:t.sideOrientation,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}bo._GoldbergMeshParser=(e,t)=>Nd.Parse(e,t);class Nd extends bo{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(we.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(we.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(we.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=n.x+o*Math.cos(a+e*Math.PI/3),u=n.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=s;eEe.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>de.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>de.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>de.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>de.FromArray(e)));const s=new Nd(e.name,t);return s.goldbergData=i,s}}function Fd(e,t){const i=e.size,s=e.sizeX||i||1,r=e.sizeY||i||1,n=e.sizeZ||i||1,o=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,a=[],l=[],h=[],c=[];let u=1/0,d=-1/0,_=1/0,p=-1/0;for(let e=0;ea){const e=l;l=a,a=e,we.Warn("n > m therefore m and n swapped")}const h=new Md;h.build(a,l);const c=Dd.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new Nd(e,i);t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),d._originalBuilderSideOrientation=t.sideOrientation,Fd(t,u).applyToMesh(d,t.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let e=0;e0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function kd(e,t,i,s,r,n){const o=n.glyphs[e]||n.glyphs["?"];if(!o)return null;const a=new Ld(r);if(o.o){const e=o.o.split(" ");for(let r=0,n=e.length;rK&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>K&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>K&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;i&&s&&r&&n&&o&&a&&t.getDescendants(!0).forEach((e=>{const t=e.getDescendants(!0)[0],l=e.getDescendants(!0)[1],{parentBody:h,parentBodyIndex:c}=t.metadata,{childBody:u,childBodyIndex:d}=l.metadata,_=this._getTransformFromBodyToRef(h,ge.Matrix[0],c),p=this._getTransformFromBodyToRef(u,ge.Matrix[1],d);_.decomposeToTransformNode(t),this._makeScalingUnitInPlace(t.scaling),p.decomposeToTransformNode(l),this._makeScalingUnitInPlace(l.scaling);const f=t.getDescendants(!0)[0];f.position.copyFrom(i);const m=l.getDescendants(!0)[0];m.position.copyFrom(s),pe.FromRotationMatrixToRef(fe.FromXYZAxesToRef(r,o,de.CrossToRef(r,o,ge.Vector3[0]),ge.Matrix[0]),f.rotationQuaternion),pe.FromRotationMatrixToRef(fe.FromXYZAxesToRef(n,a,de.CrossToRef(n,a,ge.Vector3[1]),ge.Matrix[1]),m.rotationQuaternion)}))}showImpostor(e,t){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}showInertia(e){if(!this._scene)return null;for(let t=0;tthis._updateInertiaMeshes(),this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),t}showConstraint(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugConstraints(),this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s-1&&this._debugMeshMeshes.splice(r,1),this._numMeshes--,this._numMeshes>0?(this._meshes[s]=this._meshes[this._numMeshes],this._impostors[s]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s0?(this._bodyMeshes[s]=this._bodyMeshes[this._numBodies],this._bodies[s]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}t&&0===this._numBodies&&this._scene.unregisterBeforeRender(this._renderFunction)}hideInertia(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s0?(this._constraints[s]=this._constraints[this._numConstraints],this._constraintMeshes[s]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&0===this._numConstraints&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new yc("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Ce.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new yc("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=yu("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=pe.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=Eu("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=pe.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=Ru("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=pe.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=lu("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=pe.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new bo(e.name,t,null,e);return i.setParent(e),i.position=de.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const s=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return we.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case ga.BoxImpostor:i=this._getDebugBoxMesh(s),e.getBoxSizeToRef(i.scaling);break;case ga.SphereImpostor:{i=this._getDebugSphereMesh(s);const t=e.getRadius();i.scaling.x=2*t,i.scaling.y=2*t,i.scaling.z=2*t;break}case ga.CapsuleImpostor:{i=this._getDebugCapsuleMesh(s);const t=e.object.getBoundingInfo();i.scaling.x=2*(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=2*(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}case ga.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,s));break;case ga.NoImpostor:t?t.getChildMeshes().filter((e=>e.physicsImpostor?1:0)).forEach((e=>{if(e.physicsImpostor&&"Mesh"===e.getClassName()){const t=e.getBoundingInfo(),r=t.boundingBox.minimum,n=t.boundingBox.maximum;switch(e.physicsImpostor.type){case ga.BoxImpostor:i=this._getDebugBoxMesh(s),i.position.copyFrom(r),i.position.addInPlace(n),i.position.scaleInPlace(.5);break;case ga.SphereImpostor:i=this._getDebugSphereMesh(s);break;case ga.CylinderImpostor:i=this._getDebugCylinderMesh(s);break;default:i=null}i&&(i.scaling.x=n.x-r.x,i.scaling.y=n.y-r.y,i.scaling.z=n.z-r.z,i.parent=e)}})):we.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case ga.CylinderImpostor:{i=this._getDebugCylinderMesh(s);const t=e.object.getBoundingInfo();i.scaling.x=(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new bo("custom",t),s=new cn,r=e.getGeometry();if(s.positions=r.positions,s.indices=r.indices,s.applyToMesh(i),e._pluginDataInstances){const t=new Float32Array(16*e._pluginDataInstances.length);i.thinInstanceSetBuffer("matrix",t,16,!1)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){const i=e.inertiaOrientation??pe.Identity(),s=e.inertia??de.Zero(),r=e.centerOfMass??de.Zero(),n=6*(s.x-s.y+s.z),o=Math.sqrt(Math.max(n,0)),a=12*s.x-n,l=Math.sqrt(Math.max(a,0)),h=12*s.z-n,c=Math.sqrt(Math.max(h,0)),u=ge.Vector3[0];u.set(c,o,l);const d=fe.ScalingToRef(u.x,u.y,u.z,ge.Matrix[0]),_=i.toRotationMatrix(ge.Matrix[1]),p=fe.TranslationToRef(r.x,r.y,r.z,ge.Matrix[2]);return d.multiplyToRef(_,t),t.multiplyToRef(p,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=Gd.CreateBox("custom",{size:1},t),s=fe.Identity();if(e._pluginDataInstances.length){const t=new Float32Array(16*e._pluginDataInstances.length);for(let i=0;i=0?fe.FromArrayToRef(s._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(s.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;if(!(i&&s&&r&&n&&o&&a))return null;const l=new bo("parentingDebugConstraint",t),h=e.getBodiesUsingConstraint();for(const e of h){const h=new xn("parentOfPair",t);h.parent=l;const{parentBody:c,parentBodyIndex:u,childBody:d,childBodyIndex:_}=e,p=this._getTransformFromBodyToRef(c,ge.Matrix[0],u),f=this._getTransformFromBodyToRef(d,ge.Matrix[1],_),m=new xn("parentCoordSystem",t);m.parent=h,m.metadata={parentBody:c,parentBodyIndex:u},p.decomposeToTransformNode(m);const g=new xn("childCoordSystem",t);g.parent=h,g.metadata={childBody:d,childBodyIndex:_},f.decomposeToTransformNode(g);const v=pe.FromRotationMatrix(fe.FromXYZAxesToRef(r,o,r.cross(o),ge.Matrix[0])),x=pe.FromRotationMatrix(fe.FromXYZAxesToRef(n,a,n.cross(a),ge.Matrix[0])),b=i,T=s,y=new xn("constraint_parent",t);y.position.copyFrom(b),y.rotationQuaternion=v,y.parent=m;const S=new xn("constraint_child",t);S.parent=g,S.position.copyFrom(T),S.rotationQuaternion=x;const C=new gu(t,this._constraintAxesSize);C.xAxis.parent=y,C.yAxis.parent=y,C.zAxis.parent=y;const E=new gu(t,this._constraintAxesSize);E.xAxis.parent=S,E.yAxis.parent=S,E.zAxis.parent=S}return l}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(let e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}class Wd{static CreateAndShow(e,t,i){const s=new Wd(e);return s.show(t,i),s}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const t=this.ray;this._renderFunction=()=>this._render(),this._scene=e,this._renderPoints=[t.origin,t.origin.add(t.direction.scale(t.length))],this._renderLine=Zu("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){const e=this.ray;if(!e)return;const t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),this._renderPoints[0].copyFrom(e.origin),Zu("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),this._renderLine?.refreshBoundingInfo()}attachToMesh(e,t,i,s){this._attachedToMesh=e;const r=this.ray;r&&(r.direction||(r.direction=de.Zero()),r.origin||(r.origin=de.Zero()),s&&(r.length=s),i||(i=de.Zero()),t||(t=new de(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add((()=>this._updateToMesh())),this._onAfterStepObserver=this._scene.onAfterStepObservable.add((()=>this._updateToMesh()))),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh.isDisposed()?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),de.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}class Hd{static CreateBoneWeightShader(e,t){const i=e.skeleton,s=e.colorBase??Ce.Black(),r=e.colorZero??Ce.Blue(),n=e.colorQuarter??Ce.Green(),o=e.colorHalf??Ce.Yellow(),a=e.colorFull??Ce.Red(),l=e.targetBoneIndex??0;Ti.ShadersStore["boneWeights:"+i.name+"VertexShader"]="precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",Ti.ShadersStore["boneWeights:"+i.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const h=new Yu("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",s),h.setColor3("colorZero",r),h.setColor3("colorQuarter",n),h.setColor3("colorHalf",o),h.setColor3("colorFull",a),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=uo.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,s=e.colorMap??[{color:new Ce(1,.38,.18),location:0},{color:new Ce(.59,.18,1),location:.2},{color:new Ce(.59,1,.18),location:.4},{color:new Ce(1,.87,.17),location:.6},{color:new Ce(1,.17,.42),location:.8},{color:new Ce(.17,.68,1),location:1}],r=i.bones.length+1,n=Hd._CreateBoneMapColorBuffer(r,s,t),o=new Yu("boneWeights:"+i.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*i.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=uo.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const s=new Sc("temp",{width:e,height:1},i,!1),r=s.getContext(),n=r.createLinearGradient(0,0,e,0);t.forEach((e=>{n.addColorStop(e.location,e.color.toHexString())})),r.fillStyle=n,r.fillRect(0,0,e,1),s.update();const o=[],a=r.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eHd.DISPLAY_SPHERE_AND_SPURS&&(e=Hd.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,s=!0,r=3,n={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=s,this.renderingGroupId=r,this.options=n,this.color=Ce.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=n.pauseAnimations??!0,n.returnToRest=n.returnToRest??!1,n.displayMode=n.displayMode??Hd.DISPLAY_LINES,n.displayOptions=n.displayOptions??{},n.displayOptions.midStep=n.displayOptions.midStep??.235,n.displayOptions.midStepFactor=n.displayOptions.midStepFactor??.155,n.displayOptions.sphereBaseSize=n.displayOptions.sphereBaseSize??.15,n.displayOptions.sphereScaleUnit=n.displayOptions.sphereScaleUnit??2,n.displayOptions.sphereFactor=n.displayOptions.sphereFactor??.865,n.displayOptions.spurFollowsChild=n.displayOptions.spurFollowsChild??!1,n.displayOptions.showLocalAxes=n.displayOptions.showLocalAxes??!1,n.displayOptions.localAxesSize=n.displayOptions.localAxesSize??.075,n.computeBonesUsingShaders=n.computeBonesUsingShaders??!0,n.useAllBones=n.useAllBones??!0,this._boneIndices=new Set,!n.useAllBones){const e=t?.getVerticesData(ys.MatricesIndicesKind),i=t?.getVerticesData(ys.MatricesWeightsKind);if(e&&i)for(let t=0;tHd.DISPLAY_SPHERE_AND_SPURS&&(o=Hd.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){this.displayMode===Hd.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case Hd.DISPLAY_LINES:this._displayLinesUpdate();break;case Hd.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case Hd.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,s=0,r=0,n=0){const o=ge.Matrix[0],a=t.getParent();if(o.copyFrom(t.getLocalMatrix()),0!==s||0!==r||0!==n){const e=ge.Matrix[1];fe.IdentityToRef(e),e.setTranslationFromFloats(s,r,n),e.multiplyToRef(o,o)}a&&o.multiplyToRef(a.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let s,r;t?(s=t.getWorldMatrix(),r=t.position):(s=new fe,r=e[0].position);let n=0;for(let t=0;t=0;s--){const t=e[s],o=t.getParent();if(!o||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let a=this._debugLines[i];a||(a=[de.Zero(),de.Zero()],this._debugLines[i]=a),t.getAbsolutePositionToRef(r,a[0]),o.getAbsolutePositionToRef(r,a[1]),a[0].subtractInPlace(n),a[1].subtractInPlace(n),i++}s||r.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(fe.Identity())}_createSpur(e,t,i,s,r,n){const o=i.subtract(e),a=o.length(),l=o.normalize().scale(a),h=r.midStep||.165,c=r.midStepFactor||.215,u=l.scale(h),d=cd("skeletonViewer",{shape:[new de(1,-1,0),new de(1,1,0),new de(-1,1,0),new de(-1,-1,0),new de(1,-1,0)],path:[de.Zero(),u,l],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return a*c}return 0},sideOrientation:bo.DEFAULTSIDE,updatable:!1},n),_=d.getTotalVertices(),p=[],f=[];for(let e=0;e<_;e++)p.push(1,0,0,0),s&&r.spurFollowsChild&&e>9?f.push(s.getIndex(),0,0,0):f.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(ys.MatricesWeightsKind,p,!1),d.setVerticesData(ys.MatricesIndicesKind,f,!1),d.convertToFlatShadedMesh(),d}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(ys.PositionKind),i=this.mesh.getIndices(),s=this.mesh.getVerticesData(ys.MatricesWeightsKind),r=this.mesh.getVerticesData(ys.MatricesIndicesKind);if(!(t&&i&&s&&r))return null;const n=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new de(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let a=0;for(let l=0;l1e-5){de.FromArrayToRef(t,3*h,ge.Vector3[0]),n.minimizeInPlace(ge.Vector3[0]),o.maximizeInPlace(ge.Vector3[0]),a++;break}}}return a>1?{center:de.Center(n,o),radius:de.Distance(n,o)/2}:null}_buildSpheresAndSpurs(e=!0){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=this.utilityLayer?.utilityLayerScene,i=this.skeleton.bones,s=[],r=[],n=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let o=Number.NEGATIVE_INFINITY;const a=this.options.displayOptions||{};for(let n=0;n0)l.children.forEach((i=>{const s=new fe;i.getLocalMatrix().multiplyToRef(h,s);const n=new de;s.decompose(void 0,void 0,n);const u=de.Distance(c,n);u>o&&(o=u),e||r.push(this._createSpur(c,l,n,i,a,t))}));else{const i=this._getBoundingSphereForBone(l.getIndex());if(i&&(i.radius>o&&(o=i.radius),!e)){let e;const s=l.getParent();s?(this._getAbsoluteBindPoseToRef(s,h),h.decompose(void 0,void 0,ge.Vector3[0]),e=c.subtract(ge.Vector3[0]).normalize().scale(i.radius).add(c)):e=i.center.subtract(c).normalize().scale(i.radius).add(c),r.push(this._createSpur(c,l,e,null,a,t))}}const u=Eu("skeletonViewer",{segments:6,diameter:a.sphereBaseSize||.2,updatable:!0},t),d=u.getTotalVertices(),_=[],p=[];for(let e=0;e{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)})),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach((e=>{e.setEnabled(!1)})),this._visible=!1}update(){if(!this._visible)return;if(this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,ge.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,void 0!==this._light.shadowMinZ?this._light.shadowMinZ:this._camera.minZ),ge.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,void 0!==this._light.shadowMaxZ?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();ge.Vector3[2].copyFromFloats(ge.Vector3[1].x,ge.Vector3[1].y,ge.Vector3[0].z),ge.Vector3[3].copyFromFloats(ge.Vector3[1].x,ge.Vector3[0].y,ge.Vector3[0].z),ge.Vector3[4].copyFromFloats(ge.Vector3[0].x,ge.Vector3[0].y,ge.Vector3[0].z),ge.Vector3[5].copyFromFloats(ge.Vector3[0].x,ge.Vector3[1].y,ge.Vector3[0].z),de.TransformCoordinatesToRef(ge.Vector3[2],e,ge.Vector3[2]),de.TransformCoordinatesToRef(ge.Vector3[3],e,ge.Vector3[3]),de.TransformCoordinatesToRef(ge.Vector3[4],e,ge.Vector3[4]),de.TransformCoordinatesToRef(ge.Vector3[5],e,ge.Vector3[5]),ge.Vector3[6].copyFromFloats(ge.Vector3[1].x,ge.Vector3[1].y,ge.Vector3[1].z),ge.Vector3[7].copyFromFloats(ge.Vector3[1].x,ge.Vector3[0].y,ge.Vector3[1].z),ge.Vector3[8].copyFromFloats(ge.Vector3[0].x,ge.Vector3[0].y,ge.Vector3[1].z),ge.Vector3[9].copyFromFloats(ge.Vector3[0].x,ge.Vector3[1].y,ge.Vector3[1].z),de.TransformCoordinatesToRef(ge.Vector3[6],e,ge.Vector3[6]),de.TransformCoordinatesToRef(ge.Vector3[7],e,ge.Vector3[7]),de.TransformCoordinatesToRef(ge.Vector3[8],e,ge.Vector3[8]),de.TransformCoordinatesToRef(ge.Vector3[9],e,ge.Vector3[9]),Zu("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),Zu("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),Zu("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),Zu("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),Zu("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),Zu("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),ge.Vector3[2].toArray(this._nearPlaneVertices,0),ge.Vector3[3].toArray(this._nearPlaneVertices,3),ge.Vector3[4].toArray(this._nearPlaneVertices,6),ge.Vector3[5].toArray(this._nearPlaneVertices,9),this._lightHelperFrustumMeshes[6].geometry?.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),ge.Vector3[6].toArray(this._farPlaneVertices,0),ge.Vector3[7].toArray(this._farPlaneVertices,3),ge.Vector3[8].toArray(this._farPlaneVertices,6),ge.Vector3[9].toArray(this._farPlaneVertices,9),this._lightHelperFrustumMeshes[7].geometry?.updateVerticesDataDirectly("position",this._farPlaneVertices,0),ge.Vector3[2].toArray(this._rightPlaneVertices,0),ge.Vector3[6].toArray(this._rightPlaneVertices,3),ge.Vector3[7].toArray(this._rightPlaneVertices,6),ge.Vector3[3].toArray(this._rightPlaneVertices,9),this._lightHelperFrustumMeshes[8].geometry?.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),ge.Vector3[5].toArray(this._leftPlaneVertices,0),ge.Vector3[9].toArray(this._leftPlaneVertices,3),ge.Vector3[8].toArray(this._leftPlaneVertices,6),ge.Vector3[4].toArray(this._leftPlaneVertices,9),this._lightHelperFrustumMeshes[9].geometry?.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),ge.Vector3[2].toArray(this._topPlaneVertices,0),ge.Vector3[6].toArray(this._topPlaneVertices,3),ge.Vector3[9].toArray(this._topPlaneVertices,6),ge.Vector3[5].toArray(this._topPlaneVertices,9),this._lightHelperFrustumMeshes[10].geometry?.updateVerticesDataDirectly("position",this._topPlaneVertices,0),ge.Vector3[3].toArray(this._bottomPlaneVertices,0),ge.Vector3[7].toArray(this._bottomPlaneVertices,3),ge.Vector3[8].toArray(this._bottomPlaneVertices,6),ge.Vector3[4].toArray(this._bottomPlaneVertices,9),this._lightHelperFrustumMeshes[11].geometry?.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach((e=>{e.material?.dispose(),e.dispose()})),this._rootNode.dispose()}_createGeometry(){this._rootNode=new xn("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[ge.Vector3[0],ge.Vector3[1],ge.Vector3[2],ge.Vector3[3],ge.Vector3[4]];const e=Zu("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[ge.Vector3[5],ge.Vector3[6],ge.Vector3[7],ge.Vector3[8],ge.Vector3[9]];const t=Zu("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[ge.Vector3[10],ge.Vector3[11]];const i=Zu("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[ge.Vector3[12],ge.Vector3[0]];const s=Zu("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[ge.Vector3[1],ge.Vector3[2]];const r=Zu("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[ge.Vector3[3],ge.Vector3[4]];const n=Zu("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,s,r,n);const o=(e,t,i)=>{const s=new bo(e+"plane",this._scene),r=new yc(e+"PlaneMat",this._scene);s.material=r,s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,r.emissiveColor=t,r.alpha=this.transparency,r.backFaceCulling=!1,r.disableLighting=!0;const n=new cn;n.positions=i,n.indices=[0,1,2,0,2,3],n.applyToMesh(s,!0),this._lightHelperFrustumMeshes.push(s)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],o("near",new Ce(1,0,0),this._nearPlaneVertices),o("far",new Ce(.3,0,0),this._farPlaneVertices),o("right",new Ce(0,1,0),this._rightPlaneVertices),o("left",new Ce(0,.3,0),this._leftPlaneVertices),o("top",new Ce(0,0,1),this._topPlaneVertices),o("bottom",new Ce(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=ge.Vector3[2],this._nearLinesPoints[1]=ge.Vector3[3],this._nearLinesPoints[2]=ge.Vector3[4],this._nearLinesPoints[3]=ge.Vector3[5],this._nearLinesPoints[4]=ge.Vector3[2],this._farLinesPoints[0]=ge.Vector3[6],this._farLinesPoints[1]=ge.Vector3[7],this._farLinesPoints[2]=ge.Vector3[8],this._farLinesPoints[3]=ge.Vector3[9],this._farLinesPoints[4]=ge.Vector3[6],this._trLinesPoints[0]=ge.Vector3[2],this._trLinesPoints[1]=ge.Vector3[6],this._brLinesPoints[0]=ge.Vector3[3],this._brLinesPoints[1]=ge.Vector3[7],this._tlLinesPoints[0]=ge.Vector3[4],this._tlLinesPoints[1]=ge.Vector3[8],this._blLinesPoints[0]=ge.Vector3[5],this._blLinesPoints[1]=ge.Vector3[9]}_getInvertViewMatrix(){return fe.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),de.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}class Yd{}Yd.ALPHA_DISABLE=0,Yd.ALPHA_ADD=1,Yd.ALPHA_COMBINE=2,Yd.ALPHA_SUBTRACT=3,Yd.ALPHA_MULTIPLY=4,Yd.ALPHA_MAXIMIZED=5,Yd.ALPHA_ONEONE=6,Yd.ALPHA_PREMULTIPLIED=7,Yd.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Yd.ALPHA_INTERPOLATE=9,Yd.ALPHA_SCREENMODE=10,Yd.ALPHA_ONEONE_ONEONE=11,Yd.ALPHA_ALPHATOCOLOR=12,Yd.ALPHA_REVERSEONEMINUS=13,Yd.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Yd.ALPHA_ONEONE_ONEZERO=15,Yd.ALPHA_EXCLUSION=16,Yd.ALPHA_LAYER_ACCUMULATE=17,Yd.ALPHA_EQUATION_ADD=0,Yd.ALPHA_EQUATION_SUBSTRACT=1,Yd.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Yd.ALPHA_EQUATION_MAX=3,Yd.ALPHA_EQUATION_MIN=4,Yd.ALPHA_EQUATION_DARKEN=5,Yd.DELAYLOADSTATE_NONE=0,Yd.DELAYLOADSTATE_LOADED=1,Yd.DELAYLOADSTATE_LOADING=2,Yd.DELAYLOADSTATE_NOTLOADED=4,Yd.NEVER=512,Yd.ALWAYS=519,Yd.LESS=513,Yd.EQUAL=514,Yd.LEQUAL=515,Yd.GREATER=516,Yd.GEQUAL=518,Yd.NOTEQUAL=517,Yd.KEEP=7680,Yd.ZERO=0,Yd.REPLACE=7681,Yd.INCR=7682,Yd.DECR=7683,Yd.INVERT=5386,Yd.INCR_WRAP=34055,Yd.DECR_WRAP=34056,Yd.TEXTURE_CLAMP_ADDRESSMODE=0,Yd.TEXTURE_WRAP_ADDRESSMODE=1,Yd.TEXTURE_MIRROR_ADDRESSMODE=2,Yd.TEXTURE_CREATIONFLAG_STORAGE=1,Yd.TEXTUREFORMAT_ALPHA=0,Yd.TEXTUREFORMAT_LUMINANCE=1,Yd.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Yd.TEXTUREFORMAT_RGB=4,Yd.TEXTUREFORMAT_RGBA=5,Yd.TEXTUREFORMAT_RED=6,Yd.TEXTUREFORMAT_R=6,Yd.TEXTUREFORMAT_RG=7,Yd.TEXTUREFORMAT_RED_INTEGER=8,Yd.TEXTUREFORMAT_R_INTEGER=8,Yd.TEXTUREFORMAT_RG_INTEGER=9,Yd.TEXTUREFORMAT_RGB_INTEGER=10,Yd.TEXTUREFORMAT_RGBA_INTEGER=11,Yd.TEXTUREFORMAT_BGRA=12,Yd.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Yd.TEXTUREFORMAT_DEPTH32_FLOAT=14,Yd.TEXTUREFORMAT_DEPTH16=15,Yd.TEXTUREFORMAT_DEPTH24=16,Yd.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Yd.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Yd.TEXTUREFORMAT_STENCIL8=19,Yd.TEXTUREFORMAT_UNDEFINED=4294967295,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Yd.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Yd.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Yd.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Yd.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Yd.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Yd.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Yd.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Yd.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Yd.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Yd.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Yd.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Yd.TEXTURETYPE_UNSIGNED_BYTE=0,Yd.TEXTURETYPE_UNSIGNED_INT=0,Yd.TEXTURETYPE_FLOAT=1,Yd.TEXTURETYPE_HALF_FLOAT=2,Yd.TEXTURETYPE_BYTE=3,Yd.TEXTURETYPE_SHORT=4,Yd.TEXTURETYPE_UNSIGNED_SHORT=5,Yd.TEXTURETYPE_INT=6,Yd.TEXTURETYPE_UNSIGNED_INTEGER=7,Yd.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Yd.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Yd.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Yd.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Yd.TEXTURETYPE_UNSIGNED_INT_24_8=12,Yd.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Yd.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Yd.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Yd.TEXTURETYPE_UNDEFINED=16,Yd.TEXTURE_2D=3553,Yd.TEXTURE_2D_ARRAY=35866,Yd.TEXTURE_CUBE_MAP=34067,Yd.TEXTURE_CUBE_MAP_ARRAY=3735928559,Yd.TEXTURE_3D=32879,Yd.TEXTURE_NEAREST_SAMPLINGMODE=1,Yd.TEXTURE_NEAREST_NEAREST=1,Yd.TEXTURE_BILINEAR_SAMPLINGMODE=2,Yd.TEXTURE_LINEAR_LINEAR=2,Yd.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Yd.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Yd.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Yd.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Yd.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Yd.TEXTURE_NEAREST_LINEAR=7,Yd.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Yd.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Yd.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Yd.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Yd.TEXTURE_LINEAR_NEAREST=12,Yd.TEXTURE_EXPLICIT_MODE=0,Yd.TEXTURE_SPHERICAL_MODE=1,Yd.TEXTURE_PLANAR_MODE=2,Yd.TEXTURE_CUBIC_MODE=3,Yd.TEXTURE_PROJECTION_MODE=4,Yd.TEXTURE_SKYBOX_MODE=5,Yd.TEXTURE_INVCUBIC_MODE=6,Yd.TEXTURE_EQUIRECTANGULAR_MODE=7,Yd.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Yd.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Yd.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Yd.TEXTURE_FILTERING_QUALITY_HIGH=64,Yd.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Yd.TEXTURE_FILTERING_QUALITY_LOW=8,Yd.SCALEMODE_FLOOR=1,Yd.SCALEMODE_NEAREST=2,Yd.SCALEMODE_CEILING=3,Yd.MATERIAL_TextureDirtyFlag=1,Yd.MATERIAL_LightDirtyFlag=2,Yd.MATERIAL_FresnelDirtyFlag=4,Yd.MATERIAL_AttributesDirtyFlag=8,Yd.MATERIAL_MiscDirtyFlag=16,Yd.MATERIAL_PrePassDirtyFlag=32,Yd.MATERIAL_AllDirtyFlag=63,Yd.MATERIAL_TriangleFillMode=0,Yd.MATERIAL_WireFrameFillMode=1,Yd.MATERIAL_PointFillMode=2,Yd.MATERIAL_PointListDrawMode=3,Yd.MATERIAL_LineListDrawMode=4,Yd.MATERIAL_LineLoopDrawMode=5,Yd.MATERIAL_LineStripDrawMode=6,Yd.MATERIAL_TriangleStripDrawMode=7,Yd.MATERIAL_TriangleFanDrawMode=8,Yd.MATERIAL_ClockWiseSideOrientation=0,Yd.MATERIAL_CounterClockWiseSideOrientation=1,Yd.ACTION_NothingTrigger=0,Yd.ACTION_OnPickTrigger=1,Yd.ACTION_OnLeftPickTrigger=2,Yd.ACTION_OnRightPickTrigger=3,Yd.ACTION_OnCenterPickTrigger=4,Yd.ACTION_OnPickDownTrigger=5,Yd.ACTION_OnDoublePickTrigger=6,Yd.ACTION_OnPickUpTrigger=7,Yd.ACTION_OnPickOutTrigger=16,Yd.ACTION_OnLongPressTrigger=8,Yd.ACTION_OnPointerOverTrigger=9,Yd.ACTION_OnPointerOutTrigger=10,Yd.ACTION_OnEveryFrameTrigger=11,Yd.ACTION_OnIntersectionEnterTrigger=12,Yd.ACTION_OnIntersectionExitTrigger=13,Yd.ACTION_OnKeyDownTrigger=14,Yd.ACTION_OnKeyUpTrigger=15,Yd.PARTICLES_BILLBOARDMODE_Y=2,Yd.PARTICLES_BILLBOARDMODE_ALL=7,Yd.PARTICLES_BILLBOARDMODE_STRETCHED=8,Yd.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Yd.MESHES_CULLINGSTRATEGY_STANDARD=0,Yd.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Yd.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Yd.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Yd.SCENELOADER_NO_LOGGING=0,Yd.SCENELOADER_MINIMAL_LOGGING=1,Yd.SCENELOADER_SUMMARY_LOGGING=2,Yd.SCENELOADER_DETAILED_LOGGING=3,Yd.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Yd.PREPASS_POSITION_TEXTURE_TYPE=1,Yd.PREPASS_VELOCITY_TEXTURE_TYPE=2,Yd.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Yd.PREPASS_COLOR_TEXTURE_TYPE=4,Yd.PREPASS_DEPTH_TEXTURE_TYPE=5,Yd.PREPASS_NORMAL_TEXTURE_TYPE=6,Yd.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Yd.BUFFER_CREATIONFLAG_READ=1,Yd.BUFFER_CREATIONFLAG_WRITE=2,Yd.BUFFER_CREATIONFLAG_READWRITE=3,Yd.BUFFER_CREATIONFLAG_UNIFORM=4,Yd.BUFFER_CREATIONFLAG_VERTEX=8,Yd.BUFFER_CREATIONFLAG_INDEX=16,Yd.BUFFER_CREATIONFLAG_STORAGE=32,Yd.RENDERPASS_MAIN=0,Yd.INPUT_ALT_KEY=18,Yd.INPUT_CTRL_KEY=17,Yd.INPUT_META_KEY1=91,Yd.INPUT_META_KEY2=92,Yd.INPUT_META_KEY3=93,Yd.INPUT_SHIFT_KEY=16,Yd.SNAPSHOTRENDERING_STANDARD=0,Yd.SNAPSHOTRENDERING_FAST=1,Yd.PERSPECTIVE_CAMERA=0,Yd.ORTHOGRAPHIC_CAMERA=1,Yd.FOVMODE_VERTICAL_FIXED=0,Yd.FOVMODE_HORIZONTAL_FIXED=1,Yd.RIG_MODE_NONE=0,Yd.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Yd.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Yd.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Yd.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Yd.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Yd.RIG_MODE_VR=20,Yd.RIG_MODE_CUSTOM=22,Yd.MAX_SUPPORTED_UV_SETS=6,Yd.GL_ALPHA_EQUATION_ADD=32774,Yd.GL_ALPHA_EQUATION_MIN=32775,Yd.GL_ALPHA_EQUATION_MAX=32776,Yd.GL_ALPHA_EQUATION_SUBTRACT=32778,Yd.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Yd.GL_ALPHA_FUNCTION_SRC=768,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Yd.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Yd.GL_ALPHA_FUNCTION_DST_ALPHA=772,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Yd.GL_ALPHA_FUNCTION_DST_COLOR=774,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Yd.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Yd.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Yd.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Yd.SnippetUrl="https://snippet.babylonjs.com",Yd.FOGMODE_NONE=0,Yd.FOGMODE_EXP=1,Yd.FOGMODE_EXP2=2,Yd.FOGMODE_LINEAR=3,Yd.BYTE=5120,Yd.UNSIGNED_BYTE=5121,Yd.SHORT=5122,Yd.UNSIGNED_SHORT=5123,Yd.INT=5124,Yd.UNSIGNED_INT=5125,Yd.FLOAT=5126,Yd.PositionKind="position",Yd.NormalKind="normal",Yd.TangentKind="tangent",Yd.UVKind="uv",Yd.UV2Kind="uv2",Yd.UV3Kind="uv3",Yd.UV4Kind="uv4",Yd.UV5Kind="uv5",Yd.UV6Kind="uv6",Yd.ColorKind="color",Yd.ColorInstanceKind="instanceColor",Yd.MatricesIndicesKind="matricesIndices",Yd.MatricesWeightsKind="matricesWeights",Yd.MatricesIndicesExtraKind="matricesIndicesExtra",Yd.MatricesWeightsExtraKind="matricesWeightsExtra";class Qd{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class jd extends gn{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new Qd){super(null),gn.Instances.push(this),void 0===e.deterministicLockstep&&(e.deterministicLockstep=!1),void 0!==e.timeStep&&(this._timeStep=e.timeStep),void 0===e.lockstepMaxSteps&&(e.lockstepMaxSteps=4),this._options=e,ie.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},we.Log(`Babylon.js v${gn.Version} - Null engine`);const t="undefined"!=typeof self?self:void 0!==i.g?i.g:window;"undefined"==typeof URL&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(t.Blob=function(){})}createVertexBuffer(e){const t=new Oi;return t.references=1,t}createIndexBuffer(e){const t=new Oi;return t.references=1,t}clear(e,t,i,s=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,s,r){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=null!==e&&Fi.IsWrapper(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,s=!1,r,n,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,s){return!0}setBool(e,t){return!0}setFloat4(e,t,i,s,r){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=0!==e,t||this.setDepthWrite(0===e),this._alphaMode=e)}bindBuffers(e,t,i){}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}draw(e,t,i,s){}drawElementsType(e,t,i,s){}drawArraysType(e,t,i,s){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u){const d=new Pi(this,Ai.Url),_=String(e);return d.url=_,d.generateMipMaps=!t,d.samplingMode=r,d.invertY=i,d.baseWidth=this._options.textureSize,d.baseHeight=this._options.textureSize,d.width=this._options.textureSize,d.height=this._options.textureSize,h&&(d.format=h),d.isReady=!0,n&&setTimeout((()=>{n(d)})),this._internalTexturesCache.push(d),d}_createHardwareRenderTargetWrapper(e,t,i){const s=new Ka(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.type=void 0===t.type?0:t.type,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.type=0,s.samplingMode=3);const r=new Pi(this,Ai.RenderTarget),n=e.width||e,o=e.height||e;return i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,r.baseWidth=n,r.baseHeight=o,r.width=n,r.height=o,r.isReady=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1),i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer;const r=new Pi(this,Ai.RenderTarget);return r.baseWidth=e,r.baseHeight=e,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new Pi(this,Ai.Raw);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),u}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r,e.type=n,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,s,r){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!r&&this.setViewport(this._cachedViewport,i,s)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new Oi;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,s=!1,r){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,s){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,s=0){}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){}_uploadImageToTexture(e,t,i=0,s=0){}}ki.prototype._debugPushGroup=function(e,t){},ki.prototype._debugPopGroup=function(e){},ki.prototype._debugInsertMarker=function(e,t){},ki.prototype._debugFlushPendingCommands=function(){};class Kd{constructor(){this._timeElapsedQueryEnded=!1}}class $d{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Sn.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Sn.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}gn.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},gn.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},gn.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},gn.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},gn.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},gn.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},gn.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},gn.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},gn.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},gn.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},gn.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new Kd;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery),this._currentNonTimestampToken=i}return i},gn.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const s=this._gl.getParameter(i.GPU_DISJOINT_EXT);let r=!1;if(e._endTimeQuery?r=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(r=this._getTimeQueryAvailability(e._timeElapsedQuery)),r&&!s){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},gn.prototype._captureGPUFrameTime=!1,gn.prototype._gpuFrameTime=new tr,gn.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},gn.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add((()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},gn.prototype._getGlAlgorithmType=function(e){return e===Sn.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(Sn.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Sn.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new $d),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Sn.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),Sn.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===Sn.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==Sn.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Sn.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const s=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(s.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};var qd=!0;gn.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},gn.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},gn.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},gn.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},gn.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},gn.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},gn.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},ki.prototype.createExternalTexture=function(e){return null},ki.prototype.setExternalTexture=function(e,t){throw new Error("setExternalTexture: This engine does not support external textures!")},ki.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const s=this._getInternalFormat(e.format),r=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},ki.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},ki.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},ki.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let s=0;s1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],s.readBuffer(r[t]),s.drawBuffers(r),s.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,s.COLOR_BUFFER_BIT,s.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];s.drawBuffers(r)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(a=t.depthTextureFormat)),g.label=t?.label??"MultiRenderTargetWrapper";const v=this._gl,x=v.createFramebuffer();this._bindUnboundFramebuffer(x);const b=e.width||e,T=e.height||e,y=[],S=[],C=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),E=this._setupFramebufferDepthAttachments(!C&&n,!o&&r,b,T);g._framebuffer=x,g._depthStencilBuffer=E,g._generateDepthBuffer=!o&&r,g._generateStencilBuffer=!C&&n,g._attachments=S;for(let e=0;e1||this.isWebGPU);const p=this.webGLVersion>1,f=v[p?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(S.push(f),-1===o)continue;const g=new Pi(this,Ai.MultiRenderTarget);y[e]=g,v.activeTexture(v["TEXTURE"+e]),v.bindTexture(o,g._hardwareTexture.underlyingResource),v.texParameteri(o,v.TEXTURE_MAG_FILTER,l.mag),v.texParameteri(o,v.TEXTURE_MIN_FILTER,l.min),v.texParameteri(o,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(o,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE);const x=this._getRGBABufferInternalSizedFormat(i,n,r),C=this._getInternalFormat(n),E=this._getWebGLTextureType(i);if(!p||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,x,b,T,0,C,E,null);g.isCube=!0}else v.texImage2D(v.TEXTURE_2D,0,x,b,T,0,C,E,null);else 35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=a,v.texImage3D(o,0,x,b,T,a,0,C,E,null);s&&v.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=b,g.baseHeight=T,g.width=b,g.height=T,g.isReady=!0,g.samples=1,g.generateMipMaps=s,g.samplingMode=t,g.type=i,g._useSRGBBuffer=r,g.format=n,this._internalTexturesCache.push(g)}if(o&&this._caps.depthTextureExtension){const e=new Pi(this,Ai.Depth);let t=5,i=v.DEPTH_COMPONENT16,r=v.DEPTH_COMPONENT,n=v.UNSIGNED_SHORT,o=v.DEPTH_ATTACHMENT;this.webGLVersion<2?i=v.DEPTH_COMPONENT:14===a?(t=1,n=v.FLOAT,i=v.DEPTH_COMPONENT32F):18===a?(t=0,n=v.FLOAT_32_UNSIGNED_INT_24_8_REV,i=v.DEPTH32F_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT):16===a?(t=0,n=v.UNSIGNED_INT,i=v.DEPTH_COMPONENT24,o=v.DEPTH_ATTACHMENT):13!==a&&17!==a||(t=12,n=v.UNSIGNED_INT_24_8,i=v.DEPTH24_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT),v.activeTexture(v.TEXTURE0),v.bindTexture(v.TEXTURE_2D,e._hardwareTexture.underlyingResource),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MAG_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MIN_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),v.texImage2D(v.TEXTURE_2D,0,i,b,T,0,r,n,null),v.framebufferTexture2D(v.FRAMEBUFFER,o,v.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=b,e.baseHeight=T,e.width=b,e.height=T,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=a,e.type=t,y[l]=e,this._internalTexturesCache.push(e)}return g.setTextures(y),i&&v.drawBuffers(S),this._bindUnboundFramebuffer(null),g.setLayerAndFaceIndices(f,p),this.resetTextureCache(),g},ki.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const s=e._attachments.length;if(0===s)return 1;const r=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const n=!!e._depthStencilBuffer;if(n&&(r.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(r.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof r.renderbufferStorageMultisample){const n=r.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(s.width,s.height,t,-1,this._getRGBABufferInternalSizedFormat(s.type,s.format,s._useSRGBBuffer),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),s.samples=t,o.push(a)}i&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},ki.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Pi(this,Ai.DepthStencil);if(i.isCube=!0,1===this.webGLVersion)return we.Error("Depth cube texture is not supported by WebGL 1."),i;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction);for(let t=0;t<6;t++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},ki.prototype._partialLoadFile=function(e,t,i,s,r=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&s(i)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},ki.prototype._cascadeLoadFiles=function(e,t,i,s=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,r,t,s)},ki.prototype._cascadeLoadImgs=function(e,t,i,s,r=null,n){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(s[a],a,o,e,t,i,r,n)},ki.prototype._partialLoadImg=function(e,t,i,s,r,n,o=null,a){const l=ns();Qi(e,(e=>{i[t]=e,i._internalCount++,s&&s.removePendingData(l),6===i._internalCount&&n&&n(r,i)}),((e,t)=>{s&&s.removePendingData(l),o&&o(e,t)}),s?s.offlineProvider:null,a),s&&s.addPendingData(l)},ki.prototype._setCubeMapTextureParams=function(e,t,i){const s=this._gl;s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)},ki.prototype.createCubeTextureBase=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=null,_=null,p=!1){const f=u||new Pi(this,Ai.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!s,f._lodGenerationScale=h,f._lodGenerationOffset=c,f._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!s),f!==u&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=a,f._files=i);const m=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));const g=e.split("?")[0],v=g.lastIndexOf("."),x=a||(v>-1?g.substring(v).toLowerCase():"");let b=null;for(const e of ki._TextureLoaders)if(e.canLoad(x)){b=e;break}const T=(u,g)=>{e===m?n&&u&&n(u.status+" "+u.statusText,g):(we.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!s,r,n,o,a,l,h,c,f,d,_,p))};if(b){const s=e=>{d&&d(f,e),b.loadCubeData(e,f,l,r,n)};i&&6===i.length?b.supportCascades?this._cascadeLoadFiles(t,(e=>s(e.map((e=>new Uint8Array(e))))),i,n):n?n("Textures type does not support cascades."):we.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>s(new Uint8Array(e))),void 0,void 0,!0,T)}else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,f,((e,t)=>{_&&_(e,t)}),i,n)}return this._internalTexturesCache.push(f),f},ki.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,_=!1){const p=this._gl;return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,(e=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?ki.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=i,a=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let h=o?this._getInternalFormat(o):p.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),s=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+s}Object.defineProperty(gn.prototype,"onBeforeViewRenderObservable",{get:function(){return Jd}}),Object.defineProperty(gn.prototype,"onAfterViewRenderObservable",{get:function(){return e_}}),Object.defineProperty(gn.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){this._inputElement!==e&&(this._inputElement=e,this._onEngineViewChanged?.())}}),gn.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},gn.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const s=this.getRenderingCanvas();s&&(e.width=s.width,e.height=s.height);const r={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(r),t&&!Array.isArray(t)&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),r},gn.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},gn.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const s=this.getRenderingCanvas();Jd.notifyObservers(e);const r=e.camera;let n=null,o=null,a=null;if(r&&(a=Array.isArray(r)?r[0].getScene():r.getScene(),n=a.activeCamera,o=a.activeCameras,this.activeView=e,Array.isArray(r)?a.activeCameras=r:(a.activeCamera=r,a.activeCameras=null)),e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),r=e!==t.width||s.width!==t.width||i!==t.height||s.height!==t.height;t.clientWidth&&t.clientHeight&&r&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!s.width||!s.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,s.width,s.height),i.drawImage(s,0,0),a&&(a.activeCameras=o,a.activeCamera=n),e_.notifyObservers(e),0))},gn.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},ki.prototype.createStorageBuffer=function(e,t){throw new Error("createStorageBuffer: Unsupported method in this engine!")},ki.prototype.updateStorageBuffer=function(e,t,i,s){},ki.prototype.readFromStorageBuffer=function(e,t,i,s){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")},ki.prototype.setStorageBuffer=function(e,t){throw new Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(gn.prototype,"texturesSupported",{get:function(){const e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(gn.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),gn.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},gn.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,s=t.length;i{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}i_.DEFAULT_BUFFER_SIZE=65536;const s_=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],r_=[()=>1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],n_=(e,t)=>s_[e]*r_[e](t),o_=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class a_{constructor(){this.preScaled=!1,this.l00=de.Zero(),this.l1_1=de.Zero(),this.l10=de.Zero(),this.l11=de.Zero(),this.l2_2=de.Zero(),this.l2_1=de.Zero(),this.l20=de.Zero(),this.l21=de.Zero(),this.l22=de.Zero()}addLight(e,t,i){ge.Vector3[0].set(t.r,t.g,t.b);const s=ge.Vector3[0],r=ge.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(n_(0,e),ge.Vector3[2]),this.l00.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(1,e),ge.Vector3[2]),this.l1_1.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(2,e),ge.Vector3[2]),this.l10.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(3,e),ge.Vector3[2]),this.l11.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(4,e),ge.Vector3[2]),this.l2_2.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(5,e),ge.Vector3[2]),this.l2_1.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(6,e),ge.Vector3[2]),this.l20.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(7,e),ge.Vector3[2]),this.l21.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(8,e),ge.Vector3[2]),this.l22.addInPlace(ge.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(o_[0]),this.l1_1.scaleInPlace(o_[1]),this.l10.scaleInPlace(o_[2]),this.l11.scaleInPlace(o_[3]),this.l2_2.scaleInPlace(o_[4]),this.l2_1.scaleInPlace(o_[5]),this.l20.scaleInPlace(o_[6]),this.l21.scaleInPlace(o_[7]),this.l22.scaleInPlace(o_[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(s_[0]),this.l1_1.scaleInPlace(s_[1]),this.l10.scaleInPlace(s_[2]),this.l11.scaleInPlace(s_[3]),this.l2_2.scaleInPlace(s_[4]),this.l2_1.scaleInPlace(s_[5]),this.l20.scaleInPlace(s_[6]),this.l21.scaleInPlace(s_[7]),this.l22.scaleInPlace(s_[8])}updateFromArray(e){return de.FromArrayToRef(e[0],0,this.l00),de.FromArrayToRef(e[1],0,this.l1_1),de.FromArrayToRef(e[2],0,this.l10),de.FromArrayToRef(e[3],0,this.l11),de.FromArrayToRef(e[4],0,this.l2_2),de.FromArrayToRef(e[5],0,this.l2_1),de.FromArrayToRef(e[6],0,this.l20),de.FromArrayToRef(e[7],0,this.l21),de.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return de.FromFloatsToRef(e[0],e[1],e[2],this.l00),de.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),de.FromFloatsToRef(e[6],e[7],e[8],this.l10),de.FromFloatsToRef(e[9],e[10],e[11],this.l11),de.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),de.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),de.FromFloatsToRef(e[18],e[19],e[20],this.l20),de.FromFloatsToRef(e[21],e[22],e[23],this.l21),de.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new a_).updateFromArray(e)}static FromPolynomial(e){const t=new a_;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class l_{constructor(){this.x=de.Zero(),this.y=de.Zero(),this.z=de.Zero(),this.xx=de.Zero(),this.yy=de.Zero(),this.zz=de.Zero(),this.xy=de.Zero(),this.yz=de.Zero(),this.zx=de.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=a_.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){ge.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=ge.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),ge.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),ge.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(ge.Vector3[0]).addInPlace(ge.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(ge.Vector3[0]).subtractInPlace(ge.Vector3[1]),this.zz.copyFrom(e.l00),ge.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(ge.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return(new l_).updateFromHarmonics(e)}static FromArray(e){const t=new l_;return de.FromArrayToRef(e[0],0,t.x),de.FromArrayToRef(e[1],0,t.y),de.FromArrayToRef(e[2],0,t.z),de.FromArrayToRef(e[3],0,t.xx),de.FromArrayToRef(e[4],0,t.yy),de.FromArrayToRef(e[5],0,t.zz),de.FromArrayToRef(e[6],0,t.yz),de.FromArrayToRef(e[7],0,t.zx),de.FromArrayToRef(e[8],0,t.xy),t}}function h_(e,t,i,s=!0){const r=e.getScene(),n=r.getEngine(),o=new pl("resized"+e.name,{width:t,height:i},r,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);o.wrapU=e.wrapU,o.wrapV=e.wrapV,o.uOffset=e.uOffset,o.vOffset=e.vOffset,o.uScale=e.uScale,o.vScale=e.vScale,o.uAng=e.uAng,o.vAng=e.vAng,o.wAng=e.wAng,o.coordinatesIndex=e.coordinatesIndex,o.level=e.level,o.anisotropicFilteringLevel=e.anisotropicFilteringLevel,o._texture.isReady=!1,e.wrapU=Vo.CLAMP_ADDRESSMODE,e.wrapV=Vo.CLAMP_ADDRESSMODE;const a=new Nh("pass",1,null,s?Vo.BILINEAR_SAMPLINGMODE:Vo.NEAREST_SAMPLINGMODE,n,!1,0);return a.externalTextureSamplerBinding=!0,a.getEffect().executeWhenCompiled((()=>{a.onApply=function(t){t.setTexture("textureSampler",e)};const t=o.renderTarget;t&&(r.postProcessManager.directRender([a],t),n.unBindFramebuffer(t),o.disposeFramebufferObjects(),a.dispose(),o.getInternalTexture().isReady=!0)})),o}function c_(e,t,i,s,r,n,o,a){const l=t.getEngine();return t.isReady=!1,r=r??t.samplingMode,s=s??t.type,n=n??t.format,o=o??t.width,a=a??t.height,-1===s&&(s=0),new Promise((h=>{const c=new qa("postprocess",e,null,null,1,null,r,l,!1,void 0,s,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:o,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:s,format:n});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=s,t.format=5,t.isReady=!0,h(t)}))}))}let u_,d_;function __(e){u_||(u_=new Float32Array(1),d_=new Int32Array(u_.buffer)),u_[0]=e;const t=d_[0];let i=t>>16&32768,s=t>>12&2047;const r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=(255==r?0:1)&&8388607&t,i):r<113?(s|=2048,i|=(s>>114-r)+(s>>113-r&1),i):(i|=r-112<<10|s>>1,i+=1&s,i)}function p_(e){const t=(32768&e)>>15,i=(31744&e)>>10,s=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==i?s?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+s/Math.pow(2,10))}bi.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";const f_=async(e,t,i,s,r)=>{const n=e.getScene(),o=n.getEngine();let a;if(e.isCube){const e=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new qa("lodCube","lodCube",["lod","gamma"],null,1,null,Vo.NEAREST_NEAREST_MIPNEAREST,o,!1,e[s])}else a=new qa("lod","lod",["lod","gamma"],null,1,null,Vo.NEAREST_NEAREST_MIPNEAREST,o);await new Promise((e=>{a.getEffect().executeWhenCompiled((()=>{e(0)}))}));const l=new pl("temp",{width:t,height:i},n,!1);a.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",r),t.setBool("gamma",e.gammaSpace)};const h=e.getInternalTexture();try{if(l.renderTarget&&h){const s=h.samplingMode;0!==r?e.updateSamplingMode(Vo.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(Vo.NEAREST_NEAREST),n.postProcessManager.directRender([a],l.renderTarget,!0),e.updateSamplingMode(s);const c=await o.readPixels(0,0,t,i),u=new Uint8Array(c.buffer,0,c.byteLength);return o.unBindFramebuffer(l.renderTarget),u}throw Error("Render to texture failed.")}finally{l.dispose(),a.dispose()}};async function m_(e,t,i,s=0,r=0){return!e.isReady()&&e._texture&&await new Promise(((t,i)=>{null!==e._texture?e._texture.onLoadedObservable.addOnce((()=>{t(0)})):i(0)})),await f_(e,t,i,s,r)}const g_={CreateResizedCopy:h_,ApplyPostProcess:c_,ToHalfFloat:__,FromHalfFloat:p_,GetTextureDataAsync:m_};class v_{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const s=new qa("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);s.externalTextureSamplerBinding=!0;const r=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});s.getEffect().executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],r,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),r._swapAndDie(t),t.isReady=!0}))};n&&(r?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return c_("rgbdEncode",e,t,i,1,5)}}class x_{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class b_{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),a=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace;let h=0;return 1!=e.textureType&&2!=e.textureType||(h=1),new Promise((e=>{Promise.all([s,i,r,n,o,a]).then((([i,s,r,n,o,a])=>{const c={size:t,right:s,left:i,up:r,down:n,front:o,back:a,format:5,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(c))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new a_;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let a=0;a<6;a++){const l=this._FileFaces[a],h=e[l.name];let c=o;const u=5===e.format?4:3;for(let a=0;ag){const t=g/e;p*=t,f*=t,m*=t}}else p=xe.Clamp(p,0,g),f=xe.Clamp(f,0,g),m=xe.Clamp(m,0,g);const v=new Ce(p,f,m);t.addLight(o,v,_),i+=_,d+=s}c+=r}}const a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),l_.FromHarmonics(t)}}b_._FileFaces=[new x_("right",new de(1,0,0),new de(0,0,-1),new de(0,-1,0)),new x_("left",new de(-1,0,0),new de(0,0,1),new de(0,-1,0)),new x_("up",new de(0,1,0),new de(1,0,0),new de(0,0,1)),new x_("down",new de(0,-1,0),new de(1,0,0),new de(0,0,-1)),new x_("front",new de(0,0,1),new de(1,0,0),new de(0,-1,0)),new x_("back",new de(0,0,-1),new de(-1,0,0),new de(0,-1,0))],b_.MAX_HDRI_VALUE=4096,b_.PRESERVE_CLAMPED_COLORS=!1,No.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(No.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=b_.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});bi.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";const T_="image/png",y_=2,S_=[134,22,135,150,246,214,150,54];function C_(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;ey_)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${y_}".`);return 2===e.version?e:e={...e,version:2,imageType:T_}}async function A_(e,t={}){const i=e.getInternalTexture();if(!i)return Promise.reject("The cube texture is invalid.");const s=t.imageType??T_,r=i.getEngine();if(2!==e.textureType&&1!==e.textureType&&0!==e.textureType&&0!==e.textureType&&7!==e.textureType&&-1!==e.textureType)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let n=1;if(!r.getCaps().textureFloatRender&&(n=2,!r.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");e.sphericalPolynomial;const o=e.getInternalTexture()?._sphericalPolynomialPromise,a=i.width,l=new dr(r),h={};r.flushFramebuffer();const c=xe.ILog2(i.width);for(let i=0;i<=c;i++){const o=Math.pow(2,c-i);for(let a=0;a<6;a++){let c=await e.readPixels(a,i,void 0,!1);if(c&&c.byteLength===c.length){const e=new Float32Array(4*c.byteLength);for(let t=0;t{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);s.getEffect().executeWhenCompiled((()=>{s.externalTextureSamplerBinding=!0,s.onApply=s=>{s._bindTexture("textureSampler",i),s.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([s],h,!0,n,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(r),u())}))}else{if(t._uploadImageToTexture(c,e,n,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,n,0)}u()}}))}function O_(e,t,i=T_){if(!hs.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const s=xe.ILog2(e.width)+1,r=e.getEngine();let n=!1,o=!1,a=null,l=null,h=null;const c=r.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(3,e),c.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(n=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,o=!0,h={}),n)a=new qa("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=r.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,o){const t=3,i=e._lodGenerationScale,n=e._lodGenerationOffset;for(let o=0;oM_(t,r,n,a,p,c,s,o,h,l,e)));else{const t=new Image;t.src=p,f=new Promise(((i,u)=>{t.onload=()=>{M_(t,r,n,a,p,c,s,o,h,l,e).then((()=>i())).catch((e=>{u(e)}))},t.onerror=e=>{u(e)}}))}u.push(f)}if(t.length{l&&(r._releaseTexture(e),l._swapAndDie(e)),a&&a.dispose(),o&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function D_(e,t){const i=(t=E_(t)).irradiance;if(!i)return;const s=new l_;de.FromArrayToRef(i.x,0,s.x),de.FromArrayToRef(i.y,0,s.y),de.FromArrayToRef(i.z,0,s.z),de.FromArrayToRef(i.xx,0,s.xx),de.FromArrayToRef(i.yy,0,s.yy),de.FromArrayToRef(i.zz,0,s.zz),de.FromArrayToRef(i.yz,0,s.yz),de.FromArrayToRef(i.zx,0,s.zx),de.FromArrayToRef(i.xy,0,s.xy),e._sphericalPolynomial=s}function w_(e,t,i,s,r){const n=O_(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:n,isReady:!0,isAsync:!0}),e._source=Ai.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=s,e._lodGenerationOffset=r,e._sphericalPolynomial=i,O_(e,t).then((()=>(e.isReady=!0,e)))}const N_={GetEnvInfo:C_,CreateEnvTextureAsync:A_,CreateImageDataArrayBufferViews:R_,UploadEnvLevelsAsync:I_,UploadLevelsAsync:O_,UploadEnvSpherical:D_};function F_(e,t,i,s){let r=s,n=0,o="";for(;r=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function k_(e){let t=0,i="",s=!1;const r=[];for(;t=0&&e.charAt(t)!==i&&(!s||e.charAt(t)!==s);)t--;return t}class U_{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&we.Log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&we.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&d.push(t.substring(i+1))}"void"!==r&&d.push("return"),this._functionDescr.push({name:n,type:r,parameters:d,body:c,callIndex:0}),e=h+1;const _=t>0?this._sourceCode.substring(0,t):"",p=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&we.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o{const t=[];let i=0,s=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=r[0];return L_(e.charAt(a-1))||L_(e.charAt(a+n))?t[s]:o}))}return e}}U_._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class G_{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t){this.isCompiled=!1,this._valueCache={},this._engine=e,this.isAsync=t}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t})),a.push(...l.getAttributes(this,o))}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class z_ extends Ka{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class W_{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function H_(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new Qt(`Unsupported texture format or type: format ${e}, type ${t}.`,Yt.UnsupportedTextureError)}function X_(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${e}.`)}}function Y_(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}function Q_(e){switch(e){case ys.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case ys.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case ys.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case ys.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case ys.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}const j_=new X;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&j_.notifyObservers(e)}})}function K_(){return new Promise((e=>{"undefined"==typeof _native?j_.addOnce((t=>e(t))):e(_native)}))}async function $_(e,t){(await K_())[e]=t}class q_ extends Oi{}class Z_{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=J_._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}class J_ extends gn{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new Z_(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==J_.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${J_.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback((()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()})),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},hs.Log("Babylon Native (v"+gn.Version+") launched"),hs.LoadScript=function(e,t,i,s){hs.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,s){return Array.isArray(s)?i.push.apply(i,e.call(s,t-1)):i.push(s),i}),[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new Mi,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new i_}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=s,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,s=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const s=this._normalizeIndexData(e),r=new q_;return r.references=1,r.is32Bits=4===s.BYTES_PER_ELEMENT,s.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,r.is32Bits,t??!1)),r}createVertexBuffer(e,t,i){const s=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new q_;return r.references=1,s.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,t??!1)),r}_recordVertexArrayObject(e,t,i,s,r){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let i=0;i=0){const s=n[i];let a=null;if(r&&(a=r[s]),a||(a=t[s]),a){const t=a.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.byteOffset,a.byteStride,a.getSize(),Q_(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e;return this._engine.getAttributes(i.program,t)}drawElementsType(e,t,i,s){this._drawCalls.addCount(1,!1),s&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,s){this._drawCalls.addCount(1,!1),s&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){const e=!(!this._caps.parallelShaderCompile||!this._engine.createProgramAsync);return new G_(this,e)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,s,r,n,o,a){s?this.createRawShaderProgram():this.createShaderProgram(e,t,i,a)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(i.isAsync)if(i.onCompiled){const e=i.onCompiled;i.onCompiled=()=>{e(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new U_(t);n.processCode(),t=n.code;const o=new U_(i);o.processCode(),i=o.code,t=ki._ConcatenateShader(t,s),i=ki._ConcatenateShader(i,s);const a=()=>{r.isCompiled=!0,r.onCompiled?.(),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)r.program=this._engine.createProgramAsync(t,i,a,(e=>{r.compilationError=e}));else try{r.program=this._engine.createProgram(t,i),a()}catch(e){const t=e?.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}return r.program}inlineShaderCode(e){const t=new U_(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,s,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,s=!1,r){if(void 0===s&&(s=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),s=e._hardwareTexture.underlyingResource;this._engine.copyTexture(s,i),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new Pi(this,Ai.Raw);if(u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=X_(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,s,r,n,o,a,l=null,h=0){const c=new Pi(this,Ai.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=s,c.width=t,c.height=i,c.depth=s,c.format=r,c.type=h,c.generateMipMaps=n,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,s,H_(r,h),n,o);const u=X_(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const s=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(s,t,e.width,e.height,H_(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p=!1){const f="data:"===(e=e||"").substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new Pi(this,Ai.Url),v=e;!this._transformTextureUrl||m||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():"");let T=null;for(const e of gn._TextureLoaders)if(e.canLoad(b)){T=e;break}s&&s.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=r,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(g._buffer=a);let y=null;n&&!l&&(y=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);const S=(i,l)=>{s&&s.removePendingData(g),e===v?(y&&g.onLoadedObservable.remove(y),se.UseFallbackTexture&&this.createTexture(se.FallbackTexture,t,g.invertY,s,r,null,o,a,g),o&&o((i||"Unknown error")+(se.UseFallbackTexture?" - Fallback texture was used":""),l)):(we.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,s,r,n,o,a,g,h,c,u,d))};if(T)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const n=e=>{if(!g._hardwareTexture)return void(s&&s.removePendingData(g));const n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,(()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;const e=X_(r);this._setTextureSampling(n,e),s&&s.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(f&&a)if(a instanceof ArrayBuffer)n(new Uint8Array(a));else if(ArrayBuffer.isView(a))n(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");n(new Uint8Array(hs.DecodeBase64(a)))}else m?n(new Uint8Array(hs.DecodeBase64(e))):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{S("Unable to load "+(e&&e.responseURL,t))}))}return g}wrapNativeTexture(e,t=!1,i=3){const s=new W_(e,this._engine),r=new Pi(this,Ai.Unknown,!0);return r._hardwareTexture=s,r.baseWidth=this._engine.getTextureWidth(e),r.baseHeight=this._engine.getTextureHeight(e),r.width=r.baseWidth,r.height=r.baseHeight,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const s=t.generateStencil||!1,r=t.samples||1,n=i,o=new Pi(this,Ai.DepthStencil),a=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,a,l,s,!0,r);return n._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise(((t,i)=>{const s=this.createCanvasImage();s.onload=()=>{try{const e=this._engine.createImageBitmap(s);t(e)}catch(e){i(`Error loading image ${s.src} with exception: ${e}`)}},s.onerror=e=>{i(`Error loading image ${s.src} with exception: ${e}`)},s.src=e}))}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,_=!1){const p=u||new Pi(this,Ai.Cube);p.isCube=!0,p.url=e,p.generateMipMaps=!s,p._lodGenerationScale=h,p._lodGenerationOffset=c,p._useSRGBBuffer=this._getUseSRGBBuffer(_,!!s),this._doNotHandleContextLost||(p._extension=a,p._files=i);const f=e.lastIndexOf(".");if(".env"===(a||(f>-1?e.substring(f).toLowerCase():""))){const t=e=>{const t=C_(e);p.width=t.width,p.height=t.width,D_(p,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");p._lodGenerationScale=i.lodGenerationScale;const s=R_(e,t);p.format=5,p.type=0,p.generateMipMaps=!0,p.getEngine().updateTextureSamplingMode(Vo.TRILINEAR_SAMPLINGMODE,p),p._isRGBD=!0,p.invertY=!0,this._engine.loadCubeTextureWithMips(p._hardwareTexture.underlyingResource,s,!1,p._useSRGBBuffer,(()=>{p.isReady=!0,r&&r()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>{t(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>this._loadFileAsync(e,void 0,!0).then((e=>new Uint8Array(e,0,e.byteLength)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(p._hardwareTexture.underlyingResource,e,!s,!0,p._useSRGBBuffer,t,i)})))).then((()=>{p.isReady=!0,r&&r()}),(e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(p),p}_createHardwareTexture(){return new W_(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new z_(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=Ai.Unknown){let r,n=!1,o=0,a=3,l=5,h=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=void 0===t.type?0:t.type,a=void 0===t.samplingMode?3:t.samplingMode,l=void 0===t.format?5:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,r=t.label):n=!!t,h=this._getUseSRGBBuffer(h,!n),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,we.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new Pi(this,s),d=e.width??e,_=e.height??e,p=e.layers||0;if(0!==p)throw new Error("Texture layers are not supported in Babylon Native");const f=u._hardwareTexture.underlyingResource,m=H_(l,o);return this._engine.initializeTexture(f,d,_,n,m,!0,h,c),this._setTextureSampling(f,X_(a)),u._useSRGBBuffer=h,u.baseWidth=d,u.baseHeight=_,u.width=d,u.height=_,u.depth=p,u.isReady=!0,u.samples=c,u.generateMipMaps=n,u.samplingMode=a,u.type=o,u.format=l,u.label=r,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s,r=!0,n=!1,o=!1,a=1;void 0!==t&&"object"==typeof t&&(r=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,o=!!t.noColorAttachment,s=t.colorAttachment,a=t.samples??1);const l=s||(o?null:this._createInternalTexture(e,t,!0,Ai.RenderTarget)),h=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,c,n,r,a);return i._framebuffer=u,i._generateDepthBuffer=r,i._generateStencilBuffer=n,i._samples=a,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return we.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=X_(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const s=e,r=this._normalizeIndexData(t);s.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,s){const r=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,s??n.byteLength);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;return n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,Y_(t.wrapU),Y_(t.wrapV),Y_(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(r,n._hardwareTexture.underlyingResource),0))}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,s,r,n,o,a,l,h){if(void 0!==s&&-1!==s)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture(e._hardwareTexture?.underlyingResource,r??0,l??0,h??0,t,i,n?.buffer??null,n?.byteOffset??0,n?.byteLength??0).then((e=>(n||(n=new Uint8Array(e)),n)))}}J_.PROTOCOL_VERSION=8,J_._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new ep:new i_};class ep extends i_{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var tp,ip,sp,rp,np,op,ap,lp,hp,cp,up,dp,_p,pp,fp,mp,gp,vp,xp,bp,Tp,yp,Sp,Cp,Ep,Ap,Pp,Rp,Ip,Mp,Op,Dp,wp,Np,Fp,Bp,Lp,kp,Vp,Up;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(tp||(tp={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(ip||(ip={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(sp||(sp={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(rp||(rp={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(np||(np={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(op||(op={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(ap||(ap={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(lp||(lp={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(hp||(hp={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(cp||(cp={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(up||(up={})),function(e){e.Nearest="nearest",e.Linear="linear"}(dp||(dp={})),function(e){e.Nearest="nearest",e.Linear="linear"}(_p||(_p={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(pp||(pp={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(fp||(fp={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(mp||(mp={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(gp||(gp={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(vp||(vp={})),function(e){e.WriteOnly="write-only",e.ReadOnly="read-only",e.ReadWrite="read-write"}(xp||(xp={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(bp||(bp={})),function(e){e.Validation="validation",e.Internal="internal"}(Tp||(Tp={})),function(e){e.Auto="auto"}(yp||(yp={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(Sp||(Sp={})),function(e){e.CCW="ccw",e.CW="cw"}(Cp||(Cp={})),function(e){e.None="none",e.Front="front",e.Back="back"}(Ep||(Ep={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(Ap||(Ap={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(Pp||(Pp={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(Rp||(Rp={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Ip||(Ip={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Mp||(Mp={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(Op||(Op={})),function(e){e.Vertex="vertex",e.Instance="instance"}(Dp||(Dp={})),function(e){e.Beginning="beginning",e.End="end"}(wp||(wp={})),function(e){e.Beginning="beginning",e.End="end"}(Np||(Np={})),function(e){e.Load="load",e.Clear="clear"}(Fp||(Fp={})),function(e){e.Store="store",e.Discard="discard"}(Bp||(Bp={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(Lp||(Lp={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(kp||(kp={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(Vp||(Vp={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(Up||(Up={}));class Gp{constructor(){this.shaderLanguage=ui.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let t=0;t=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new bs(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Gp.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,s,r)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,s,r)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,s,r)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const Wp={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Hp{static get KnownUBOs(){return Hp._SimplifiedKnownBindings?Hp._SimplifiedKnownUBOs:Hp._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Hp.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;-1!==s.groupIndex&&(void 0===t[s.groupIndex]?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(Wp[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(Wp[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Hp._SimplifiedKnownBindings=!0,Hp._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},Hp._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class Xp extends Gp{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=ui.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const t=e.substring(r+1,n);s=+t,isNaN(s)&&(s=+i[t.trim()]),e=e.substr(0,r)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\nuniform ${Gp.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,s=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const r=s[1]??"",n=s[2],o=s[3];let a;t?(a=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[a]="",void 0===a&&we.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(a=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=a,this._missingVaryings[a]=`layout(location = ${a}) ${r} in ${n} ${o};`),e=e.replace(s[0],void 0===a?"":`layout(location = ${a}) ${r} ${t?"in":"out"} ${n} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const s=i[1],r=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const t=o<0?-1===o?"int":"ivec"+-o:1===o?"uint":"uvec"+o,a=`_int_${r}_`;e=e.replace(i[0],`layout(location = ${n}) in ${t} ${a}; ${s} ${r} = ${s}(${a});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${s} ${r};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],n=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[n,r,s]=this._getArraySize(n,r,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:vp.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const a=Gp._SamplerTypeByWebGLSamplerType[r]??"sampler",l=!!Gp._IsComparisonSamplerByWebGPUSamplerType[a],h=l?gp.Comparison:gp.Filtering,c=n+Gp.AutoSamplerSuffix;let u=this._webgpuProcessingContext.availableSamplers[c];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const d="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";d&&(r=r.substr(1));const _=l?vp.Depth:"u"===d?vp.Uint:"i"===d?vp.Sint:vp.Float;o.sampleType=_;const p=s>0,f=u.binding.groupIndex,m=u.binding.bindingIndex,g=Gp._SamplerFunctionByWebGLSamplerType[r],v=Gp._TextureTypeByWebGLSamplerType[r],x=Gp._GpuTextureViewDimensionByWebGPUTextureType[v];if(p){const t=[];t.push(`layout(set = ${f}, binding = ${m}) uniform ${d}${a} ${c};`),e="\n";for(let i=0;i0?"\n":""}#define ${n}${i} ${d}${g}(${n}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else s=1,e=`layout(set = ${f}, binding = ${m}) uniform ${a} ${c};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${d}${v} ${n}Texture;\n #define ${n} ${d}${g}(${n}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[c]=u,this._addSamplerBindingDescription(c,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",s=t?"vec4 glFragCoord_;\n":"",r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",s),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",r.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;null!==s;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}bi.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n";bi.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";bi.IncludesShadersStoreWGSL.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";bi.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";bi.IncludesShadersStoreWGSL.clipPlaneVertex="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";bi.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";bi.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n";bi.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i<$NUM_MORPH_INFLUENCERS$; i=i+1) {if (i>=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n";const Yp={texture_1d:lp.E1d,texture_2d:lp.E2d,texture_2d_array:lp.E2dArray,texture_3d:lp.E3d,texture_cube:lp.Cube,texture_cube_array:lp.CubeArray,texture_multisampled_2d:lp.E2d,texture_depth_2d:lp.E2d,texture_depth_2d_array:lp.E2dArray,texture_depth_cube:lp.Cube,texture_depth_cube_array:lp.CubeArray,texture_depth_multisampled_2d:lp.E2d,texture_storage_1d:lp.E1d,texture_storage_2d:lp.E2d,texture_storage_2d_array:lp.E2dArray,texture_storage_3d:lp.E3d,texture_external:null};class Qp extends Gp{constructor(){super(...arguments),this.shaderLanguage=ui.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let e=r;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const n=t.substring(e+1,r);for(s=+n,isNaN(s)&&(s=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${Gp.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${Gp.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+k_(e)}varyingCheck(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const s=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==s){const r=s[1]??"perspective",n=s[2]??"center",o=s[4],a=s[3],l="flat"===r?`@interpolate(${r})`:`@interpolate(${r}, ${n})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[a],void 0===h&&we.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=h,this._varyingsWGSL.push(` @location(${h}) ${l} ${a} : ${o},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const s=i[2],r=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const e=o<0?-1===o?"i32":"vec"+-o+"":1===o?"u32":"vec"+o+"",t=`_int_${r}_`;this._attributesInputWGSL.push(`@location(${n}) ${t} : ${e},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = ${s}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${r} : ${s},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = vertexInputs_.${r};`);e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(null!==s){const t=s[2],r=s[1];this._addUniformToLeftOverUBO(r,t,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(null!==s){const r=s[1],n=s[2],o=!!s[3],a=s[4],l=a.indexOf("storage")>0,h=s[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(r,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[r];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:vp.Float},u=u||1;for(let e=0;e0,p=Yp[a],f=_?vp.Depth:"u32"===h?vp.Uint:"i32"===h?vp.Sint:vp.Float;if(d.sampleType=f,void 0===p)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i2?t[2]:""}return e.replace(/\$(\w+)\$/g,((e,t)=>i[t]??t))}finalizeShaders(e,t){const i=t.indexOf("fragmentInputs.position")>=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const s=this._buildLeftOverUBO();t=s+t,e=(e=s+e).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(r+=this._attributesInputWGSL.join("\n")),r+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(r+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",r+=this._attributesWGSL.join("\n"),r+="\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=r+n+e;let o=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n"),e=this._injectStartingAndEndingCode(e,"fn main",o," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let a="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(a+=this._varyingsWGSL.join("\n")),a+="\n};\nvar fragmentInputs : FragmentInputs;\n";let l="struct FragmentOutputs {\n @location(0) color : vec4,\n",h=!1,c=0;for(;!(h||(c=t.indexOf("fragmentOutputs.fragDepth",c),c<0));){const e=c;for(h=!0;c>1&&"\n"!==t.charAt(c);){if("/"===t.charAt(c)&&"/"===t.charAt(c-1)){h=!1;break}c--}c=e+25}h&&(l+=" @builtin(frag_depth) fragDepth: f32,\n"),l+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=a+l+t;const u=" fragmentInputs = input;\n "+i;return t=this._injectStartingAndEndingCode(t,"fn main",u," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const r=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=Gp.UniformSizes[r];if(t.length>0)if(n<=2){const n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} {\n @size(16)\n el: ${r},\n }`,this._stridedUniformArrays.push(t.name),s+=` @align(16) ${t.name} : array<${n}, ${t.length}>,\n`}else s+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else s+=` ${t.name} : ${t.type},\n`}return s+="};\n",s=`${i}\n${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[2],o=r.indexOf(Gp.AutoSamplerSuffix)===r.length-Gp.AutoSamplerSuffix.length?r.substring(0,r.indexOf(Gp.AutoSamplerSuffix)):null,a="sampler_comparison"===n?gp.Comparison:gp.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[r];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[r]=l),this._addSamplerBindingDescription(r,l,t);const h=e.substring(0,s.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(s.index);e=h+c+u,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[3];let o=s[4];const a=s[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===r?Hp.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[o]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===n?mp.Storage:"storage"===r?mp.ReadOnlyStorage:mp.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,s.index),d=`@group(${h}) @binding(${c}) `,_=e.substring(s.index);e=u+d+_,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class jp{static ComputeNumMipmapLevels(e,t){return xe.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case cp.R8Unorm:case cp.R8Snorm:case cp.R8Uint:case cp.R8Sint:case cp.RG8Unorm:case cp.RG8Snorm:case cp.RG8Uint:case cp.RG8Sint:case cp.RGBA8Unorm:case cp.RGBA8UnormSRGB:case cp.RGBA8Snorm:case cp.RGBA8Uint:case cp.RGBA8Sint:case cp.BGRA8Unorm:case cp.BGRA8UnormSRGB:case cp.RGB10A2UINT:case cp.RGB10A2Unorm:case cp.RGB9E5UFloat:case cp.RG11B10UFloat:case cp.BC7RGBAUnorm:case cp.BC7RGBAUnormSRGB:case cp.BC6HRGBUFloat:case cp.BC6HRGBFloat:case cp.BC5RGUnorm:case cp.BC5RGSnorm:case cp.BC3RGBAUnorm:case cp.BC3RGBAUnormSRGB:case cp.BC2RGBAUnorm:case cp.BC2RGBAUnormSRGB:case cp.BC4RUnorm:case cp.BC4RSnorm:case cp.BC1RGBAUnorm:case cp.BC1RGBAUnormSRGB:case cp.ETC2RGB8Unorm:case cp.ETC2RGB8UnormSRGB:case cp.ETC2RGB8A1Unorm:case cp.ETC2RGB8A1UnormSRGB:case cp.ETC2RGBA8Unorm:case cp.ETC2RGBA8UnormSRGB:case cp.EACR11Unorm:case cp.EACR11Snorm:case cp.EACRG11Unorm:case cp.EACRG11Snorm:case cp.ASTC4x4Unorm:case cp.ASTC4x4UnormSRGB:case cp.ASTC5x4Unorm:case cp.ASTC5x4UnormSRGB:case cp.ASTC5x5Unorm:case cp.ASTC5x5UnormSRGB:case cp.ASTC6x5Unorm:case cp.ASTC6x5UnormSRGB:case cp.ASTC6x6Unorm:case cp.ASTC6x6UnormSRGB:case cp.ASTC8x5Unorm:case cp.ASTC8x5UnormSRGB:case cp.ASTC8x6Unorm:case cp.ASTC8x6UnormSRGB:case cp.ASTC8x8Unorm:case cp.ASTC8x8UnormSRGB:case cp.ASTC10x5Unorm:case cp.ASTC10x5UnormSRGB:case cp.ASTC10x6Unorm:case cp.ASTC10x6UnormSRGB:case cp.ASTC10x8Unorm:case cp.ASTC10x8UnormSRGB:case cp.ASTC10x10Unorm:case cp.ASTC10x10UnormSRGB:case cp.ASTC12x10Unorm:case cp.ASTC12x10UnormSRGB:case cp.ASTC12x12Unorm:case cp.ASTC12x12UnormSRGB:case cp.Stencil8:return 0;case cp.R16Uint:case cp.R16Sint:case cp.RG16Uint:case cp.RG16Sint:case cp.RGBA16Uint:case cp.RGBA16Sint:case cp.Depth16Unorm:return 5;case cp.R16Float:case cp.RG16Float:case cp.RGBA16Float:return 2;case cp.R32Uint:case cp.R32Sint:case cp.RG32Uint:case cp.RG32Sint:case cp.RGBA32Uint:case cp.RGBA32Sint:return 7;case cp.R32Float:case cp.RG32Float:case cp.RGBA32Float:case cp.Depth32Float:case cp.Depth32FloatStencil8:case cp.Depth24Plus:case cp.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case cp.R8Unorm:case cp.R8Snorm:case cp.R8Uint:case cp.R8Sint:return{width:1,height:1,length:1};case cp.R16Uint:case cp.R16Sint:case cp.R16Float:case cp.RG8Unorm:case cp.RG8Snorm:case cp.RG8Uint:case cp.RG8Sint:return{width:1,height:1,length:2};case cp.R32Uint:case cp.R32Sint:case cp.R32Float:case cp.RG16Uint:case cp.RG16Sint:case cp.RG16Float:case cp.RGBA8Unorm:case cp.RGBA8UnormSRGB:case cp.RGBA8Snorm:case cp.RGBA8Uint:case cp.RGBA8Sint:case cp.BGRA8Unorm:case cp.BGRA8UnormSRGB:case cp.RGB9E5UFloat:case cp.RGB10A2UINT:case cp.RGB10A2Unorm:case cp.RG11B10UFloat:return{width:1,height:1,length:4};case cp.RG32Uint:case cp.RG32Sint:case cp.RG32Float:case cp.RGBA16Uint:case cp.RGBA16Sint:case cp.RGBA16Float:return{width:1,height:1,length:8};case cp.RGBA32Uint:case cp.RGBA32Sint:case cp.RGBA32Float:return{width:1,height:1,length:16};case cp.Stencil8:throw"No fixed size for Stencil8 format!";case cp.Depth16Unorm:return{width:1,height:1,length:2};case cp.Depth24Plus:throw"No fixed size for Depth24Plus format!";case cp.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case cp.Depth32Float:return{width:1,height:1,length:4};case cp.Depth32FloatStencil8:return{width:1,height:1,length:5};case cp.BC7RGBAUnorm:case cp.BC7RGBAUnormSRGB:case cp.BC6HRGBUFloat:case cp.BC6HRGBFloat:case cp.BC5RGUnorm:case cp.BC5RGSnorm:case cp.BC3RGBAUnorm:case cp.BC3RGBAUnormSRGB:case cp.BC2RGBAUnorm:case cp.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case cp.BC4RUnorm:case cp.BC4RSnorm:case cp.BC1RGBAUnorm:case cp.BC1RGBAUnormSRGB:case cp.ETC2RGB8Unorm:case cp.ETC2RGB8UnormSRGB:case cp.ETC2RGB8A1Unorm:case cp.ETC2RGB8A1UnormSRGB:case cp.EACR11Unorm:case cp.EACR11Snorm:return{width:4,height:4,length:8};case cp.ETC2RGBA8Unorm:case cp.ETC2RGBA8UnormSRGB:case cp.EACRG11Unorm:case cp.EACRG11Snorm:case cp.ASTC4x4Unorm:case cp.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case cp.ASTC5x4Unorm:case cp.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case cp.ASTC5x5Unorm:case cp.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case cp.ASTC6x5Unorm:case cp.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case cp.ASTC6x6Unorm:case cp.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case cp.ASTC8x5Unorm:case cp.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case cp.ASTC8x6Unorm:case cp.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case cp.ASTC8x8Unorm:case cp.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case cp.ASTC10x5Unorm:case cp.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case cp.ASTC10x6Unorm:case cp.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case cp.ASTC10x8Unorm:case cp.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case cp.ASTC10x10Unorm:case cp.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case cp.ASTC12x10Unorm:case cp.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case cp.ASTC12x12Unorm:case cp.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case cp.BC7RGBAUnormSRGB:case cp.BC7RGBAUnorm:case cp.BC6HRGBFloat:case cp.BC6HRGBUFloat:case cp.BC5RGSnorm:case cp.BC5RGUnorm:case cp.BC4RSnorm:case cp.BC4RUnorm:case cp.BC3RGBAUnormSRGB:case cp.BC3RGBAUnorm:case cp.BC2RGBAUnormSRGB:case cp.BC2RGBAUnorm:case cp.BC1RGBAUnormSRGB:case cp.BC1RGBAUnorm:case cp.ETC2RGB8Unorm:case cp.ETC2RGB8UnormSRGB:case cp.ETC2RGB8A1Unorm:case cp.ETC2RGB8A1UnormSRGB:case cp.ETC2RGBA8Unorm:case cp.ETC2RGBA8UnormSRGB:case cp.EACR11Unorm:case cp.EACR11Snorm:case cp.EACRG11Unorm:case cp.EACRG11Snorm:case cp.ASTC4x4Unorm:case cp.ASTC4x4UnormSRGB:case cp.ASTC5x4Unorm:case cp.ASTC5x4UnormSRGB:case cp.ASTC5x5Unorm:case cp.ASTC5x5UnormSRGB:case cp.ASTC6x5Unorm:case cp.ASTC6x5UnormSRGB:case cp.ASTC6x6Unorm:case cp.ASTC6x6UnormSRGB:case cp.ASTC8x5Unorm:case cp.ASTC8x5UnormSRGB:case cp.ASTC8x6Unorm:case cp.ASTC8x6UnormSRGB:case cp.ASTC8x8Unorm:case cp.ASTC8x8UnormSRGB:case cp.ASTC10x5Unorm:case cp.ASTC10x5UnormSRGB:case cp.ASTC10x6Unorm:case cp.ASTC10x6UnormSRGB:case cp.ASTC10x8Unorm:case cp.ASTC10x8UnormSRGB:case cp.ASTC10x10Unorm:case cp.ASTC10x10UnormSRGB:case cp.ASTC12x10Unorm:case cp.ASTC12x10UnormSRGB:case cp.ASTC12x12Unorm:case cp.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return cp.Depth16Unorm;case 16:return cp.Depth24Plus;case 13:return cp.Depth24PlusStencil8;case 14:return cp.Depth32Float;case 18:return cp.Depth32FloatStencil8;case 19:return cp.Stencil8;case 36492:return i?cp.BC7RGBAUnormSRGB:cp.BC7RGBAUnorm;case 36495:return cp.BC6HRGBUFloat;case 36494:return cp.BC6HRGBFloat;case 33779:return i?cp.BC3RGBAUnormSRGB:cp.BC3RGBAUnorm;case 33778:return i?cp.BC2RGBAUnormSRGB:cp.BC2RGBAUnorm;case 33777:case 33776:return i?cp.BC1RGBAUnormSRGB:cp.BC1RGBAUnorm;case 37808:return i?cp.ASTC4x4UnormSRGB:cp.ASTC4x4Unorm;case 36196:case 37492:return i?cp.ETC2RGB8UnormSRGB:cp.ETC2RGB8Unorm;case 37496:return i?cp.ETC2RGBA8UnormSRGB:cp.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return cp.R8Snorm;case 7:return cp.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return cp.R8Sint;case 9:return cp.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return cp.RGBA8Sint;default:return cp.RGBA8Snorm}case 0:switch(t){case 6:return cp.R8Unorm;case 7:return cp.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?cp.RGBA8UnormSRGB:cp.RGBA8Unorm;case 12:return i?cp.BGRA8UnormSRGB:cp.BGRA8Unorm;case 8:return cp.R8Uint;case 9:return cp.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return cp.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return cp.RGBA8Unorm}case 4:switch(t){case 8:return cp.R16Sint;case 9:return cp.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cp.RGBA16Sint}case 5:switch(t){case 8:return cp.R16Uint;case 9:return cp.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cp.RGBA16Uint}case 6:switch(t){case 8:return cp.R32Sint;case 9:return cp.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cp.RGBA32Sint}case 7:switch(t){case 8:return cp.R32Uint;case 9:return cp.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cp.RGBA32Uint}case 1:switch(t){case 6:return cp.R32Float;case 7:return cp.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return cp.RGBA32Float}case 2:switch(t){case 6:return cp.R16Float;case 7:return cp.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return cp.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return cp.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return cp.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return cp.RGB10A2Unorm;case 11:return cp.RGB10A2UINT}}return i?cp.RGBA8UnormSRGB:cp.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case cp.R8Unorm:case cp.R8Snorm:case cp.R8Uint:case cp.R8Sint:case cp.BC4RUnorm:case cp.BC4RSnorm:case cp.R16Uint:case cp.R16Sint:case cp.Depth16Unorm:case cp.R16Float:case cp.R32Uint:case cp.R32Sint:case cp.R32Float:case cp.Depth32Float:case cp.Stencil8:case cp.Depth24Plus:case cp.EACR11Unorm:case cp.EACR11Snorm:return 1;case cp.RG8Unorm:case cp.RG8Snorm:case cp.RG8Uint:case cp.RG8Sint:case cp.Depth32FloatStencil8:case cp.BC5RGUnorm:case cp.BC5RGSnorm:case cp.RG16Uint:case cp.RG16Sint:case cp.RG16Float:case cp.RG32Uint:case cp.RG32Sint:case cp.RG32Float:case cp.Depth24PlusStencil8:case cp.EACRG11Unorm:case cp.EACRG11Snorm:return 2;case cp.RGB9E5UFloat:case cp.RG11B10UFloat:case cp.BC6HRGBUFloat:case cp.BC6HRGBFloat:case cp.ETC2RGB8Unorm:case cp.ETC2RGB8UnormSRGB:return 3;case cp.RGBA8Unorm:case cp.RGBA8UnormSRGB:case cp.RGBA8Snorm:case cp.RGBA8Uint:case cp.RGBA8Sint:case cp.BGRA8Unorm:case cp.BGRA8UnormSRGB:case cp.RGB10A2UINT:case cp.RGB10A2Unorm:case cp.BC7RGBAUnorm:case cp.BC7RGBAUnormSRGB:case cp.BC3RGBAUnorm:case cp.BC3RGBAUnormSRGB:case cp.BC2RGBAUnorm:case cp.BC2RGBAUnormSRGB:case cp.BC1RGBAUnorm:case cp.BC1RGBAUnormSRGB:case cp.RGBA16Uint:case cp.RGBA16Sint:case cp.RGBA16Float:case cp.RGBA32Uint:case cp.RGBA32Sint:case cp.RGBA32Float:case cp.ETC2RGB8A1Unorm:case cp.ETC2RGB8A1UnormSRGB:case cp.ETC2RGBA8Unorm:case cp.ETC2RGBA8UnormSRGB:case cp.ASTC4x4Unorm:case cp.ASTC4x4UnormSRGB:case cp.ASTC5x4Unorm:case cp.ASTC5x4UnormSRGB:case cp.ASTC5x5Unorm:case cp.ASTC5x5UnormSRGB:case cp.ASTC6x5Unorm:case cp.ASTC6x5UnormSRGB:case cp.ASTC6x6Unorm:case cp.ASTC6x6UnormSRGB:case cp.ASTC8x5Unorm:case cp.ASTC8x5UnormSRGB:case cp.ASTC8x6Unorm:case cp.ASTC8x6UnormSRGB:case cp.ASTC8x8Unorm:case cp.ASTC8x8UnormSRGB:case cp.ASTC10x5Unorm:case cp.ASTC10x5UnormSRGB:case cp.ASTC10x6Unorm:case cp.ASTC10x6UnormSRGB:case cp.ASTC10x8Unorm:case cp.ASTC10x8UnormSRGB:case cp.ASTC10x10Unorm:case cp.ASTC10x10UnormSRGB:case cp.ASTC12x10Unorm:case cp.ASTC12x10UnormSRGB:case cp.ASTC12x12Unorm:case cp.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case cp.Stencil8:case cp.Depth32FloatStencil8:case cp.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case cp.Depth32FloatStencil8:case cp.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case cp.Depth16Unorm:return cp.Depth16Unorm;case cp.Depth24Plus:case cp.Depth24PlusStencil8:return cp.Depth24Plus;case cp.Depth32Float:case cp.Depth32FloatStencil8:return cp.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class Kp{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){return this._webgpuMSAATexture?.[e]??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=cp.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,r,n,o,a){let l=lp.E2d,h=1;s?(l=i?lp.CubeArray:lp.Cube,h=6*(a||1)):r?(l=lp.E3d,h=1):i&&(l=lp.E2dArray,h=a);const c=jp.GetDepthFormatOnly(this.format),u=jp.HasDepthAndStencilAspects(this.format)?hp.DepthOnly:hp.All;this.createView({label:`TextureView${r?"3D":s?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:c,dimension:l,mipLevelCount:t?xe.ILog2(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:u})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATexture(),this._copyInvertYTempTexture?.destroy(),this.reset()}}const $p="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",qp=$p;var Zp,Jp;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Zp||(Zp={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(Jp||(Jp={}));const ef=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:$p,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:qp,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],tf={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class sf{constructor(e,t,i,s,r,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=r,-1!==n.indexOf(ip.RG11B10UFloatRenderable)){const e=Object.keys(tf);tf[cp.RG11B10UFloat]=tf[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:dp.Linear}),this._videoSampler=t.createSampler({minFilter:dp.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,rp.Uniform|rp.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(cp.RGBA8Unorm),this._getVideoPipeline(cp.RGBA8Unorm)}_getPipeline(e,t=Zp.MipMap,i){const s=t===Zp.MipMap?1:t===Zp.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Zp.Clear?8:t===Zp.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n="#version 450\n";t!==Zp.InvertYPremultiplyAlpha&&t!==Zp.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[s];if(!o){let e=this._glslang.compileGLSL(n+ef[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+ef[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const r=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[s]=[r,a]}const a=this._device.createRenderPipeline({layout:yp.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Sp.TriangleStrip,stripIndexFormat:Mp.Uint16}});r=this._pipelines[e][s]=[a,a.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=Jp.DontInvertY){const i=t===Jp.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),s=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,s]}const r=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:yp.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Sp.TriangleStrip,stripIndexFormat:Mp.Uint16}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,r){const n=void 0===r,[o,a]=this._getVideoPipeline(i,s?Jp.InvertY:Jp.DontInvertY);n&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.(`copy video to texture - invertY=${s}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:lp.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:hp.All}),loadOp:Fp.Load,storeOp:Bp.Store}]},c=r.beginRenderPass(h),u={layout:a,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(u);c.setPipeline(o),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),r.popDebugGroup?.(),n&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,_,p){const f=0!==u,m=void 0===_,[g,v]=this._getPipeline(s,f?Zp.InvertYPremultiplyAlphaWithOfst:Zp.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});let x;if(o=Math.max(o,0),m&&(_=this._device.createCommandEncoder({})),_.pushDebugGroup?.(`internal process texture - invertY=${r} premultiplyAlpha=${n}`),jp.IsHardwareTexture(e)?(x=e.underlyingResource,r&&!n&&1===l&&0===o||(e=void 0)):(x=e,e=void 0),!x)return;f&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const b=e,T=b?._copyInvertYTempTexture??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,_,ap.CopySrc|ap.RenderAttachment|ap.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),y=b?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${r?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:T.createView({format:s,dimension:lp.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Fp.Load,storeOp:Bp.Store}]},S=_.beginRenderPass(y);let C=f?b?._copyInvertYBindGroupWithOfst:b?._copyInvertYBindGroup;if(!C){const e={layout:v,entries:[{binding:0,resource:x.createView({format:s,dimension:lp.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};f&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),C=this._device.createBindGroup(e)}S.setPipeline(g),S.setBindGroup(0,C),S.draw(4,1,0,0),S.end(),_.copyTextureToTexture({texture:T},{texture:x,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),b?(b._copyInvertYTempTexture=T,b._copyInvertYRenderPassDescr=y,f?b._copyInvertYBindGroupWithOfst=C:b._copyInvertYBindGroup=C):this._deferredReleaseTextures.push([T,null]),_.popDebugGroup?.(),m&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,s){const r=void 0===s,[n,o]=this._getPipeline(t,Zp.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.("internal copy texture with invertY");const a=s.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});a.setPipeline(n),a.setBindGroup(0,l),a.draw(4,1,0,0),a.end(),s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=cp.RGBA8Unorm,a=1,l,h=-1,c=0,u){a=jp.GetSample(a);const d=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:d},p=tf[o]?ap.RenderAttachment:0,f=jp.IsCompressedFormat(o),m=t?jp.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:ap.CopySrc|ap.CopyDst|ap.TextureBinding;c|=t&&!f?ap.CopySrc|p:0,f||n||(c|=p|ap.CopyDst);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${u?u+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:_,dimension:n?op.E3d:op.E2d,format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return jp.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(v,o,m,0,n,l)),v}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=cp.RGBA8Unorm,o=1,a,l=-1,h=0,c){o=jp.GetSample(o);const u=jp.IsImageBitmapArray(e)?e[0].width:e.width,d=jp.IsImageBitmapArray(e)?e[0].height:e.height,_=tf[n]?ap.RenderAttachment:0,p=jp.IsCompressedFormat(n),f=t?jp.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:ap.CopySrc|ap.CopyDst|ap.TextureBinding;h|=t&&!p?ap.CopySrc|_:0,p||(h|=_|ap.CopyDst);const g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:op.E2d,format:n,usage:m|h,sampleCount:o,mipLevelCount:f});return jp.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,a)),g}generateCubeMipmaps(e,t,i,s){const r=void 0===s;r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.(`create cube mipmaps - ${i} levels`);for(let r=0;r<6;++r)this.generateMipmaps(e,t,i,r,!1,s);s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r=!1,n){const o=void 0===n,[a,l]=this._getPipeline(t);let h;if(s=Math.max(s,0),o&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup?.(`create mipmaps for face #${s} - ${i} levels`),jp.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let e=1;eh;)this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,r-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=p_(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0,d=this._engine.uniqueId;return new Promise(((i,_)=>{e.mapAsync(np.Read,a,t).then((()=>{const d=e.getMappedRange(a,t);let _=l;if(c)_=null===_?mn(o,t,!0,d):mn(o,_.buffer,void 0,d);else if(null===_)switch(u){case 0:_=new Uint8Array(t),_.set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:_=new Float32Array(t/4),_.set(new Float32Array(d))}else switch(u){case 0:_=new Uint8Array(_.buffer),_.set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:_=new Float32Array(_.buffer),_.set(new Float32Array(d))}if(r!==n){1!==u||c||(r*=2,n*=2);const e=new Uint8Array(_.buffer);let t=r,i=0;for(let o=1;o{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):_(e)}))}))}releaseBuffer(e){return nf._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return of[e.samplingMode]+af[(e._comparisonFunction||514)-512+1]+lf[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=dp.Linear,s=dp.Linear,r=dp.Nearest,a||(n=o=0);break;case 3:case 3:i=dp.Linear,s=dp.Linear,a?r=dp.Linear:(r=dp.Nearest,n=o=0);break;case 8:i=dp.Nearest,s=dp.Nearest,a?r=dp.Linear:(r=dp.Nearest,n=o=0);break;case 4:i=dp.Nearest,s=dp.Nearest,r=dp.Nearest,a||(n=o=0);break;case 5:i=dp.Nearest,s=dp.Linear,r=dp.Nearest,a||(n=o=0);break;case 6:i=dp.Nearest,s=dp.Linear,a?r=dp.Linear:(r=dp.Nearest,n=o=0);break;case 7:i=dp.Nearest,s=dp.Linear,r=dp.Nearest,n=o=0;break;case 1:case 1:default:i=dp.Nearest,s=dp.Nearest,r=dp.Nearest,n=o=0;break;case 9:i=dp.Linear,s=dp.Nearest,r=dp.Nearest,a||(n=o=0);break;case 10:i=dp.Linear,s=dp.Nearest,a?r=dp.Linear:(r=dp.Nearest,n=o=0);break;case 2:case 2:i=dp.Linear,s=dp.Linear,r=dp.Nearest,n=o=0;break;case 12:i=dp.Linear,s=dp.Nearest,r=dp.Nearest,n=o=0}return t>1&&(0!==n||0!==o)&&r!==dp.Nearest?{magFilter:dp.Linear,minFilter:dp.Linear,mipmapFilter:dp.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return up.Repeat;case 0:return up.ClampToEdge;case 2:return up.MirrorRepeat}return up.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?hf.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return pp.Always;case 514:return pp.Equal;case 516:return pp.Greater;case 518:return pp.GreaterEqual;case 513:default:return pp.Less;case 515:return pp.LessEqual;case 512:return pp.Never;case 517:return pp.NotEqual}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(hf._GetSamplerDescriptor(e,s));t?i=0:0===i&&(i=hf.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(hf._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var cf;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(cf||(cf={}));const uf={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},df={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},_f={[ys.PositionKind]:!0,[ys.NormalKind]:!0,[ys.TangentKind]:!0,[ys.UVKind]:!0,[ys.UV2Kind]:!0,[ys.UV3Kind]:!0,[ys.UV4Kind]:!0,[ys.UV5Kind]:!0,[ys.UV6Kind]:!0,[ys.ColorKind]:!0,[ys.ColorInstanceKind]:!0,[ys.MatricesIndicesKind]:!0,[ys.MatricesWeightsKind]:!0,[ys.MatricesIndicesExtraKind]:!0,[ys.MatricesWeightsExtraKind]:!0};class pf{static _IsSignedType(e){switch(e){case ys.BYTE:case ys.SHORT:case ys.INT:case ys.FLOAT:return!0;case ys.UNSIGNED_BYTE:case ys.UNSIGNED_SHORT:case ys.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[cp.BGRA8Unorm],this.setColorFormat(cp.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(cp.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,s=0){if(i=jp.GetSample(i),this.disabled){const r=pf._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,r,i),pf.NumCacheMiss++,pf._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,pf.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return pf.NumCacheHitWithHash++,this._parameter.pipeline;const r=pf._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),pf.NumCacheMiss++,pf._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){pf.NumPipelineCreationLastFrame=pf._NumPipelineCreationCurrentFrame,pf._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,s,r,n,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(a??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[cf.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[cf.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=tf[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let s=0,r=0,n=0;for(let o=0;o=32&&(r=0,s++)}this._mrtFormats.length=n,this._mrtAttachments1===i[0]&&this._mrtAttachments2===i[1]||(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[cf.MRTAttachments1]=i[0],this._states[cf.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:tf[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:df[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:df[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:df[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[cf.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[cf.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=null===i?1:df[i],this._stencilFrontPassOp=null===s?2:df[s],this._stencilFrontFailOp=null===r?1:df[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return Sp.TriangleList;case 2:case 3:return Sp.PointList;case 1:case 4:return Sp.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Sp.LineStrip;case 7:return Sp.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return Rp.Add;case 32778:return Rp.Subtract;case 32779:return Rp.ReverseSubtract;case 32775:return Rp.Min;case 32776:return Rp.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return Pp.Zero;case 1:default:return Pp.One;case 768:return Pp.Src;case 769:return Pp.OneMinusSrc;case 770:return Pp.SrcAlpha;case 771:return Pp.OneMinusSrcAlpha;case 772:return Pp.DstAlpha;case 773:return Pp.OneMinusDstAlpha;case 774:return Pp.Dst;case 775:return Pp.OneMinusDst;case 776:return Pp.SrcAlphaSaturated;case 32769:case 32771:return Pp.Constant;case 32770:case 32772:return Pp.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return pp.Never;case 1:return pp.Less;case 2:return pp.Equal;case 3:return pp.LessEqual;case 4:return pp.Greater;case 5:return pp.NotEqual;case 6:return pp.GreaterEqual;case 7:return pp.Always}return pp.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Ip.Zero;case 1:return Ip.Keep;case 2:return Ip.Replace;case 3:return Ip.IncrementClamp;case 4:return Ip.DecrementClamp;case 5:return Ip.Invert;case 6:return Ip.IncrementWrap;case 7:return Ip.DecrementWrap}return Ip.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case ys.BYTE:switch(s){case 1:case 2:return i?Op.Snorm8x2:Op.Sint8x2;case 3:case 4:return i?Op.Snorm8x4:Op.Sint8x4}break;case ys.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?Op.Unorm8x2:Op.Uint8x2;case 3:case 4:return i?Op.Unorm8x4:Op.Uint8x4}break;case ys.SHORT:switch(s){case 1:case 2:return i?Op.Snorm16x2:Op.Sint16x2;case 3:case 4:return i?Op.Snorm16x4:Op.Sint16x4}break;case ys.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?Op.Unorm16x2:Op.Uint16x2;case 3:case 4:return i?Op.Unorm16x4:Op.Uint16x4}break;case ys.INT:switch(s){case 1:return Op.Sint32;case 2:return Op.Sint32x2;case 3:return Op.Sint32x3;case 4:return Op.Sint32x4}break;case ys.UNSIGNED_INT:switch(s){case 1:return Op.Uint32;case 2:return Op.Uint32x2;case 3:return Op.Uint32x3;case 4:return Op.Uint32x4}break;case ys.FLOAT:switch(s){case 1:return Op.Float32;case 2:return Op.Float32x2;case 3:return Op.Float32x3;case 4:return Op.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:pf._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:pf._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:pf._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:pf._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:pf._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:pf._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[cf.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[cf.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:uf[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:uf[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:uf[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:uf[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[cf.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[cf.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let i=cf.VertexState;const s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,n=s.shaderProcessingContext.attributeLocationsFromEffect;let o,a=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class bf{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=bf._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?hf.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){let i=this.textures[e],s=-1;i?s=i.texture?.uniqueId??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,i.isExternalTexture=xf.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const r=s!==(t?.uniqueId??-1);r&&this.updateId++,this.isDirty||(this.isDirty=r)}}bf._Counter=0;class Tf{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,rp.CopyDst|rp.Indirect|rp.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=Tf._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){this._isDirty||(this._isDirty=t?.uniqueId!==this.buffers[e]?.uniqueId),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}Tf._Counter=0;class yf{constructor(){this.values={}}}class Sf{static get Statistics(){return{totalCreated:Sf.NumBindGroupsCreatedTotal,lastFrameCreated:Sf.NumBindGroupsCreatedLastFrame,lookupLastFrame:Sf.NumBindGroupsLookupLastFrame,noLookupLastFrame:Sf.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Sf._Cache=new yf,Sf.NumBindGroupsCreatedTotal=0,Sf.NumBindGroupsCreatedLastFrame=0,Sf.NumBindGroupsLookupLastFrame=0,Sf.NumBindGroupsNoLookupLastFrame=0,Sf._NumBindGroupsCreatedCurrentFrame=0,Sf._NumBindGroupsLookupCurrentFrame=0,Sf._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Sf.NumBindGroupsCreatedLastFrame=Sf._NumBindGroupsCreatedCurrentFrame,Sf.NumBindGroupsLookupLastFrame=Sf._NumBindGroupsLookupCurrentFrame,Sf.NumBindGroupsNoLookupLastFrame=Sf._NumBindGroupsNoLookupCurrentFrame,Sf._NumBindGroupsCreatedCurrentFrame=0,Sf._NumBindGroupsLookupCurrentFrame=0,Sf._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){let s,r=Sf._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return Sf._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=t.buffers[i]?.uniqueId??0;let s=r.values[e];s||(s=new yf,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.samplerNames){const e=i.samplers[t]?.hashCode??0;let s=r.values[e];s||(s=new yf,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.textureNames){const e=i.textures[t]?.texture?.uniqueId??0;let s=r.values[e];s||(s=new yf,r.values[e]=s),r=s}s=r.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,Sf._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,n||(r.bindGroups=s),Sf.NumBindGroupsCreatedTotal++,Sf._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else we.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){we.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){we.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=n.storageTexture?t.viewForWriting:t.view}else we.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){we.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){we.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._device.importExternalTexture({source:t})}else we.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;a[s].resource.buffer=t,a[s].resource.size=e.capacity}else we.Error(`Can't find buffer "${l}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const l=o[r];s[r]=this._device.createBindGroup({layout:l,entries:a})}return s}}Sf.NumBindGroupsCreatedTotal=0,Sf.NumBindGroupsCreatedLastFrame=0,Sf.NumBindGroupsLookupLastFrame=0,Sf.NumBindGroupsNoLookupLastFrame=0,Sf._Cache=new yf,Sf._NumBindGroupsCreatedCurrentFrame=0,Sf._NumBindGroupsLookupCurrentFrame=0,Sf._NumBindGroupsNoLookupCurrentFrame=0;bi.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";bi.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";class Cf{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new mf(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,ui.WGSL)}clear(e,t,i,s,r=1){let n,o,a=null;const l=!!this._engine._currentRenderTarget;if(e)n=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+h*2**37,o=this._keyTemp.join("_"),a=this._bundleCache[o],a)return a;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:jp.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&jp.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),c=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),c.uniformBuffer.update();const u=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=c.uniformBuffer.getBuffer(),_=d.uniqueId+"-"+u.uniqueId;let p=this._bindGroups[_];if(!p){const e=c.bindGroupLayouts[0];p=this._bindGroups[_]=[],p.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${_}`,layout:e[0],entries:[]})),Hp._SimplifiedKnownBindings||p.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${_}`,layout:e[1],entries:[]})),p.push(this._device.createBindGroup({label:`clearQuadBindGroup${Hp._SimplifiedKnownBindings?1:2}-${_}`,layout:e[Hp._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:u.underlyingResource,size:u.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}n.setPipeline(h);for(let e=0;e{const e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw e}))}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(np.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(np.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then((e=>{t._addDuration(i,null!==e&&e>0?e:0)}))}dispose(){this._measureDuration?.dispose()}}class Ff{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new wf(e,s,Lp.Timestamp,t,i,!0,r)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class Bf{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,r=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=r,this._allocateNewIndices(s)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e})))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose),1e3)}dispose(){this._querySet?.dispose(),this._availableIndices.length=0}}class Lf{async initTwgsl(e){if(!Lf._Twgsl)return e=e||{},(e={...Lf._TWgslDefaultOptions,...e}).twgsl?(Lf._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await hs.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Lf._Twgsl=await self.twgsl(hs.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Lf._Twgsl.convertSpirV2WGSL(e,Lf.DisableUniformityAnalysis||t);return Lf.ShowWGSLShaderCode&&(we.Log(i),we.Log("***********************************************")),Lf.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}Lf._TWgslDefaultOptions={jsPath:`${hs._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${hs._DefaultCdnUrl}/twgsl/twgsl.wasm`},Lf.ShowWGSLShaderCode=!1,Lf.DisableUniformityAnalysis=!1,Lf._Twgsl=null;class kf{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}bi.ShadersStoreWGSL.postprocessVertexShader="attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";const Vf={label:"TextureView_SwapChain_ResolveTarget",dimension:op.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Uf={label:"TextureView_SwapChain",dimension:op.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Gf="/* disable_uniformity_analysis */",zf=new Ee;class Wf extends gn{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then((e=>!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return we.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new iu:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Wf(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){super(null,t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,we.Log(`Babylon.js v${gn.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new Xp,this._shaderProcessorWGSL=new Qp):we.Error("WebGPU is not supported by your browser.")}initAsync(e,t){return this.uniqueId=Wf._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??this._options?.glslangOptions).then((e=>(this._glslang=e,this._tintWASM=Wf.UseTWGSL?new Lf:null,this._tintWASM?this._tintWASM.initTwgsl(t??this._options?.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options))):navigator.gpu.requestAdapter(this._options)))).then((e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const t=this._options.deviceDescriptor??{},i=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(i){const e=i,s=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&s.push(t);t.requiredFeatures=s}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",(e=>{++t{this._isDisposed||(this._contextWasLost=!0,we.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost((async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,s=this.disableCacheRenderPipelines,r=this.disableCacheBindGroups,n=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=s,this.disableCacheBindGroups=r,this.enableGPUTimingMeasurements=n,this._currentRenderPass=null})))}))})).then((()=>{this._bufferManager=new nf(this,this._device),this._textureHelper=new sf(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new hf(this._device),this._cacheBindGroups=new Sf(this._device,this._cacheSampler,this),this._timestampQuery=new Nf(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Bf(this,this._device,this._bufferManager):void 0,this._bundleList=new Df(this._device),this._snapshotRendering=new kf(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),rp.Uniform|rp.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),rp.Uniform|rp.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,we.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new ys(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new mf(this._device,this._emptyVertexBuffer),this._depthCullingState=new vf(this._cacheRenderPipeline),this._stencilStateComposer=new gf(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new Cf(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()})).catch((e=>{throw we.Error("A fatal error occurred during WebGPU creation/initialization."),e}))}_initGlslang(e){return e=e||{},(e={...Wf._GLSLslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?hs.LoadBabylonScriptAsync(e.jsPath).then((()=>self.glslang(hs.GetBabylonScriptURL(e.wasmPath)))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(ip.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(ip.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(ip.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(ip.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(ip.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(ip.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(ip.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new Kp],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:op.E2d,format:this._options.swapChainFormat,usage:ap.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:op.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Ee(0,0,0,1),loadOp:Fp.Clear,storeOp:Bp.Store}]}else t=[{view:void 0,clearValue:new Ee(0,0,0,1),loadOp:Fp.Clear,storeOp:Bp.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?cp.Depth24PlusStencil8:cp.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:op.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:ap.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:op.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Fp.Clear,depthStoreOp:Bp.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Fp.Clear:void 0,stencilStoreOp:this.isStencilEnable?Bp.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:ap.RenderAttachment|ap.CopySrc,alphaMode:this.premultipliedAlpha?kp.Premultiplied:kp.Opaque})}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){mf.ResetCache(),Sf.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,r=t.indexOf(Gf)>=0,n=i===ui.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===ui.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf(Gf)>=0,n=t.indexOf(Gf)>=0,o="#version 450\n",a=s===ui.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=s===ui.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new U_(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new zp(e,this)}createMaterialContext(){return new bf}createDrawContext(){return new Tf(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(we.Log(["defines",a]),we.Log(t),we.Log(i),we.Log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},l.stages=s?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let e=0;e0,n.is3D=l>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=r.useSRGBBuffer,n.label=r.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,a,h||1,r.creationFlags),n}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,s,r,n,o,((e,t,i,s,r,n,o,a)=>{const l=s;if(e.baseWidth=l.width,e.baseHeight=l.height,e.width=l.width,e.height=l.height,e.format=-1!==e.format?e.format:h??5,e.type=-1!==e.type?e.type:0,e._creationFlags=_??0,a(e.width,e.height,l,t,e,(()=>{})),e._hardwareTexture?.underlyingResource)n||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,l.width,l.height,void 0,_);jp.IsImageBitmap(l)&&(this._textureHelper.updateTexture(l,e,l.width,l.height,e.depth,t.format,0,0,r,!1,0,0),n||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,p)}wrapWebGPUTexture(e){const t=new Kp(e),i=new Pi(this,Ai.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){if(e.generateMipMaps){const t=e._hardwareTexture?.underlyingResource;t||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e)}}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const s=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){const e=i+Gp.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let e=0;e0;for(const t in e){const r=e[t],n=i[t],o=n.group,a=n.binding,l=r.type,h=r.object;let c=r.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case tu.Sampler:{const e=h;void 0!==c&&s?u[c].resource=this._cacheSampler.getSampler(e):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case tu.Texture:case tu.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&s?(l===tu.Texture&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(r.indexInGroupEntries=u.length,l===tu.Texture&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case tu.StorageTexture:{const e=h,t=e._texture._hardwareTexture;t.textureAdditionalUsages&ap.StorageBinding||we.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&s?u[c].resource=t.viewForWriting:(r.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case tu.ExternalTexture:{const e=h.underlyingResource;void 0!==c&&s?u[c].resource=this._device.importExternalTexture({source:e}):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._device.importExternalTexture({source:e})}));break}case tu.UniformBuffer:case tu.StorageBuffer:case tu.DataBuffer:{const e=l===tu.DataBuffer?h:(tu.UniformBuffer,h.getBuffer()),t=e.underlyingResource;void 0!==c&&s?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e0&&c.dispatchWorkgroups(s,r,n),c.end(),a&&(this._timestampQuery.endPass(this._timestampIndex,a),this._timestampIndex+=2)},Wf.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},Wf.prototype._prepareComputePipelineContext=function(e,t,i,s,r){const n=e;this.dbgShowShaderCode&&(we.Log(s),we.Log(t)),n.sources={compute:t,rawCompute:i},n.stage=this._createComputePipelineStageDescriptor(t,s,r)},Wf.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},Wf.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},Wf.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((e=>{const i={numErrors:0,messages:[]};for(const t of e.messages)"error"===t.type&&i.numErrors++,i.messages.push({type:t.type,text:t.message,line:t.lineNum,column:t.linePos,length:t.length,offset:t.offset});t(i)}))},Wf.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},Wf.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},Wf.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Pi(this,t.generateStencil?Ai.DepthStencil:Ai.Depth);i.isCube=!0,i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=jp.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Wf.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,null,((e,t)=>{const i=t,n=i[0].width,a=n;this._setCubeMapTextureParams(e,!s),e.format=o??-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,n,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,n,a,l.format,!1,!1,0,0),s||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),r&&r()}),!!d)},Wf.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},Wf.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},Wf.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},Wf.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},Wf.prototype._debugFlushPendingCommands=function(){for(let e=0;e{const i=d.width,n=o(e);if(!n)return;const h=[0,2,4,1,3,5];if(a){const e=4===s,t=a(n),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let s=0;s>s,a=[];for(let i=0;i<6;i++){let o=t[s][l[i]];e&&(o=jf(o,n,n,r)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,n,n,o.format,u,!1,0,0)}}else{const e=[];for(let t=0;t<6;t++)e.push(n[h[t]]);this.updateRawCubeTexture(d,e,s,r,u)}d.isReady=!0,t?.removePendingData(d),l&&l()};return this._loadFile(e,(e=>{_(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},Wf.prototype.createRawTexture3D=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=Ai.Raw3D,d=new Pi(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is3D=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Wf.prototype.updateRawTexture3D=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=jf(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Wf.prototype.createRawTexture2DArray=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=Ai.Raw2DArray,d=new Pi(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is2DArray=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,s,c),this.updateRawTexture2DArray(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Wf.prototype.updateRawTexture2DArray=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=jf(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Wf.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,s,r,n,a)},Wf.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class Kf extends Ka{constructor(e,t,i,s,r){super(e,t,i,s,r),s.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new iu)}}Wf.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const s=new Kf(e,t,i,this);return this._renderTargetWrapperCache.push(s),s},Wf.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode,s.creationFlags=t.creationFlags??0,s.noColorAttachment=!!t.noColorAttachment,s.samples=t.samples,s.label=t.label):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.samplingMode=3,s.creationFlags=0,s.noColorAttachment=!1);const r=s.noColorAttachment?null:this._createInternalTexture(e,t,!0,Ai.RenderTarget);return i.label=s.label??"RenderTargetWrapper",i._samples=s.samples??1,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,!1,i._generateStencilBuffer,i.samples,s.generateStencilBuffer?13:14,s.label?s.label+"-DepthStencil":void 0),r&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r,void 0,void 0,void 0,s.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1)),i},Wf.prototype._createDepthStencilTexture=function(e,t){const i=new Pi(this,t.generateStencil?Ai.DepthStencil:Ai.Depth);i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=jp.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Wf.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.is3D=h>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=1,e._comparisonFunction=r,e._cachedWrapU=0,e._cachedWrapV=0},Wf.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},Wf.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=s.label??"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new Pi(this,Ai.RenderTarget);return r.width=e,r.height=e,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i},Ti.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},Wf.prototype.setTextureSampler=function(e,t){this._currentMaterialContext?.setSampler(e,t)},Ti.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},Wf.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,32|t,i)},Wf.prototype.updateStorageBuffer=function(e,t,i,s){const r=e;let n;void 0===i&&(i=0),void 0===s?(n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,s=n.byteLength):n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(r,i,n,0,s)},Wf.prototype.readFromStorageBuffer=function(e,t,i,s,r){i=i||e.capacity;const n=this._bufferManager.createRawBuffer(i,rp.MapRead|rp.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t??0,n,0,i),new Promise(((e,t)=>{const o=()=>{n.mapAsync(np.Read,0,i).then((()=>{const t=n.getMappedRange(0,i);let r=s;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}n.unmap(),this._bufferManager.releaseBuffer(n),e(r)}),(i=>{this.isDisposed?e(new Uint8Array):t(i)}))};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce((()=>{o()}))}))},Wf.prototype.setStorageBuffer=function(e,t){this._currentDrawContext?.setBuffer(e,t?.getBuffer()??null)},Wf.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),function(e){return!(!e||void 0===e.underlyingResource)}(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0})).catch((()=>{e.isReady=!0}))};class $f{static async CreateAsync(e,t){return await Wf.IsSupportedAsync?Wf.CreateAsync(e,t):gn.IsSupported?new gn(e,void 0,t):new jd(t)}}class qf{}qf.COPY=1,qf.CUT=2,qf.PASTE=3;class Zf{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return qf.COPY;case 86:return qf.PASTE;case 88:return qf.CUT;default:return-1}}}class Jf extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ce.Gray(),i=uu.DefaultUtilityLayer,s=null,r=1,n=Ce.Yellow(),o=Ce.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new X,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new de(0,0,0),this._incrementalStartupValue=de.Zero(),this._parent=s,this._coloredMaterial=new yc("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ce(.1,.1,.1)),this._hoverMaterial=new yc("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new yc("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new bo("axis",i.utilityLayerScene);const{arrowMesh:a,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,r),h=this._createGizmoMesh(this._gizmoMesh,r+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,fu.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const c=a.position.clone(),u=l.position.clone(),d=l.scaling.clone(),_=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;a.position.z+=t/3.5,l.scaling.y+=t,this.dragScale=l.scaling.y,l.position.z=a.position.z/2},p=()=>{a.position.set(c.x,c.y,c.z),l.position.set(u.x,u.y,u.z),l.scaling.set(d.x,d.y,d.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new sa({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let f=0,m=0;const g={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),s=this._tmpVector;let r=!1,n=0;if(this.uniformScaling?s.setAll(.57735):s.copyFrom(e),0==this.snapDistance)s.scaleToRef(i,s);else{f+=i,m+=i;const e=this.incrementalSnap?m:f;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),f%=this.snapDistance,s.scaleToRef(this.snapDistance*n,s),r=!0):s.scaleInPlace(0)}s.addInPlaceFromFloats(1,1,1),s.x=Math.abs(s.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,ge.Quaternion[0],ge.Vector3[2],fu.PreserveScaling?o:void 0),s.addInPlace(this._incrementalStartupValue),s.addInPlaceFromFloats(-1,-1,-1),s.x=Math.abs(s.x)*(this._incrementalStartupValue.x>0?1:-1),s.y=Math.abs(s.y)*(this._incrementalStartupValue.y>0?1:-1),s.z=Math.abs(s.z)*(this._incrementalStartupValue.z>0?1:-1),fe.ComposeToRef(s,ge.Quaternion[0],ge.Vector3[2],ge.Matrix[1])):(fe.ScalingToRef(s.x,s.y,s.z,ge.Matrix[2]),ge.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),ge.Matrix[1])),ge.Matrix[1].decompose(ge.Vector3[1],void 0,void 0,fu.PreserveScaling?o:void 0);const a=1e5;Math.abs(ge.Vector3[1].x){this._dragging=!0;const e=this.attachedNode._isMesh?this.attachedNode:void 0;this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,fu.PreserveScaling?e:void 0),f=0,m=0})),this.dragBehavior.onDragObservable.add((e=>_(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(p),s?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e=>_(e.delta.y))),s?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(p);const v={gizmoMeshes:[a,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,v),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(this._customMeshSet)return;let t=this._parent?.getAxisCache(this._gizmoMesh);if(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),t=this._parent?.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh))),!this._parent){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(v.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(v.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const s=yu("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),r=lu("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return s.scaling.scaleInPlace(.1),s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,s.position.z+=.3,r.material=this._coloredMaterial,r.position.z+=.1375,r.rotation.x=Math.PI/2,i&&(s.visibility=0,r.visibility=0),e.addChild(s),e.addChild(r),{arrowMesh:s,arrowTail:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}Jf.MinimumAbsoluteScale=K;class em extends fu{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let e=0;e<3;e++)for(let s=0;s<3;s++)for(let r=0;r<3;r++){const n=(1===e?1:0)+(1===s?1:0)+(1===r?1:0);if(1!==n&&3!==n){if(t[i]){const n=new de(e-1,s-1,r-1);n.multiplyInPlace(this._axisFactor),t[i].setEnabled(n.lengthSquared()>K)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}get isDragging(){return this._dragging||this._pointerDragBehavior.dragging}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new Ce(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach((t=>{t.color&&(t.color=e)}))}constructor(e=Ce.Gray(),t=uu.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new de(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._rotateSpheresDragBehaviors=[],this._scaleBoxesDragBehaviors=[],this._dragging=!1,this._tmpQuaternion=new pe,this._tmpVector=new de(0,0,0),this._tmpRotationMatrix=new fe,this._incrementalStartupValue=de.Zero(),this._incrementalAnchorStartupValue=de.Zero(),this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.scalingSnapDistance=0,this.rotationSnapDistance=0,this.onDragStartObservable=new X,this.onScaleBoxDragObservable=new X,this.onScaleBoxDragEndObservable=new X,this.onRotationSphereDragObservable=new X,this.onRotationSphereDragEndObservable=new X,this.scalePivot=null,this._axisFactor=new de(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new de,this._dragMesh=null,this._pointerDragBehavior=new sa,this.updateScale=!1,this._anchorMesh=new Sn("anchor",t.utilityLayerScene),this._coloredMaterial=new yc("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new yc("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new Sn("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new pe;const i=[];i.push(Zu("lines",{points:[new de(0,0,0),new de(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,0,0),new de(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,0,0),new de(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,0,0),new de(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,0,0),new de(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,this._boundingDimensions.y,0),new de(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,this._boundingDimensions.y,0),new de(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,0,this._boundingDimensions.z),new de(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,0,this._boundingDimensions.z),new de(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new de(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new de(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new de(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach((t=>{t.color=e,t.position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),t.isPickable=!1,this._lineBoundingBox.addChild(t)})),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateSpheresParent=new Sn("",t.utilityLayerScene),this._rotateSpheresParent.rotationQuaternion=new pe;for(let e=0;e<12;e++){const i=Eu("",{diameter:1},t.utilityLayerScene);i.rotationQuaternion=new pe,i.material=this._coloredMaterial,i.isNearGrabbable=!0;const s=new sa({});s.moveAttached=!1,s.updateDragPlane=!1,i.addBehavior(s);const r=new de(1,0,0);let n=0,o=0;s.onDragStartObservable.add((()=>{r.copyFrom(i.forward),n=0,o=0})),s.onDragObservable.add((t=>{if(this.onRotationSphereDragObservable.notifyObservers({}),this.attachedMesh){const i=this.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void we.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Jo._RemoveAndStorePivotPoint(this.attachedMesh);const s=r,a=t.dragPlaneNormal.scale(de.Dot(t.dragPlaneNormal,s)),l=s.subtract(a).normalizeToNew();let h=de.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());if(h=h/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=pe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=pe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),n+=h,Math.abs(n)<=2*Math.PI){if(this.rotationSnapDistance>0){const e=Math.floor(Math.abs(n)/this.rotationSnapDistance)*(n<0?-1:1),t=this.rotationSnapDistance*e;h=t-o,o=t}e>=8?pe.RotationYawPitchRollToRef(0,0,h,this._tmpQuaternion):e>=4?pe.RotationYawPitchRollToRef(h,0,0,this._tmpQuaternion):pe.RotationYawPitchRollToRef(0,h,0,this._tmpQuaternion),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.copyFrom(this.attachedMesh.position),this._anchorMesh.addChild(this.attachedMesh),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._tmpQuaternion.normalize(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.rotationQuaternion.normalize(),this._anchorMesh.removeChild(this.attachedMesh),this.attachedMesh.setParent(i)}this.updateBoundingBox(),Jo._RestorePivotPoint(this.attachedMesh)}this._updateDummy()})),s.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(i)})),s.onDragEndObservable.add((e=>{this.onRotationSphereDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,i)})),this._rotateSpheresDragBehaviors.push(s),this._rotateSpheresParent.addChild(i)}this._rootMesh.addChild(this._rotateSpheresParent),this._scaleBoxesParent=new Sn("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new pe;for(let e=0;e<3;e++)for(let i=0;i<3;i++)for(let s=0;s<3;s++){const r=(1===e?1:0)+(1===i?1:0)+(1===s?1:0);if(1===r||3===r)continue;const n=yu("",{size:1},t.utilityLayerScene);n.material=this._coloredMaterial,n._internalMetadata=2===r,n.isNearGrabbable=!0;const o=new de(e-1,i-1,s-1).normalize(),a=new sa({dragAxis:o});a.updateDragPlane=!1,a.moveAttached=!1;let l=0,h=0;n.addBehavior(a),a.onDragObservable.add((e=>{if(this.onScaleBoxDragObservable.notifyObservers({}),this.attachedMesh){const t=this.attachedMesh.parent;if(t&&t.scaling&&t.scaling.isNonUniformWithinEpsilon(.001))return void we.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Jo._RemoveAndStorePivotPoint(this.attachedMesh);let i=e.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(l+=i,this.scalingSnapDistance>0){const e=Math.floor(Math.abs(l)/this.scalingSnapDistance)*(l<0?-1:1),t=this.scalingSnapDistance*e;i=t-h,h=t}const s=new de(i,i,i),a=new de(h,h,h);2===r&&(s.x*=Math.abs(o.x),s.y*=Math.abs(o.y),s.z*=Math.abs(o.z)),s.scaleInPlace(this._scaleDragSpeed),s.multiplyInPlace(this._axisFactor),a.scaleInPlace(this._scaleDragSpeed),a.multiplyInPlace(this._axisFactor),a.addInPlace(this._incrementalStartupValue),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),de.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),de.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(n.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.subtractInPlace(this.attachedMesh.getPivotPoint())),this._anchorMesh.addChild(this.attachedMesh),this.incrementalSnap?(a.x/=Math.abs(this._incrementalStartupValue.x){this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(n),l=0,h=0,this._incrementalStartupValue.copyFrom(this.attachedMesh.scaling),this._incrementalAnchorStartupValue.copyFrom(this._anchorMesh.scaling)})),a.onDragEndObservable.add((e=>{this.onScaleBoxDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,n)})),this._scaleBoxesParent.addChild(n),this._scaleBoxesDragBehaviors.push(a)}this._rootMesh.addChild(this._scaleBoxesParent);const s=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add((e=>{s[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=s[e.event.pointerId]&&(s[e.event.pointerId].material=this._coloredMaterial,delete s[e.event.pointerId],this._isHovered=!1):this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{e.pickInfo&&e.pickInfo.pickedMesh==t&&(s[e.event.pointerId]=t,t.material=this._hoverColoredMaterial,this._isHovered=!0)}))})),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationSpheres(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))})),this.updateBoundingBox()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),Jo._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),Jo._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach((e=>{e.markAsDirty("scaling")})),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce((()=>{this._updateDummy()}))}}_selectNode(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{t.isVisible=!e||t==e}))}_unhoverMeshOnTouchUp(e,t){e?.event instanceof PointerEvent&&"touch"===e?.event.pointerType&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){Jo._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=pe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=pe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),Jo._RestorePivotPoint(this.attachedMesh))}_updateRotationSpheres(){const e=this._rotateSpheresParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let s=0;s<2;s++){const r=4*t+2*i+s;if(0==t&&(e[r].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*s),e[r].position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(de.Cross(e[r].position.normalizeToNew(),de.Right()).normalizeToNew().add(e[r].position))),1==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*s),e[r].position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(de.Cross(e[r].position.normalizeToNew(),de.Up()).normalizeToNew().add(e[r].position))),2==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*s,this._boundingDimensions.z/2),e[r].position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(de.Cross(e[r].position.normalizeToNew(),de.Forward()).normalizeToNew().add(e[r].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const t=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(t,t,t)}else this.fixedDragMeshBoundsSize?e[r].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[r].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let s=0;s<3;s++)for(let r=0;r<3;r++){const n=(1===i?1:0)+(1===s?1:0)+(1===r?1:0);if(1!==n&&3!==n){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(s/2),this._boundingDimensions.z*(r/2)),e[t].position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);const i=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(i,i,i)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateSpheresParent.getChildMeshes().forEach(((t,i)=>{i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach((i=>{let s=e;t&&!0===i._internalMetadata&&(s=!1),i.setEnabled(s)}))}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=yu("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new pe,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}releaseDrag(){this._scaleBoxesDragBehaviors.forEach((e=>{e.releaseDrag()})),this._rotateSpheresDragBehaviors.forEach((e=>{e.releaseDrag()})),this._pointerDragBehavior.releaseDrag()}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),this._scaleBoxesDragBehaviors.length=0,this._rotateSpheresDragBehaviors.length=0,super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e),e.rotationQuaternion||(e.rotationQuaternion=pe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),s=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const r=yu("box",{size:1},e.getScene()),n=e.getHierarchyBoundingVectors();return n.max.subtractToRef(n.min,r.scaling),0===r.scaling.y&&(r.scaling.y=K),0===r.scaling.x&&(r.scaling.x=K),0===r.scaling.z&&(r.scaling.z=K),r.position.set((n.max.x+n.min.x)/2,(n.max.y+n.min.y)/2,(n.max.z+n.min.z)/2),e.addChild(r),e.rotationQuaternion.copyFrom(s),e.position.copyFrom(i),e.removeChild(r),r.addChild(e),r.visibility=0,r}setCustomMesh(){we.Error("Custom meshes are not supported on this gizmo")}}class tm extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ce.Gray(),i=uu.DefaultUtilityLayer,s=32,r=null,n=!1,o=1,a=Ce.Yellow(),l=Ce.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new X,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new de,this._parent=r,this._coloredMaterial=new yc("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ce(.1,.1,.1)),this._hoverMaterial=new yc("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._hoverMaterial.specularColor=a,this._disableMaterial=new yc("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new bo("",i.utilityLayerScene);const{rotationMesh:h,collider:c}=this._createGizmoMesh(this._gizmoMesh,o,s);this._rotationDisplayPlane=ta("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),Ti.ShadersStore.rotationGizmoVertexShader=tm._RotationGizmoVertexShader,Ti.ShadersStore.rotationGizmoFragmentShader=tm._RotationGizmoFragmentShader,this._rotationShaderMaterial=new Yu("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=a,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,fu.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new sa({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=tm.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new de,d=new fe,_=new de;let p=new de;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(d),de.TransformCoordinatesToRef(e.dragPlanePoint,d,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const f={snapDistance:0};let m=0;const g=new fe,v=new pe;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const s=new de(1,1,1),r=new pe(0,0,0,1),n=new de(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(s,r,n),!(Math.abs(Math.abs(s.x)-Math.abs(s.y))<=K&&Math.abs(Math.abs(s.x)-Math.abs(s.z))<=K)&&this.updateGizmoRotationToMatchAttachedMesh)return void we.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");r.normalize();const o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,a=t.dragPlanePoint.subtract(o).normalize(),l=u.subtract(o).normalize(),h=de.Cross(a,l),c=de.Dot(a,l);let x=Math.atan2(h.length(),c)*this.sensitivity;_.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(r.toRotationMatrix(d),p=de.TransformCoordinates(_,d));let b=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();de.Dot(e,p)>0&&(_.scaleInPlace(-1),p.scaleInPlace(-1),b=!0)}de.Dot(p,h)>0&&(x=-x),ge.Vector3[0].set(x,0,0),this.dragBehavior.validateDrag(ge.Vector3[0])||(x=0);let T=!1;if(0!=this.snapDistance)if(m+=x,Math.abs(m)>this.snapDistance){let e=Math.floor(Math.abs(m)/this.snapDistance);m<0&&(e*=-1),m%=this.snapDistance,x=this.snapDistance*e,T=!0}else x=0;const y=Math.sin(x/2);if(v.set(_.x*y,_.y*y,_.z*y,Math.cos(x/2)),g.determinant()>0){const e=new de;v.toEulerAnglesToRef(e),pe.RotationYawPitchRollToRef(e.y,-e.x,-e.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)r.multiplyToRef(v,r),r.normalize(),fe.ComposeToRef(s,r,n,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(ge.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(ge.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),T&&(f.snapDistance=x,this.onSnapObservable.notifyObservers(f)),this._angles.y+=x,this.angle+=b?-x:x,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[c],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=tm.MaxDragAngle,this._isHovered=!(-1==b.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const s=Xc("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);s.visibility=0;const r=Xc("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,s.rotation.x=Math.PI/2,e.addChild(r,fu.PreserveScaling),e.addChild(s,fu.PreserveScaling),{rotationMesh:r,collider:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}tm.MaxDragAngle=9*Math.PI/20,tm._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",tm._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ";class im extends fu{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&we.Log("Rotation Gizmo will not work with transforms in billboard mode.")}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=uu.DefaultUtilityLayer,t=32,i=!1,s=1,r,n){super(e),this.onDragStartObservable=new X,this.onDragObservable=new X,this.onDragEndObservable=new X,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=n&&n.xOptions&&n.xOptions.color?n.xOptions.color:Ce.Red().scale(.5),a=n&&n.yOptions&&n.yOptions.color?n.yOptions.color:Ce.Green().scale(.5),l=n&&n.zOptions&&n.zOptions.color?n.zOptions.color:Ce.Blue().scale(.5);this.xGizmo=new tm(new de(1,0,0),o,e,t,this,i,s),this.yGizmo=new tm(new de(0,1,0),a,e,t,this,i,s),this.zGizmo=new tm(new de(0,0,1),l,e,t,this,i,s),this.additionalTransformNode=n?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((e=>{n&&null!=n.updateScale&&(e.updateScale=n.updateScale),e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,r?r.addToAxisCache(this._gizmoAxisCache):fu.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}))}setCustomMesh(){we.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class sm extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new xn("plane",e),s=ta("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return s.material=t,s.parent=i,i}constructor(e,t=Ce.Gray(),i=uu.DefaultUtilityLayer,s=null,r=Ce.Yellow(),n=Ce.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new X,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new yc("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ce(.1,.1,.1)),this._hoverMaterial=new yc("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=r,this._disableMaterial=new yc("",i.utilityLayerScene),this._disableMaterial.diffuseColor=n,this._disableMaterial.alpha=.4,this._gizmoMesh=sm._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let o=0;const a=new de,l={snapDistance:0};this.dragBehavior=new sa({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(ge.Vector3[0]),ge.Vector3[0].addToRef(e.delta,ge.Vector3[0]),this.dragBehavior.validateDrag(ge.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z);else if(o+=e.dragDistance,Math.abs(o)>this.snapDistance){const t=Math.floor(Math.abs(o)/this.snapDistance);o%=this.snapDistance,e.delta.normalizeToRef(a),a.scaleInPlace(this.snapDistance*t),this.attachedNode.getWorldMatrix().getTranslationToRef(ge.Vector3[0]),ge.Vector3[0].addToRef(a,ge.Vector3[0]),this.dragBehavior.validateDrag(ge.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(a.x,a.y,a.z),l.snapDistance=this.snapDistance*t,this.onSnapObservable.notifyObservers(l))}this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const h=i._getSharedGizmoLight();h.includedOnlyMeshes=h.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const c={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,c),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==c.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=c.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(c.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(c.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class rm extends fu{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=uu.DefaultUtilityLayer,t=1,i,s){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new X,this.onDragObservable=new X,this.onDragEndObservable=new X,this._planarGizmoEnabled=!1,this.xGizmo=new mu(new de(1,0,0),Ce.Red().scale(.5),e,this,t),this.yGizmo=new mu(new de(0,1,0),Ce.Green().scale(.5),e,this,t),this.zGizmo=new mu(new de(0,0,1),Ce.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new sm(new de(1,0,0),Ce.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new sm(new de(0,1,0),Ce.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new sm(new de(0,0,1),Ce.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=s?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):fu.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))}),this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)}))}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear()}setCustomMesh(){we.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}class nm extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.uniformScaleGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=uu.DefaultUtilityLayer,t=1,i,s){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new X,this.onDragObservable=new X,this.onDragEndObservable=new X,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new Jf(new de(1,0,0),Ce.Red().scale(.5),e,this,t),this.yGizmo=new Jf(new de(0,1,0),Ce.Green().scale(.5),e,this,t),this.zGizmo=new Jf(new de(0,0,1),Ce.Blue().scale(.5),e,this,t),this.additionalTransformNode=s?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):fu.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new yc("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Ce.Gray(),this._hoverMaterial=new yc("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Ce.Yellow(),this._disableMaterial=new yc("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Ce.Gray(),this._disableMaterial.alpha=.4;const e=new Jf(new de(0,1,0),Ce.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=vd("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=vd("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._octahedron,this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))):we.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.anchorPoint=e)}))}get anchorPoint(){return this._anchorPoint}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set coordinatesMode(e){e==_u.World&&we.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.coordinatesMode=_u.Local}))}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set incrementalSnap(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.incrementalSnap=e)}))}get incrementalSnap(){return this._incrementalSnap}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}getAxisCache(e){return this._gizmoAxisCache.get(e)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach((e=>{e&&e.dispose()})),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class om{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}get isDragging(){let e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((t=>{t&&t.isDragging&&(e=!0)})),e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set coordinatesMode(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.coordinatesMode=e)}))}get coordinatesMode(){return this._coordinatesMode}get attachedMesh(){return this._attachedMesh}get attachedNode(){return this._attachedNode}get additionalTransformNode(){return this._additionalTransformNode}constructor(e,t=1,i=uu.DefaultUtilityLayer,s=uu.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new X,this.onAttachedToNodeObservable=new X,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Ce.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=_u.Local,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new oa,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=s,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const r=this._attachToMeshPointerObserver(e),n=fu.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[r,n]}_attachToMeshPointerObserver(e){return e.onPointerObservable.add((e=>{if(this.usePointerToAttachGizmos&&e.type==Ms.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){if(this.enableAutoPicking){let t=e.pickInfo.pickedMesh;if(null==this.attachableMeshes)for(;t&&null!=t.parent;)t=t.parent;else{let e=!1;this.attachableMeshes.forEach((i=>{t&&(t==i||t.isDescendantOf(i))&&(t=i,e=!0)})),e||(t=null)}t instanceof Sn?this._attachedMesh!=t&&this.attachToMesh(t):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}))}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new rm(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new im(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new nm(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new em(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}set additionalTransformNode(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()}_setAdditionalTransformNode(){for(const e in this.gizmos){const t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}}addToAxisCache(e){e.size>0&&e.forEach(((e,t)=>{this._gizmoAxisCache.set(t,e)}))}releaseDrag(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((e=>{e?.releaseDrag()}))}dispose(){this._pointerObservers.forEach((e=>{this._scene.onPointerObservable.remove(e)}));for(const e in this.gizmos){const t=this.gizmos[e];t&&t.dispose()}this._defaultKeepDepthUtilityLayer!==uu._DefaultKeepDepthUtilityLayer&&this._defaultKeepDepthUtilityLayer?.dispose(),this._defaultUtilityLayer!==uu._DefaultUtilityLayer&&this._defaultUtilityLayer?.dispose(),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class am extends yo{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=fe.Identity(),this._projectionMatrix=fe.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix||(this.transformedPosition||(this.transformedPosition=de.Zero()),de.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=de.Zero()),de.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=de.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=de.Cross(this.direction,_r.Y),t=de.Cross(e,this.direction);return de.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=de.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=fe.Identity()),fe.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=ge.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),de.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(de.Dot(t,de.Up()))&&(t.z=1e-13);const s=ge.Vector3[1];return i.addToRef(t,s),fe.LookAtLHToRef(i,s,de.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}qe([lt()],am.prototype,"position",null),qe([lt()],am.prototype,"direction",null),qe([st()],am.prototype,"shadowMinZ",null),qe([st()],am.prototype,"shadowMaxZ",null),Ct.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new lm(e,de.Zero(),t)));class lm extends am{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return yo.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&fe.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=de.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zr&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;fe.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?a:o,l?o:a,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function hm(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const s=Eu("",{slice:.5,diameter:t.diameter,segments:t.segments},i),r=Nu("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);r.rotation.x=-Math.PI/2,r.parent=s;const n=bo.MergeMeshes([r,s],!0);return n.name=e,n}qe([st()],lm.prototype,"shadowFrustumSize",null),qe([st()],lm.prototype,"shadowOrthoScale",null),qe([st()],lm.prototype,"autoUpdateExtends",void 0),qe([st()],lm.prototype,"autoCalcShadowZBounds",void 0),qe([st("orthoLeft")],lm.prototype,"_orthoLeft",void 0),qe([st("orthoRight")],lm.prototype,"_orthoRight",void 0),qe([st("orthoTop")],lm.prototype,"_orthoTop",void 0),qe([st("orthoBottom")],lm.prototype,"_orthoBottom",void 0);const cm={CreateHemisphere:hm};bo.CreateHemisphere=(e,t,i,s)=>hm(e,{segments:t,diameter:i},s),Ct.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new um(e,de.Zero(),de.Zero(),0,0,t)));class um extends am{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(um._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):um._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=fe.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=de.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=de.Zero(),this._projectionTextureViewLightMatrix=fe.Zero(),this._projectionTextureProjectionLightMatrix=fe.Zero(),this._projectionTextureScalingMatrix=fe.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return yo.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;fe.PerspectiveFovLHToRef(r,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),fe.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),s=-i*t,r=1/Math.tan(this._angle/2);fe.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Vo){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;fe.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=de.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=de.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?de.Normalize(this.transformedDirection):de.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}qe([st()],um.prototype,"angle",null),qe([st()],um.prototype,"innerAngle",null),qe([st()],um.prototype,"shadowAngleScale",null),qe([st()],um.prototype,"exponent",void 0),qe([st()],um.prototype,"projectionTextureLightNear",null),qe([st()],um.prototype,"projectionTextureLightFar",null),qe([st()],um.prototype,"projectionTextureUpDirection",null),qe([rt("projectedLightTexture")],um.prototype,"_projectionTexture",void 0);class dm extends fu{constructor(e=uu.DefaultUtilityLayer){super(e),this._cachedPosition=new de,this._cachedForward=new de(0,0,1),this._pointerObserver=null,this.onClickedObservable=new X,this._light=null,this.attachedMesh=new Sn("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new xn("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new yc("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Ce(.5,.5,.5),this._material.specularColor=new Ce(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),Ms.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){we.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof cu?dm._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof lm?dm._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof um?dm._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):dm._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new pe,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(ge.Vector3[0]),e=ge.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new de(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(de.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new de(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else de.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new bo("hemisphereLight",e),i=hm(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(dm._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new bo("pointLight",e),i=Eu(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(dm._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new bo("spotLight",e);Eu(t.name,{segments:10,diameter:1},e).parent=t;const i=hm(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(dm._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new bo("directionalLight",e),i=new bo(t.name,e);i.parent=t,Eu(t.name,{diameter:1.2,segments:10},e).parent=i;const s=lu(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let r=s.clone(t.name);r.scaling.y=.5,r.position.x+=1.25;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;const o=lu(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,r=o.clone(t.name),r.position.y=1.5,r.position.x+=1.25,n=o.clone(t.name),n.position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(dm._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}dm._Scale=.007,dm._CreateLightLines=(e,t)=>{const i=new bo("root",t);i.rotation.x=Math.PI/2;const s=new bo("linePivot",t);s.parent=i;const r=lu("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(r.position.y=r.scaling.y/2+1.2,r.parent=s,e<2)return s;for(let e=0;e<4;e++){const t=s.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(s.clone("linePivotClone").rotation.z=Math.PI),i};class _m extends fu{constructor(e=uu.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new X,this._camera=null,this._invProjection=new fe,this._material=new yc("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Ce(.5,.5,.5),this._material.specularColor=new Ce(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),Ms.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=_m._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const t=this._frustumLinesColor?.toColor4(1)??new Ee(1,1,1,1);this._cameraLinesMesh=_m._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,t),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new bo("rootCameraGizmo",e),i=new bo(t.name,e);i.parent=t,yu(t.name,{width:1,height:.8,depth:.5},e).parent=i;const s=lu(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;const r=lu(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);r.parent=i,r.position.y=.5,r.position.x=.4,r.rotation.x=.5*Math.PI;const n=lu(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(_m._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){const i=new bo("rootCameraGizmo",e),s=new bo(i.name,e);s.parent=i;for(let i=0;i<4;i+=2)for(let r=0;r<4;r+=2){let n=Zu("lines",{points:[new de(-1+r,-1+i,-1),new de(-1+r,-1+i,1)],colors:[t,t]},e);n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Zu("lines",{points:[new de(-1,-1+r,-1+i),new de(1,-1+r,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Zu("lines",{points:[new de(-1+r,-1,-1+i),new de(-1+r,1,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}_m._Scale=.05;bi.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";bi.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";bi.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";bi.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";bi.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";bi.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";bi.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class pm extends qa{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=Vo.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return yt.Parse((()=>new pm(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,s)}}qe([st("kernel")],pm.prototype,"_kernel",void 0),qe([st("packedFloat")],pm.prototype,"_packedFloat",void 0),qe([at()],pm.prototype,"direction",void 0),ee("BABYLON.BlurPostProcess",pm);class fm extends pl{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,s,r=0,n=Vo.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new ir(0,1,0,1),this._transformMatrix=fe.Zero(),this._mirrorMatrix=fe.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const a=i.getEngine();let l;a.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{a._debugPushGroup?.(`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),fe.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),l=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=de.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=l}))}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new pm("horizontal blur",new ue(1,0),this._blurKernelX,this._blurRatio,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new pm("vertical blur",new ue(0,1),this._blurKernelY,this._blurRatio,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new fm(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),this._sceneUBO?.dispose()}}Vo._CreateMirror=(e,t,i,s)=>new fm(e,t,i,s);class mm extends No{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(fe.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach((e=>s+=e)),new mm(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new mm(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,a=5,l=!1,h=null,c=!1,u=.8,d=0,_,p){super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new X,this.boundingBoxPosition=de.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new fe,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=a,this.isCube=!0,this._textureMatrix=fe.Identity(),this._createPolynomials=c,this.coordinatesMode=Vo.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=h,this._loaderOptions=_,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=d,(e||r)&&this.updateURL(e,h,n,l,o,i,this.getScene()?.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(d||u||c||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=ge.Vector3[0],i=ge.Quaternion[0],s=ge.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,fe.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Vo.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?hs.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const s=yt.Parse((()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new mm(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=de.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=de.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new mm(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}qe([st()],mm.prototype,"url",void 0),qe([lt()],mm.prototype,"boundingBoxPosition",void 0),qe([lt()],mm.prototype,"boundingBoxSize",null),qe([st("rotationY")],mm.prototype,"rotationY",null),qe([st("files")],mm.prototype,"_files",void 0),qe([st("forcedExtension")],mm.prototype,"_forcedExtension",void 0),qe([st("extensions")],mm.prototype,"_extensions",void 0),qe([pt("textureMatrix")],mm.prototype,"_textureMatrix",void 0),qe([pt("textureMatrixRefraction")],mm.prototype,"_textureMatrixRefraction",void 0),Vo._CubeTextureParser=mm.Parse,ee("BABYLON.CubeTexture",mm);bi.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n";bi.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};\n#include\n";bi.ShadersStore.backgroundPixelShader="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";bi.ShadersStore.backgroundVertexShader="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class gm extends Oa{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class vm extends Ra{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=vm.StandardReflectance0*t,this.reflectionReflectance90=vm.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=vm.StandardReflectance0+(1-vm.StandardReflectance0)*t,this.reflectionReflectance90=vm.StandardReflectance90+(1-vm.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=Ce.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=de.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new ds(16),this._reflectionControls=_e.Zero(),this._white=Ce.White(),this._primaryShadowColor=Ce.Black(),this._primaryHighlightColor=Ce.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new gm);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(Zn(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,no(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&lc.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Un(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&lc.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(n.REFLECTION=!0,n.GAMMAREFLECTION=e.gammaSpace,n.RGBDREFLECTION=e.isRGBD,n.REFLECTIONBLUR=this._reflectionBlur>0,n.LODINREFLECTIONALPHA=e.lodLevelInAlpha,n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Vo.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=e.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Vo.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case Vo.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case Vo.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case Vo.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case Vo.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case Vo.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Vo.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Vo.CUBIC_MODE:case Vo.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTION=!1,n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1}n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),qn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),eo(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),ro(e,n,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(ys.NormalKind)||(e.createNormals(!0),we.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const i=new ja;n.FOG&&i.addFallback(0,"FOG"),n.POINTSIZE&&i.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),Kn(n,i,this._maxSimultaneousLights);const s=[ys.PositionKind];n.NORMAL&&s.push(ys.NormalKind),n.UV1&&s.push(ys.UVKind),n.UV2&&s.push(ys.UV2Kind),Qn(s,e,n,i),jn(s,n);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];An(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];xs&&(xs.PrepareUniforms(a,n),xs.PrepareSamplers(l,n)),co({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});const c=n.toString(),u=r.getEngine().createEffect("background",{attributes:s,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(u,n,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),Wn(t,this._activeEffect);const o=this._mustRebind(s,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(s.texturesEnabled&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Gn(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&lc.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),s.texturesEnabled&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&lc.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),In(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&Yn(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),Nn(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&wn(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return yt.Clone((()=>new vm(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return yt.Parse((()=>new vm(e.name,t)),e,t,i)}}vm.StandardReflectance0=.05,vm.StandardReflectance90=.5,qe([nt()],vm.prototype,"_primaryColor",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],vm.prototype,"primaryColor",void 0),qe([nt()],vm.prototype,"__perceptualColor",void 0),qe([st()],vm.prototype,"_primaryColorShadowLevel",void 0),qe([st()],vm.prototype,"_primaryColorHighlightLevel",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],vm.prototype,"primaryColorHighlightLevel",null),qe([rt()],vm.prototype,"_reflectionTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionTexture",void 0),qe([st()],vm.prototype,"_reflectionBlur",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionBlur",void 0),qe([rt()],vm.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"shadowLights",void 0),qe([st()],vm.prototype,"_shadowLevel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"shadowLevel",void 0),qe([lt()],vm.prototype,"_sceneCenter",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"sceneCenter",void 0),qe([st()],vm.prototype,"_opacityFresnel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"opacityFresnel",void 0),qe([st()],vm.prototype,"_reflectionFresnel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionFresnel",void 0),qe([st()],vm.prototype,"_reflectionFalloffDistance",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionFalloffDistance",void 0),qe([st()],vm.prototype,"_reflectionAmount",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionAmount",void 0),qe([st()],vm.prototype,"_reflectionReflectance0",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionReflectance0",void 0),qe([st()],vm.prototype,"_reflectionReflectance90",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionReflectance90",void 0),qe([st()],vm.prototype,"_useRGBColor",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"useRGBColor",void 0),qe([st()],vm.prototype,"_enableNoise",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"enableNoise",void 0),qe([st()],vm.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"maxSimultaneousLights",void 0),qe([st()],vm.prototype,"_shadowOnly",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],vm.prototype,"shadowOnly",void 0),qe([dt()],vm.prototype,"_imageProcessingConfiguration",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],vm.prototype,"enableGroundProjection",void 0),qe([st()],vm.prototype,"projectedGroundRadius",void 0),qe([st()],vm.prototype,"projectedGroundHeight",void 0),ee("BABYLON.BackgroundMaterial",vm);class xm{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Ce(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Ce(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:de.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...xm._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new X,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new Ee(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof No)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=mm.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new bo("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const s=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Th&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const n=r.length();n>e&&(e=2*n,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=ta("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new vm("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof No?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Vo(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Vo.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new fm("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Vo.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new ir(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new vm("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof No?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new mm(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Vo.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}xm._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",xm._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",xm._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class bm extends xn{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Vo.CLAMP_ADDRESSMODE,this._texture.wrapV=Vo.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Vo.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=bm.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new X,this.onLoadObservable=new X,s=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(s.activeCamera?.48*s.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=Eu(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:bo.BACKSIDE},s);const n=this._material=new vm(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=Eu("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:bo.BACKSIDE},s),this._halfDomeMask.rotate(_r.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&s.activeCamera){const e=s.activeCamera,t=de.Forward(),i=de.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(de.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case bm.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case bm.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let s=i.isRightCamera;this._crossEye&&(s=!s),this._texture.uOffset=s?e:t}));break}case bm.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}bm.MODE_MONOSCOPIC=0,bm.MODE_TOPBOTTOM=1,bm.MODE_SIDEBYSIDE=2;class Tm extends bm{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new Vo(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}Tm.MODE_MONOSCOPIC=bm.MODE_MONOSCOPIC,Tm.MODE_TOPBOTTOM=bm.MODE_TOPBOTTOM,Tm.MODE_SIDEBYSIDE=bm.MODE_SIDEBYSIDE;let ym=0;const Sm=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const s=Vo.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+ym++,e,!0,!1,Vo.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const r=e.getEngine().getLoadedTexturesCache(),n=r.indexOf(s.getInternalTexture());-1!==n&&r.splice(n,1),s.isRGBD=!0,s.wrapU=Vo.CLAMP_ADDRESSMODE,s.wrapV=Vo.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=s,e.useDelayedTextureLoading=t,v_.ExpandRGBDTexture(s);const o=e.getEngine().onContextRestoredObservable.add((()=>{s.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{s.isReady()&&(e.onBeforeRenderObservable.remove(t),v_.ExpandRGBDTexture(s))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture},Cm={GetEnvironmentBRDFTexture:Sm};class Em extends Oa{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class Am extends gc{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new Em,t),this._useEnergyConservation=Am.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Am.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Am.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Am.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Am.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Am.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Am.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Am.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Am.DEFAULT_USE_ENERGY_CONSERVATION=!0,Am.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Am.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Am.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,qe([st(),it("_markAllSubMeshesAsMiscDirty")],Am.prototype,"useEnergyConservation",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Am.prototype,"useSmithVisibilityHeightCorrelated",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Am.prototype,"useSphericalHarmonics",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Am.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);bi.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";bi.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";bi.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";bi.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";bi.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#endif\n";bi.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";bi.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}";bi.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n";bi.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}\n#endif\n#endif\n";bi.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";bi.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";bi.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nfloat cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}Rm._DefaultIndexOfRefraction=1.5,qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"isEnabled",void 0),qe([st()],Rm.prototype,"intensity",void 0),qe([st()],Rm.prototype,"roughness",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"indexOfRefraction",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"texture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"useRoughnessFromMainTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"textureRoughness",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"remapF0OnInterfaceChange",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"bumpTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"isTintEnabled",void 0),qe([nt()],Rm.prototype,"tintColor",void 0),qe([st()],Rm.prototype,"tintColorAtDistance",void 0),qe([st()],Rm.prototype,"tintThickness",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"tintTexture",void 0);class Im extends Oa{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class Mm extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new Im,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Mm._DefaultMinimumThickness,this.maximumThickness=Mm._DefaultMaximumThickness,this.indexOfRefraction=Mm._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&lc.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&lc.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lc.IridescenceTextureEnabled?Un(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&lc.IridescenceTextureEnabled?Un(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&lc.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&Gn(this._texture,e,"iridescence"),this._thicknessTexture&&Gn(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&lc.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&lc.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){e&&(this._texture?.dispose(),this._thicknessTexture?.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}Mm._DefaultMinimumThickness=100,Mm._DefaultMaximumThickness=400,Mm._DefaultIndexOfRefraction=1.3,qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"isEnabled",void 0),qe([st()],Mm.prototype,"intensity",void 0),qe([st()],Mm.prototype,"minimumThickness",void 0),qe([st()],Mm.prototype,"maximumThickness",void 0),qe([st()],Mm.prototype,"indexOfRefraction",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"texture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"thicknessTexture",void 0);class Om extends Oa{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Dm extends gc{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new Om,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new ue(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&lc.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(ys.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lc.AnisotropicTextureEnabled?Un(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&lc.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Gn(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&lc.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"isEnabled",void 0),qe([st()],Dm.prototype,"intensity",void 0),qe([at()],Dm.prototype,"direction",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"texture",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Dm.prototype,"legacy",void 0);class wm extends Oa{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class Nm extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new wm,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Ce.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&lc.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&lc.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lc.SheenTextureEnabled?(Un(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&lc.SheenTextureEnabled?Un(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&lc.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&Gn(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Gn(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&lc.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&lc.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"isEnabled",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"linkSheenWithAlbedo",void 0),qe([st()],Nm.prototype,"intensity",void 0),qe([nt()],Nm.prototype,"color",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"texture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"useRoughnessFromMainTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"roughness",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"textureRoughness",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"albedoScaling",void 0);class Fm extends Oa{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class Bm extends gc{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Fm,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Ce.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Ce.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&lc.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&lc.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,void(e.SS_USE_GLTF_TEXTURES=!1);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&lc.ThicknessTextureEnabled&&Un(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&lc.RefractionIntensityTextureEnabled&&Un(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&lc.TranslucencyIntensityTextureEnabled&&Un(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&lc.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(ge.Vector3[0]);const r=Math.max(Math.abs(ge.Vector3[0].x),Math.abs(ge.Vector3[0].y),Math.abs(ge.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,a=r.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&lc.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Gn(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&lc.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Gn(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&lc.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),Gn(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&lc.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,s=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/s,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",i,xe.Log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&lc.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&lc.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&lc.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&lc.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){lc.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e}hasRenderTargetTextures(){return!!(lc.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"}]}}}qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"isRefractionEnabled",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"isTranslucencyEnabled",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"isDispersionEnabled",void 0),qe([st(),it("_markScenePrePassDirty")],Bm.prototype,"isScatteringEnabled",void 0),qe([st()],Bm.prototype,"_scatteringDiffusionProfileIndex",void 0),qe([st()],Bm.prototype,"refractionIntensity",void 0),qe([st()],Bm.prototype,"translucencyIntensity",void 0),qe([st()],Bm.prototype,"useAlbedoToTintRefraction",void 0),qe([st()],Bm.prototype,"useAlbedoToTintTranslucency",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"thicknessTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"refractionTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"indexOfRefraction",void 0),qe([st()],Bm.prototype,"_volumeIndexOfRefraction",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"volumeIndexOfRefraction",null),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"invertRefractionY",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"linkRefractionWithTransparency",void 0),qe([st()],Bm.prototype,"minimumThickness",void 0),qe([st()],Bm.prototype,"maximumThickness",void 0),qe([st()],Bm.prototype,"useThicknessAsDepth",void 0),qe([nt()],Bm.prototype,"tintColor",void 0),qe([st()],Bm.prototype,"tintColorAtDistance",void 0),qe([st()],Bm.prototype,"dispersion",void 0),qe([nt()],Bm.prototype,"diffusionDistance",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"useMaskFromThicknessTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"refractionIntensityTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"translucencyIntensityTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"useGltfStyleTextures",void 0);const Lm={effect:null,subMesh:null};class km extends Oa{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Vm extends Ra{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new _e(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Vm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=Ce.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Ce(0,0,0),this._albedoColor=new Ce(1,1,1),this._reflectivityColor=new Ce(1,1,1),this._reflectionColor=new Ce(1,1,1),this._emissiveColor=new Ce(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=Vm.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new ds(16),this._globalAmbientColor=new Ce(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Am(this),this.clearCoat=new Rm(this),this.iridescence=new Mm(this),this.anisotropy=new Dm(this),this.sheen=new Nm(this),this.subSurface=new Bm(this),this.detailMap=new xc(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),lc.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Sm(this.getScene()),this.prePassConfiguration=new ac}get hasRenderTargetTextures(){return!!(lc.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Vm.PBRMATERIAL_OPAQUE||this._transparencyMode===Vm.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Vm.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Vm.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(En.GetDefineNames,this._eventInfo),t.materialDefines=new km(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&lc.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&lc.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&lc.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&lc.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&lc.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&lc.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(lc.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&lc.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&lc.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(ys.NormalKind)||(e.createNormals(!0),we.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=r._areLightsDisposed;let h=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(Lm.effect=h,Lm.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Lm)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,r.markAsUnprocessed(),c=this.isFrozen,l)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,r,this._materialContext);return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!c,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new ja;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=Kn(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[ys.PositionKind];t.NORMAL&&c.push(ys.NormalKind),t.TANGENT&&c.push(ys.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(ys.ColorKind),Qn(c,e,t,l),jn(c,t),Bn(c,e,t),zn(c,0,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],p=["Material","Scene","Mesh"],f={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=p,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=f,this._callbackPluginEventGeneric(En.PrepareEffect,this._eventInfo),ac.AddUniforms(d),ac.AddSamplers(_),An(d),xs&&(xs.PrepareUniforms(d,t),xs.PrepareSamplers(_,t)),co({uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const m={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,p,_,t,c,m));const g=t.toString(),v=a.createEffect(u,{attributes:c,uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:g,fallbacks:l,onCompiled:i,onError:s,indexParameters:f,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,v}_prepareDefines(e,t,i=null,s=null,r=!1){const n=this.getScene(),o=n.getEngine();Zn(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,no(n,t);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(ao(n,t,this.canRenderToMRT&&!a),oo(n,t,a),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&lc.DiffuseTextureEnabled?(Un(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&lc.AmbientTextureEnabled?(Un(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&lc.OpacityTextureEnabled?(Un(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&lc.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Vo.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case Vo.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Vo.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Vo.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Vo.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Vo.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Vo.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Vo.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Vo.CUBIC_MODE:case Vo.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Vo.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&lc.LightmapTextureEnabled?(Un(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&lc.EmissiveTextureEnabled?(Un(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,lc.SpecularTextureEnabled?(this._metallicTexture?(Un(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(Un(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(Un(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(Un(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?Un(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&lc.BumpTextureEnabled&&!this._disableBumpMap?(Un(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&lc.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&lc.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===Vm.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Vm.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(ys.NormalKind),t.DEBUGMODE=this._debugMode),eo(n,o,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ro(e,t,!0,!0,!0,this._transparencyMode!==Vm.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(En.GetDefineNames,this._eventInfo);const r=new km(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Lm.effect=n,Lm.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Lm)),n.isReady()?t&&t(this):n.onCompileObservable.add((()=>{t&&t(this)}))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=s.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const a=this._mustRebind(s,n,i,t.visibility);Wn(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(a){if(this.bindViewProjection(n),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&lc.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Gn(this._albedoTexture,h,"albedo")),this._ambientTexture&&lc.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Gn(this._ambientTexture,h,"ambient")),this._opacityTexture&&lc.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Gn(this._opacityTexture,h,"opacity")),l&&lc.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,xe.Log2(e))}if(!r.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&e)if(r.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&lc.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Gn(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&lc.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Gn(this._lightmapTexture,h,"lightmap")),lc.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Gn(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Gn(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Gn(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Gn(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Gn(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&lc.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Gn(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){Ae.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,Ae.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",Ae.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,Ae.Color3[0]);const s=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",Ae.Color3[0],s)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",lc.EmissiveTextureEnabled?this._emissiveColor:Ce.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&lc.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&lc.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&lc.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&lc.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),r.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),r.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&lc.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&lc.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),lc.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&lc.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),In(this._activeEffect,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!a&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&Yn(s,t,this._activeEffect,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Nn(s,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&kn(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),wn(r,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e}setPrePassRenderer(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Vm.PBRMATERIAL_OPAQUE=uo.MATERIAL_OPAQUE,Vm.PBRMATERIAL_ALPHATEST=uo.MATERIAL_ALPHATEST,Vm.PBRMATERIAL_ALPHABLEND=uo.MATERIAL_ALPHABLEND,Vm.PBRMATERIAL_ALPHATESTANDBLEND=uo.MATERIAL_ALPHATESTANDBLEND,Vm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Vm.LIGHTFALLOFF_PHYSICAL=0,Vm.LIGHTFALLOFF_GLTF=1,Vm.LIGHTFALLOFF_STANDARD=2,qe([dt()],Vm.prototype,"_imageProcessingConfiguration",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],Vm.prototype,"debugMode",void 0);class Um extends Vm{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Vm.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Vm.LIGHTFALLOFF_PHYSICAL:Vm.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Vm.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Vm.LIGHTFALLOFF_GLTF:Vm.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=Um.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Ce.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Ce(0,0,0),this.albedoColor=new Ce(1,1,1),this.reflectivityColor=new Ce(1,1,1),this.reflectionColor=new Ce(1,1,1),this.emissiveColor=new Ce(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=Sm(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=yt.Clone((()=>new Um(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=yt.Parse((()=>new Um(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),uo._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}Um.PBRMATERIAL_OPAQUE=Vm.PBRMATERIAL_OPAQUE,Um.PBRMATERIAL_ALPHATEST=Vm.PBRMATERIAL_ALPHATEST,Um.PBRMATERIAL_ALPHABLEND=Vm.PBRMATERIAL_ALPHABLEND,Um.PBRMATERIAL_ALPHATESTANDBLEND=Vm.PBRMATERIAL_ALPHATESTANDBLEND,Um.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Vm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"directIntensity",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"emissiveIntensity",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"environmentIntensity",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"specularIntensity",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"disableBumpMap",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"albedoTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"ambientTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"ambientTextureStrength",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesAndMiscDirty")],Um.prototype,"opacityTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectionTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"emissiveTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectivityTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallicTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallic",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"roughness",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallicF0Factor",void 0),qe([nt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallicReflectanceColor",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallicReflectanceTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectanceTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"microSurfaceTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"bumpTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty",null)],Um.prototype,"lightmapTexture",void 0),qe([nt("ambient"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"ambientColor",void 0),qe([nt("albedo"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"albedoColor",void 0),qe([nt("reflectivity"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectivityColor",void 0),qe([nt("reflection"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectionColor",void 0),qe([nt("emissive"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"emissiveColor",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"microSurface",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useLightmapAsShadowmap",void 0),qe([st(),it("_markAllSubMeshesAsTexturesAndMiscDirty")],Um.prototype,"useAlphaFromAlbedoTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesAndMiscDirty")],Um.prototype,"forceAlphaTest",void 0),qe([st(),it("_markAllSubMeshesAsTexturesAndMiscDirty")],Um.prototype,"alphaCutOff",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useSpecularOverAlpha",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useRoughnessFromMetallicTextureGreen",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useMetallnessFromMetallicTextureBlue",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useAmbientInGrayScale",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),qe([st()],Um.prototype,"usePhysicalLightFalloff",null),qe([st()],Um.prototype,"useGLTFLightFalloff",null),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useRadianceOverAlpha",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useObjectSpaceNormalMap",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useParallax",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useParallaxOcclusion",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"parallaxScaleBias",void 0),qe([st(),it("_markAllSubMeshesAsLightsDirty")],Um.prototype,"disableLighting",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"forceIrradianceInFragment",void 0),qe([st(),it("_markAllSubMeshesAsLightsDirty")],Um.prototype,"maxSimultaneousLights",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"invertNormalMapX",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"invertNormalMapY",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"twoSidedLighting",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useAlphaFresnel",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useLinearAlphaFresnel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"environmentBRDFTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"forceNormalForward",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"enableSpecularAntiAliasing",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useHorizonOcclusion",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useRadianceOcclusion",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Um.prototype,"unlit",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Um.prototype,"applyDecalMapAfterDetailMap",void 0),ee("BABYLON.PBRMaterial",Um);const Gm=131072,zm=131072;function Wm(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const Hm=Wm("DXT1"),Xm=Wm("DXT3"),Ym=Wm("DXT5"),Qm=Wm("DX10");class jm{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let s=1;t[2]&Gm&&(s=Math.max(1,t[7]));const r=t[21],n=r===Qm?i[32]:0;let o=0;switch(r){case 113:o=2;break;case 116:o=1;break;case Qm:if(10===n){o=2;break}if(2===n){o=1;break}}return{width:t[4],height:t[3],mipmapCount:s,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&zm)===zm,isCube:!(512&~t[28]),isCompressed:r===Hm||r===Xm||r===Ym,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),a=new Uint16Array(r,i);let l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,a){const l=new Uint8Array(s),h=new Uint8Array(r,i);let c=0;for(let i=0;i>8&255,C>>16&255,C>>24&255))])}var C;const E=jm._ExtractLongWordOrder(u[23]),A=jm._ExtractLongWordOrder(u[24]),P=jm._ExtractLongWordOrder(u[25]),R=jm._ExtractLongWordOrder(u[26]);S&&(b=e._getRGBABufferInternalSizedFormat(s.textureType)),g=1,u[2]&Gm&&!1!==r&&(g=Math.max(1,u[7]));const I=a||0,M=e.getCaps();for(let r=I;r0?s.sphericalPolynomial=b_.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}jm.StoreLODInAlphaChannel=!1,ki.prototype.createPrefilteredCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new l_,n._source=Ai.CubePrefiltered,this.getCaps().textureLOD)return void(r&&r(n));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let r=0;r<3;r++){const l=1-r/2,c=s,u=xe.Log2(a)*i+s,d=c+(u-c)*l,_=Math.round(Math.min(Math.max(d,0),u)),p=new Pi(this,Ai.Temp);if(p.type=n.type,p.format=n.format,p.width=Math.pow(2,Math.max(xe.Log2(a)-_,0)),p.height=p.width,p.isCube=!0,p._cachedWrapU=0,p._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,p,!0),p.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),jm.UploadDDSLevels(this,p,i,t,!0,6,_)}else we.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const f=new No(t);f._isCube=!0,f._texture=p,p.isReady=!0,h.push(f)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],r&&r(n)}),n,o,a,l,i,s)};class Km{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,s){const r=t.getEngine();let n,o=!1,a=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),jm.UploadDDSLevels(r,t,s,n,o,6,-1,i),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t)}else{const s=e;n=jm.GetDDSInfo(s),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new l_),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),jm.UploadDDSLevels(r,t,s,n,o,6),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t,!1)}r._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=jm.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1==1;i(s.width,s.height,r,s.isFourCC,(()=>{jm.UploadDDSLevels(t.getEngine(),t,e,s,r,1)}))}}gn._TextureLoaders.push(new Km);class $m{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=C_(e);if(n){t.width=n.width,t.height=n.width;try{D_(t,n),I_(t,e,n).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{r?.("Can not upload environment levels",e)}))}catch(e){r?.("Can not upload environment file",e)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}gn._TextureLoaders.push(new $m);class qm{constructor(e,t){if(this.data=e,this.isInvalid=!1,!qm.IsValid(e))return this.isInvalid=!0,void we.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),r=67305985===s.getUint32(0,!0);return this.glType=s.getUint32(1*i,r),this.glTypeSize=s.getUint32(2*i,r),this.glFormat=s.getUint32(3*i,r),this.glInternalFormat=s.getUint32(4*i,r),this.glBaseInternalFormat=s.getUint32(5*i,r),this.pixelWidth=s.getUint32(6*i,r),this.pixelHeight=s.getUint32(7*i,r),this.pixelDepth=s.getUint32(8*i,r),this.numberOfArrayElements=s.getUint32(9*i,r),this.numberOfFaces=s.getUint32(10*i,r),this.numberOfMipmapLevels=s.getUint32(11*i,r),this.bytesOfKeyValueData=s.getUint32(12*i,r),0!==this.glType?(we.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(we.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(we.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(we.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=qm.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case qm.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case qm.TEX_2D:case qm.COMPRESSED_3D:case qm.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=qm.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}qm.HEADER_LEN=64,qm.COMPRESSED_2D=0,qm.COMPRESSED_3D=1,qm.TEX_2D=2,qm.TEX_3D=3;class Zm{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((i=>{t(i,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class Jm extends Zm{constructor(e,t,i=Jm.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{s(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}var eg,tg,ig;function sg(e,t){const i=t?.jsDecoderModule||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function rg(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const s=i.data.urls;s&&(s.jsDecoderModule&&void 0===e&&(importScripts(s.jsDecoderModule),e=KTX2DECODER),sg(s)),i.data.wasmBinaries&&sg(void 0,{...i.data.wasmBinaries,jsDecoderModule:e}),t=new e.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}Jm.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(eg||(eg={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(tg||(tg={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(ig||(ig={}));class ng{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[tg.BC1_RGB,tg.BC3_RGBA],yes:{transcodeFormat:tg.RGBA32,engineFormat:ig.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class og{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(og._WorkerPoolPromise||og._DecoderModulePromise)return;const t={jsDecoderModule:hs.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:hs.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:hs.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:hs.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?og._WorkerPoolPromise=new Promise((i=>{const s=`${sg}(${rg})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new Jm(e,(()=>function(e,t,i){return new Promise(((t,s)=>{const r=t=>{e.removeEventListener("error",r),e.removeEventListener("message",n),s(t)},n=i=>{"init"===i.data.action&&(e.removeEventListener("error",r),e.removeEventListener("message",n),t(e))};e.addEventListener("error",r),e.addEventListener("message",n),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(r),0,t))))})):void 0===og._KTX2DecoderModule?og._DecoderModulePromise=hs.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(og._KTX2DecoderModule=KTX2DECODER,og._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,og._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,sg(t,og._KTX2DecoderModule),new og._KTX2DecoderModule.KTX2Decoder))):(og._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,og._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,og._DecoderModulePromise=Promise.resolve(new og._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=og.DefaultNumWorkers){if(this._engine=e,"object"==typeof t&&t.workerPool)og._WorkerPoolPromise=Promise.resolve(t.workerPool);else{"object"==typeof t?og._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(og._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??og.DefaultNumWorkers;og._Initialize(e)}}_uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(og._WorkerPoolPromise)return og._WorkerPoolPromise.then((s=>new Promise(((n,o)=>{s.push(((s,a)=>{const l=e=>{s.removeEventListener("error",l),s.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(s.removeEventListener("error",l),s.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};s.addEventListener("error",l),s.addEventListener("message",h),s.postMessage({action:"setDefaultDecoderOptions",options:og.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),s.postMessage({action:"decode",data:c,caps:r,options:i},[c.buffer])}))}))));if(og._DecoderModulePromise)return og._DecoderModulePromise.then((i=>(og.DefaultDecoderOptions.isDirty&&(og._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=og.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((r,n)=>{i.decode(e,s).then((e=>{this._createTexture(e,t),r()})).catch((e=>{n({message:e})}))})))));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}og.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},og.DefaultNumWorkers=og.GetDefaultNumWorkers(),og.DefaultDecoderOptions=new ng;class ag{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new qm(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(qm.IsValid(e)){t._invertVScale=!t.invertY;const s=new qm(e,1),r=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(s.glInternalFormat);r?(t.format=r,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,(()=>{s.uploadLevels(t,t.generateMipMaps)}),s.isInvalid)}else og.IsValid(e)?new og(t.getEngine())._uploadAsync(e,t,s).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{we.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(we.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}}gn._TextureLoaders.unshift(new ag);class lg extends xh{constructor(e,t,i){super(e,de.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=pe.Identity(),this._referencedPosition=new de,this._trackingState=Fc.NOT_TRACKING,this.onXRCameraInitializedObservable=new X,this.onBeforeCameraTeleport=new X,this.onAfterCameraTeleport=new X,this.onTrackingStateChanged=new X,this.compensateOnFirstFrame=!0,this._rotate180=new pe(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new pe,this.cameraRigMode=Kr.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add((()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()}))})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new jr(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new jr(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,pe.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=ge.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),pe.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(Fc.NOT_TRACKING);const t=e.emulatedPosition?Fc.TRACKING_LOST:Fc.TRACKING;if(this._setTrackingState(t),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{const i=this.rigCameras[t];i.isLeftCamera||i.isRightCamera||("right"===e.eye?i._isRightCamera=!0:"left"===e.eye&&(i._isLeftCamera=!0));const s=this.getScene().customRenderTargets;for(let e=0;ee;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=ge.Matrix[0],t=ge.Matrix[1],i=ge.Matrix[2];fe.ComposeToRef(lg._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),fe.ComposeToRef(lg._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const s=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}lg._ScaleReadOnly=de.One();class hg{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new X,this.onStateChangedObservable=new X,this.state=Nc.NOT_IN_XR,this.sessionManager=new wc(e),this.camera=new lg("webxr",e,this.sessionManager),this.featuresManager=new ca(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new hg(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(Nc.NOT_IN_XR),t.dispose(),e}))}dispose(){this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._spectatorCamera?.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Nc.ENTERING_XR),"viewer"!==t&&"local"!==t&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),"immersive-ar"===e&&"unbounded"!==t&&we.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const r={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(ha.LAYERS)){const e=await i.initializeXRLayerAsync(this.sessionManager.session);r.baseLayer=e}return this.sessionManager.updateRenderState(r),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!this._nonVRCamera?.inputs?.attachedToElement,this._nonVRCamera?.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==Nc.EXITING_XR&&this._setState(Nc.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(Nc.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(Nc.IN_XR)})),this.sessionManager}catch(e){throw we.Log(e),we.Log(e.message),this._setState(Nc.NOT_IN_XR),e}}exitXRAsync(){return this.state!==Nc.IN_XR?Promise.resolve():(this._setState(Nc.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/(e?.fps?e.fps:1e3)*1e3,i=e?.preferredCameraIndex?e?.preferredCameraIndex:0,s=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===Nc.IN_XR?(this._spectatorCamera=new Dh("webxr-spectator",de.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new pe,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===Nc.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class cg{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new X,this.onButtonStateChangedObservable=new X}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}cg.BUTTON_TYPE="button",cg.SQUEEZE_TYPE="squeeze",cg.THUMBSTICK_TYPE="thumbstick",cg.TOUCHPAD_TYPE="touchpad",cg.TRIGGER_TYPE="trigger";class ug{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,s=t.gamepadIndices.button,r=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&r.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new cg(e,i,s,r)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new X,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?we.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,s)=>{const r=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void r(e[0].meshes)}Pa.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),r(e)}),null,((e,i)=>{we.Log(i),we.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const s=i?.5*t+.5:t;pe.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),de.LerpToRef(e.minMesh.position,e.maxMesh.position,s,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=pe.FromEulerAngles(0,Math.PI,0)}}class dg extends ug{constructor(e,t,i){super(e,_g[i],t,i),this.profileId=dg.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=pe.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}dg.ProfileId="generic-trigger";const _g={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class pg extends ug{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=Pa.IsPluginForExtensionAvailable(".glb");return e||we.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const s=t.visualResponses[i];if("transform"===s.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s.valueNodeName),minMesh:this._getChildByName(this.rootMesh,s.minNodeName),maxMesh:this._getChildByName(this.rootMesh,s.maxNodeName)};else{const r=t.type===cg.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:s.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r)},t.type===cg.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=Eu(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new yc(i+"mat",this.scene),t.material.diffuseColor=Ce.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new bo(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],s=this.layout.components[e];Object.keys(s.visualResponses).forEach((e=>{const r=s.visualResponses[e];let n=t.value;if("xAxis"===r.componentProperty?n=t.axes.x:"yAxis"===r.componentProperty&&(n=t.axes.y),"transform"===r.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==r.componentProperty);else{const s=i.states[e].valueMesh;s&&(s.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const fg=[];class mg{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const s=[];i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&s.push("oculus-touch-v2");const r=s.indexOf("windows-mixed-reality");if(-1!==r&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,r=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,s,e,t).catch((()=>r.call(this,s,e,t)))}return this._LoadProfilesFromAvailableControllers(s,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=hs.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e))),this._ProfilesList}static ClearControllerCache(){fg.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),fg.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=hs.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new pg(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:fg)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew dg(t,e.gamepad,e.handedness))),mg.DefaultFallbacks();let gg=0;class vg{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new de,this._disposed=!1,this.onDisposeObservable=new X,this.onMeshLoadedObservable=new X,this.onMotionControllerInitObservable=new X,this._uniqueId=`controller-${gg++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Sn(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new pe,this.inputSource.gripSpace&&(this.grip=new Sn(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new pe),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&mg.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&this.motionController?.dispose()}))}),(()=>{hs.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;de.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,s){const r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){const e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor);const t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(s.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(s.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class xg{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new X,this.onControllerRemovedObservable=new X,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(mg.BaseRepositoryUrl=this._options.customControllersRepositoryURL),mg.UseOnlineRepository=!this._options.disableOnlineControllerRepository,mg.UseOnlineRepository)try{mg.UpdateProfilesList().catch((()=>{mg.UseOnlineRepository=!1}))}catch(e){mg.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new vg(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const s=[],r=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?s.push(e):r.push(e)})),this.controllers=s,r.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),mg.ClearControllerCache()}}class bg extends ua{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Zo(new de,new de),disabledByNearInteraction:!1,id:bg._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":case"transient-pointer":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new de,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Ce(.9,.9,.9),this.laserPointerDefaultColor=new Ce(.7,.7,.7),this.selectionMeshDefaultColor=new Ce(.8,.8,.8),this.selectionMeshPickedColor=new Ce(.3,.3,1),this._identityMatrix=fe.Identity(),this._screenCoordinatesRef=de.Zero(),this._viewportRef=new jr(0,0,0,0),this._scene=this._xrSessionManager.scene,void 0===this._options.lookAndPickMode&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)}),!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Zo(new de,new de),disabledByNearInteraction:!1,id:bg._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(this._options.lookAndPickMode&&"transient-pointer"!==t.xrController?.inputSource.targetRayMode)return;if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=this._options.forceGripIfAvailable&&t.xrController.grip?t.xrController.grip.position:t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay,this._options.forceGripIfAvailable);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,s=this._options.xrInput.xrCamera;s&&(s.viewport.toGlobalToRef(e.getEngine().getRenderWidth()/s.rigCameras.length,e.getEngine().getRenderHeight(),this._viewportRef),de.ProjectToRef(i,this._identityMatrix,s.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||this._screenCoordinatesRef.x===1/0||this._screenCoordinatesRef.y===1/0||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let s=null;this._utilityLayerScene&&(s=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const r=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);s&&s.hit?r&&r.hit?s.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{const e=1-o/i;n.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),r=t.pick}})),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const s=s=>{this._options.overrideButtonId&&(t.selectionComponent=s.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=s.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((s=>{if(s.changes.pressed){const r=s.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),r?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor));else if(r&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const t=this._controllers[this._attachedController];t&&t.pointerDownTriggered&&!t.finalPointerUpTriggered&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(new Ss,{pointerId:t.id,pointerType:"xr"}),t.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}}))};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const e=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)}))},s=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)}))};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(de.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new Ss,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){hs.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():lu("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new yc("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():Xc("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new yc("targetMat",t);return n.specularColor=Ce.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;e.pickedPoint?.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}var Tg,yg,Sg;bg._IdCounter=200,bg.Name=ha.POINTER_SELECTION,bg.Version=1,ca.AddWebXRFeature(bg.Name,((e,t)=>()=>new bg(e,t)),bg.Version,!0),ln.prototype._projectOnTrianglesToRef=function(e,t,i,s,r,n){const o=ge.Vector3[0],a=ge.Vector3[1];let l=1/0;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh(),r=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s,currentAnimationState:Tg.DEHYDRATED,grabRay:new Zo(new de,new de),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:Cg._IdCounter++,pickedPointVisualCue:r},this._controllers[e.uniqueId]._worldScaleObserver=this._controllers[e.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add((t=>{if(t.newScaleFactor!==t.previousScaleFactor){this._controllers[e.uniqueId].touchCollisionMesh.dispose(),this._controllers[e.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh();this._controllers[e.uniqueId].touchCollisionMesh=t,this._controllers[e.uniqueId].touchCollisionMeshFunction=i,this._controllers[e.uniqueId].hydrateCollisionMeshFunction=s,this._controllers[e.uniqueId].pickedPointVisualCue=this._generateVisualCue()}})),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new Ce(.8,.8,.8),this.selectionMeshPickedColor=new Ce(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=yg.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case Tg.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===Tg.HOVER)break;case Tg.HOVER:if(e.touchCollisionMeshFunction(!0),t===Tg.TOUCH)break}else switch(e.currentAnimationState){case Tg.TOUCH:if(e.touchCollisionMeshFunction(!1),t===Tg.HOVER)break;case Tg.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===Tg.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(ge.Vector3[0]),s.grabRay.direction.copyFrom(ge.Vector3[0]),this._options.nearInteractionControllerMode!==yg.CENTERED_IN_FRONT||s.xrController?.inputSource.hand||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{const i=this._controllers[t],s=i.xrController?.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!s&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad))return void(i.pick=null);if(i.hoverInteraction=!1,i.nearInteraction=!1,!i.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const s=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(s&&s.transform){const e=this._scene.useRightHandedSystem?1:-1;ge.Vector3[0].set(s.transform.position.x,s.transform.position.y,s.transform.position.z*e),ge.Quaternion[0].set(s.transform.orientation.x,s.transform.orientation.y,s.transform.orientation.z*e,s.transform.orientation.w*e),this._processTouchPoint(t,ge.Vector3[0],ge.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==yg.DISABLED){let e=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===yg.CENTERED_ON_CONTROLLER&&(e=i.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new Ss,i=!1;const s=e&&e.pickedPoint&&e.hit;return e?.pickedPoint&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),s&&!i&&(t=e),t};if(!i.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const o=r(this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(o&&o.hit&&(e=n(o),e.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let t=null;const o=(s?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,o,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const a=n(r(this._pickWithSphere(i,o,this._scene,(e=>this._nearPickPredicate(e))),t));a.hit&&(e=a,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=e,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=Tg.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=Tg.TOUCH:i.hoverInteraction&&(o=Tg.HOVER),this._handleTransitionAnimation(i,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Eu("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=pe.Identity();const i=new yc("targetMat",e);return i.specularColor=Ce.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))}));const s=s=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),s&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!s&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!s||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},s=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{if(!t.downTriggered)return;const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new Ss,e)})),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._scene,i=Eu("PickSphere",{diameter:1*e},t);i.isVisible=!1,this._options.motionControllerOrbMaterial?i.material=this._options.motionControllerOrbMaterial:Tl.ParseFromSnippetAsync("8RUNKL#3",t).then((e=>{i.material=e}));const s=new Or;s.setEasingMode(Sr.EASINGMODE_EASEINOUT);const r=new de(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new de(n,n,n).scaleInPlace(e),a=this._controllerPickRadius*(7/6),l=new de(a,a,a).scaleInPlace(e),h=.8*this._controllerPickRadius,c=new de(h,h,h).scaleInPlace(e),u=1.5*this._controllerPickRadius,d=[{frame:0,value:r},{frame:10,value:new de(u,u,u).scaleInPlace(e)},{frame:18,value:o}],_=[{frame:0,value:o},{frame:10,value:c},{frame:18,value:r}],p=[{frame:0,value:de.ZeroReadOnly},{frame:12,value:l},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:de.ZeroReadOnly},{frame:15,value:de.ZeroReadOnly}],m=new Nt("touch","scaling",60,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT),g=new Nt("release","scaling",60,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT),v=new Nt("hydrate","scaling",60,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT),x=new Nt("dehydrate","scaling",60,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(s),g.setEasingFunction(s),v.setEasingFunction(s),x.setEasingFunction(s),m.setKeys(d),g.setKeys(_),v.setKeys(p),x.setKeys(f),{touchCollisionMesh:i,touchCollisionMeshFunction:e=>{const s=e?m:g;t.beginDirectAnimation(i,[s],0,18,!1,1)},hydrateCollisionMeshFunction:e=>{const s=e?v:x;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[s],0,15,!1,1,(()=>{e||(i.isVisible=!1)}))}}}_pickWithSphere(e,t,i,s){const r=new Ss;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=Zr.CreateFromCenterAndRadius(n,t);for(let t=0;tc&&(h=0,a.copyFrom(t.center)),-1!==h&&h<_&&(_=h,Zo.CreateFromToToRef(t.center,a,l),l.length=2*_,d=l.intersectsMesh(e),o.copyFrom(a));return _()=>new Cg(e,t)),Cg.Version,!0);class Eg{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Ag{}class Pg{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new X,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw hs.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let s=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const r=document.createElement("style");r.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(r);const n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new Eg(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==Nc.NOT_IN_XR&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):hs.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const s=new Pg(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Nc.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Nc.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,s=i.title;i.title="Error entering XR session : "+s,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function Rg(e){let t=0;const i=Date.now();e.observableParameters=e.observableParameters??{};const s=e.contextObservable.add((r=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/e.timeout,payload:r};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),t>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(Sg||(Sg={}));class Ig{constructor(e){this.onEachCountObservable=new X,this.onTimerAbortedObservable=new X,this.onTimerEndedObservable=new X,this.onStateChangedObservable=new X,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},s=this._breakOnNextTick||this._breakCondition(i);s||this._timer>=this._timeToEnd?this._stop(i,s):this.onEachCountObservable.notifyObservers(i)},this._setState(Sg.INIT),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===Sg.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(Sg.STARTED)}stop(){this._state===Sg.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(Sg.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Mg extends ua{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new Ee(1,1,1,1),this._tmpRay=new Zo(new de,new de),this._tmpVector=new de,this._tmpQuaternion=new pe,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new X,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new X,this.onAfterCameraTeleportRotation=new X,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(cg.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(cg.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(!this.teleportationEnabled)return;const s=()=>{t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,Rg({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};i.changes.pressed&&(i.changes.pressed.current?this._options.timeToTeleportStart?Rg({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{i.pressed&&s()}}):s():(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,pe.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),pe.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else{t.teleportationState.mainComponentUsed=!0;let i=!1;const s=()=>{this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,Rg({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add((e=>{e.type===Ms.POINTERDOWN?(i=!1,this._options.timeToTeleportStart?Rg({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&s()},breakCondition:()=>!!i&&(i=!1,!0)}):s()):e.type===Ms.POINTERUP&&(i=!0,t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Ee(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add((e=>{this.parabolicCheckRadius=this.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,this._options.teleportationTargetMesh?.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor)}))}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(e))return!0;if(this._options.blockAllPickableMeshes&&e.isPickable)return!0;if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.blockerMeshesPredicate||!this._options.blockerMeshesPredicate(e))||!(!this._options.blockAllPickableMeshes||!e.isPickable)||!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e))),l=a&&a.pickedMesh&&-1!==this._floorMeshes.indexOf(a.pickedMesh);if(a&&a.pickedMesh&&!l)return e.teleportationState.mainComponentUsed&&!e.teleportationState.initialHit?void(e.teleportationState.forward=!1):(e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,r),void this._showParabolicPath(a));a&&a.pickedPoint&&(e.teleportationState.initialHit=!0,e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0,!1,r),this._showParabolicPath(a))}this._setTargetMeshVisibility(t,!1,r)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Uc("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,s=new Sc("teleportationPlaneDynamicTexture",i,e,!0);s.hasAlpha=!0;const r=s.getContext(),n=i/2,o=i/2,a=200;r.beginPath(),r.arc(n,o,a,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),s.update();const l=new yc("teleportationPlaneMaterial",e);l.diffuseTexture=s,t.material=l}const i=Xc("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new Nt("animationInnerCircle","position.y",30,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),t.setKeys(s);const r=new Nr;r.setEasingMode(Sr.EASINGMODE_EASEINOUT),t.setEasingFunction(r),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const s=lu("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(_r.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new yc("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new Ce(.3,.3,1):t.diffuseColor=new Ce(.3,.3,1),t.alpha=.9,i.material=t,s.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach((t=>{const n=de.DistanceSquared(t,e);n<=r&&n{t.isVisible=e})),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=yr.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(r||this._cachedColor4White),o=s.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=Zu("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,pe.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}Mg.Name=ha.TELEPORTATION,Mg.Version=1,ca.AddWebXRFeature(Mg.Name,((e,t)=>()=>new Mg(e,t)),Mg.Version,!0);class Og{}class Dg{constructor(){}static CreateAsync(e,t={}){const i=new Dg;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const s={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Pg(e,s)}return hg.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new xg(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(bg.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Mg.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(Cg.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(Ml.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(we.Error("Error initializing XR"),we.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var wg=!0;function Ng(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}dr.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),s=t.max.subtract(t.min),r=t.min.add(s.scale(.5));let n,o=1.5*s.length();if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),e){const e=new Th("default camera",-Math.PI/2,Math.PI/2,o,r,this);e.lowerRadiusLimit=.01*o,e.wheelPrecision=100/o,n=e}else{const e=new xh("default camera",new de(r.x,r.y,-o),this);e.setTarget(r),n=e}n.minZ=.01*o,n.maxZ=1e3*o,n.speed=.2*o,this.activeCamera=n,i&&n.attachControl()}},dr.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},dr.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,s=0,r=!0){if(!e)return we.Warn("Can not create default skybox without environment texture."),null;r&&e&&(this.environmentTexture=e);const n=yu("hdrSkyBox",{size:i},this);if(t){const t=new Um("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Vo.SKYBOX_MODE),t.microSurface=1-s,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{const t=new yc("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Vo.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},dr.prototype.createDefaultEnvironment=function(e){return xm?new xm(e,this):null},dr.prototype.createDefaultVRExperience=function(e={}){return new $c(this,e)},dr.prototype.createDefaultXRExperienceAsync=function(e={}){return Dg.CreateAsync(this,e).then((e=>e))};class Fg extends Vo{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new X),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):we.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===e?.name){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return we.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,s=!1,r=!1,n=Vo.TRILINEAR_SAMPLINGMODE,o={},a,l=5){super(null,i,!s,r),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||hs.IsExponentOfTwo(this.video.videoWidth)&&hs.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Vo.WRAP_ADDRESSMODE,this.wrapV=Vo.WRAP_ADDRESSMODE):(this.wrapU=Vo.CLAMP_ADDRESSMODE,this.wrapV=Vo.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&h?h&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return hs.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(hs.SetCorsBehavior(e,t),t.src=e):(hs.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Ng(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new Fg(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),this._externalTexture?.dispose()}static CreateFromStreamAsync(e,t,i,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(void 0!==r.mozSrcObject?r.mozSrcObject=t:"object"==typeof r.srcObject?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const n=new Fg("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce((()=>{r.remove()})),n.onDisposeObservable.addOnce((()=>{Ng(r)})),t(n),r.removeEventListener("playing",i)};r.addEventListener("playing",i),r.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce((()=>{r.getTracks().forEach((e=>{e.stop()}))})),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then((function(e){t&&t(e)})).catch((function(e){we.Error(e.name)}))}}qe([st("settings")],Fg.prototype,"_settings",void 0),qe([st("src")],Fg.prototype,"_currentSrc",void 0),qe([st()],Fg.prototype,"isVideo",void 0),Vo._CreateVideoTexture=(e,t,i,s=!1,r=!1,n=Vo.TRILINEAR_SAMPLINGMODE,o={},a,l=5)=>new Fg(e,t,i,s,r,n,o,a,l),ee("BABYLON.VideoTexture",Fg);class Bg extends bm{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new Fg((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Vo.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{e.pickInfo?.pickedMesh===this.mesh&&this._texture.video.play()}),Ms.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}Bg.MODE_MONOSCOPIC=bm.MODE_MONOSCOPIC,Bg.MODE_TOPBOTTOM=bm.MODE_TOPBOTTOM,Bg.MODE_SIDEBYSIDE=bm.MODE_SIDEBYSIDE;class Lg{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((()=>{this._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new tr,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class kg{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((()=>{hs.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((()=>{hs.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring(!1)}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((()=>{hs.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((()=>{hs.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((()=>{hs.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((()=>{hs.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((()=>{hs.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((()=>{hs.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((()=>{hs.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((()=>{hs.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((()=>{this._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((()=>{this._renderTime.beginMonitoring(),hs.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((()=>{this._renderTime.endMonitoring(!1),hs.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((e=>{this._cameraRenderTime.beginMonitoring(),hs.StartPerformanceCounter(`Rendering camera ${e.name}`)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((e=>{this._cameraRenderTime.endMonitoring(!1),hs.EndPerformanceCounter(`Rendering camera ${e.name}`)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new tr,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new tr,this._captureFrameTime=!1,this._frameTime=new tr,this._captureRenderTime=!1,this._renderTime=new tr,this._captureInterFrameTime=!1,this._interFrameTime=new tr,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new tr,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new tr,this._capturePhysicsTime=!1,this._physicsTime=new tr,this._captureAnimationsTime=!1,this._animationsTime=new tr,this._captureCameraRenderTime=!1,this._cameraRenderTime=new tr,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add((()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(hs.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this._captureRenderTime&&this._renderTime.fetchNewFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.fetchNewFrame(),this.scene.getEngine()._drawCalls.fetchNewFrame()})),this._onAfterRenderObserver=e.onAfterRenderObservable.add((()=>{this._captureFrameTime&&(hs.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring(),this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.endFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.endFrame(),this._captureParticlesRenderTime&&this._particlesRenderTime.endFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.endFrame(),this._captureRenderTime&&this._renderTime.endFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.endFrame()}))}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}bi.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";class Vg{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let r;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const a=[],l=[ys.PositionKind];let h=!1,c=!1;if(o){const e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(a.push("#define DIFFUSE"),r.isVerticesDataPresent(ys.UV2Kind)&&1===t.coordinatesIndex?(a.push("#define DIFFUSEUV2"),c=!0):r.isVerticesDataPresent(ys.UVKind)&&(a.push("#define DIFFUSEUV1"),h=!0),e&&(a.push("#define ALPHATEST"),a.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||a.push("#define DIFFUSE_ISLINEAR"));const s=o.opacityTexture;s&&(a.push("#define OPACITY"),r.isVerticesDataPresent(ys.UV2Kind)&&1===s.coordinatesIndex?(a.push("#define OPACITYUV2"),c=!0):r.isVerticesDataPresent(ys.UVKind)&&(a.push("#define OPACITYUV1"),h=!0))}i&&(a.push("#define EMISSIVE"),r.isVerticesDataPresent(ys.UV2Kind)&&1===i.coordinatesIndex?(a.push("#define EMISSIVEUV2"),c=!0):r.isVerticesDataPresent(ys.UVKind)&&(a.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||a.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(ys.ColorKind)&&r.hasVertexAlpha&&o.transparencyMode!==uo.MATERIAL_OPAQUE&&(l.push(ys.ColorKind),a.push("#define VERTEXALPHA")),h&&(l.push(ys.UVKind),a.push("#define UV1")),c&&(l.push(ys.UV2Kind),a.push("#define UV2"));const u=new ja;if(r.useBones&&r.computeBonesUsingShaders){l.push(ys.MatricesIndicesKind),l.push(ys.MatricesWeightsKind),r.numBoneInfluencers>4&&(l.push(ys.MatricesIndicesExtraKind),l.push(ys.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,r)}else a.push("#define NUM_BONE_INFLUENCERS 0");const d=r.morphTargetManager;let _=0;d&&(_=d.numMaxInfluencers||d.numInfluencers,_>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+_),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Fn(l,r,_))),t&&(a.push("#define INSTANCES"),Ln(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),Pn(o,this._scene,a),this._addCustomEffectDefines(a);const p=e._getDrawWrapper(void 0,!0),f=p.defines,m=a.join("\n");if(f!==m){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];An(e),p.setEffect(this._engine.createEffect("glowMapGeneration",l,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,u,void 0,void 0,{maxSimultaneousMorphTargets:_}),m)}return p.effect.isReady()}render(){for(let e=0;eh.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return hs.Instantiate(e.customType).Parse(e,t,i)}}Vg._SceneComponentInitialization=e=>{throw vt("EffectLayerSceneComponent")},qe([st()],Vg.prototype,"name",void 0),qe([ut()],Vg.prototype,"neutralColor",void 0),qe([st()],Vg.prototype,"isEnabled",void 0),qe([ft()],Vg.prototype,"camera",null),qe([st()],Vg.prototype,"renderingGroupId",null),qe([st()],Vg.prototype,"disableBoundingBoxesFromEffectLayer",void 0),G.AddParser(Rs.NAME_EFFECTLAYER,((e,t,i,s)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const s=r._mainTexture;this._engine.currentRenderPassId=s.renderPassId;for(const s of e.subMeshes)if(!r.isReady(s,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===Kr.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==Kr.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const e=s._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(Rs.NAME_EFFECTLAYER);t||(t=new Ug(e),e._addComponent(t))};bi.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",G.prototype.getGlowLayerByName=function(e){for(let t=0;t{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new pm("GlowLayerVBP1",new ue(0,1),n,{width:e,height:t},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new pm("GlowLayerHBP2",new ue(1,0),n,{width:s,height:r},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new pm("GlowLayerVBP2",new ue(0,1),n,{width:s,height:r},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(uo.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=yt.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Gg(e.name,t,e.options)),e,t,i);let r;for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class Wg extends Vg{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new X,this.onAfterBlurObservable=new X,this._instanceGlowingMeshStencilReference=Wg.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Wg.NeutralColor,this._engine.isStencilEnable||we.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Wg.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[ys.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?gn.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?gn.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new pl("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Vo.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Vo.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Vo.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new Nh("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new zg("HighlightLayerHBP",new ue(1,0),this._options.blurHorizontalSize,1,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new zg("HighlightLayerVBP",new ue(0,1),this._options.blurVerticalSize,1,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new pm("HighlightLayerHBP",new ue(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new pm("HighlightLayerVBP",new ue(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(uo.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(uo.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!this._meshes&&!!super.hasMesh(e)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const e in this._meshes)if(this._meshes[e]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes)for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Wg.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=yt.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const s=yt.Parse((()=>new Wg(e.name,t,e.options)),e,t,i);let r;for(r=0;rthis._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,s,r){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(r)>-1&&!!(e.layerMask&s)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}bi.ShadersStore.layerPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.layerVertexShader="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Xg{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}constructor(e,t,i,s,r){this.name=e,this._applyPostProcess=!0,this.scale=new ue(1,1),this.offset=new ue(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new X,this.onBeforeRenderObservable=new X,this.onAfterRenderObservable=new X,this.texture=t?new Vo(t,i,!0):null,this.isBackground=void 0===s||s,this.color=void 0===r?new Ee(1,1,1,1):r,this._scene=i||se.LastCreatedScene;let n=this._scene._getComponent(Rs.NAME_LAYER);n||(n=new Hg(this._scene),this._scene._addComponent(n)),this._scene.layers.push(this);const o=this._scene.getEngine();this._drawWrapper=new Fi(o);const a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);const l=new ys(o,a,ys.PositionKind,!1,!1,2);this._vertexBuffers[ys.PositionKind]=l,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+="\n#define LINEAR"),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[ys.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));const i=this._drawWrapper.effect;return i?.isReady()&&this.texture?.isReady()}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(uo.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(uo.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[ys.PositionKind];e&&(e.dispose(),this._vertexBuffers[ys.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}class Yg{static AddFlare(e,t,i,s,r){return new Yg(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Ce(1,1,1),this.texture=s?new Vo(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new Fi(n),this._drawWrapper.effect=n.createEffect("lensFlare",[ys.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}bi.ShadersStore.lensFlarePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.lensFlareVertexShader="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Qg{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||se.LastCreatedScene,Qg._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&i.activeCamera.layerMask);const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[ys.PositionKind]=new ys(s,r,ys.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=de.Project(t,fe.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=de.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new Zo(this._scene.activeCamera.globalPosition,e),s=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,s;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,s=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let r=i>s?i:s;r-=this.viewportBorder,r>this.borderLimit&&(r=this.borderLimit);let n=1-xe.Clamp(r/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const o=t.x+t.width/2,a=t.y+t.height/2,l=o-this._positionX,h=a-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i{throw vt("LensFlareSystemSceneComponent")},G.AddParser(Rs.NAME_LENSFLARESYSTEM,((e,t,i,s)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let r=0,n=e.lensFlareSystems.length;r{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()}))}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;hs.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();hs.EndPerformanceCounter("Lens flares",t.length>0)}}}Qg._SceneComponentInitialization=e=>{let t=e._getComponent(Rs.NAME_LENSFLARESYSTEM);t||(t=new jg(e),e._addComponent(t))};bi.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";bi.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";bi.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";bi.ShadersStore.shadowMapPixelShader="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";bi.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";bi.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";bi.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n";bi.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";bi.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";bi.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";bi.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";bi.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";bi.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";bi.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";class Kg{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===Kg.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===Kg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===Kg.FILTER_PCF||e===Kg.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==Kg.FILTER_PCF&&e!==Kg.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===Kg.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Kg.FILTER_POISSONSAMPLING);(e||this.filter===Kg.FILTER_POISSONSAMPLING)&&(this.filter=e?t:Kg.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Kg.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Kg.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===Kg.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:Kg.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Kg.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Kg.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===Kg.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:Kg.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Kg.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Kg.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Kg.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Kg.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Kg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Kg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Kg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Kg.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Kg.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Kg.FILTER_PCF);(e||this.filter===Kg.FILTER_PCF)&&(this.filter=e?t:Kg.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===Kg.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Kg.FILTER_PCSS);(e||this.filter===Kg.FILTER_PCSS)&&(this.filter=e?t:Kg.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return Kg.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new X,this.onAfterShadowMapRenderObservable=new X,this.onBeforeShadowMapRenderMeshObservable=new X,this.onAfterShadowMapRenderMeshObservable=new X,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Kg.FILTER_NONE,this._filteringQuality=Kg.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=de.Zero(),this._viewMatrix=fe.Zero(),this._projectionMatrix=fe.Zero(),this._transformMatrix=fe.Zero(),this._cachedPosition=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=fe.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),Kg._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new pl(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new pl(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Vo.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Vo.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Vo.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,s)=>this._renderForShadowMap(e,t,i,s),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===Kg.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Kg.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0),e._debugPopGroup?.(1))}));const t=new Ee(0,0,0,0),i=new Ee(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===Kg.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=Ps.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new pm(this._light.name+"KernelBlurY",new ue(0,1),this.blurKernel,1,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new qa(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r{s===i||e?(s.getMeshUniformBuffer().bindToEffect(h,"Mesh"),s.transferToEffect(e?t:_)):(i.getMeshUniformBuffer().bindToEffect(h,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(h),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===Kg.FILTER_NONE||this.filter===Kg.FILTER_PCSS?this._shadowMap.updateSamplingMode(Vo.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Vo.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s)return void(e&&e(this));const r=s.renderList;if(!r)return void(e&&e(this));const n=[];for(const e of r)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let o=0;const a=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[o],i.useInstances,n[o].getMaterial()?.needAlphaBlendingForMesh(n[o].getMesh())??!1);)if(o++,o>=n.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(ys.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===yo.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,o=i.defines;const a=[ys.PositionKind],l=e.getMesh();this.normalBias&&l.isVerticesDataPresent(ys.NormalKind)&&(a.push(ys.NormalKind),n.push("#define NORMAL"),l.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const h=s.needAlphaTesting();if((h||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=s.alphaCutOff??Kg.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),h&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),l.isVerticesDataPresent(ys.UVKind)&&(a.push(ys.UVKind),n.push("#define UV1")),l.isVerticesDataPresent(ys.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(a.push(ys.UV2Kind),n.push("#define UV2"))}const c=new ja;if(l.useBones&&l.computeBonesUsingShaders&&l.skeleton){a.push(ys.MatricesIndicesKind),a.push(ys.MatricesWeightsKind),l.numBoneInfluencers>4&&(a.push(ys.MatricesIndicesExtraKind),a.push(ys.MatricesWeightsExtraKind));const e=l.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+l.numBoneInfluencers),l.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,l),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=l.morphTargetManager;let d=0;if(u&&(d=u.numMaxInfluencers||u.numInfluencers,d>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),Fn(a,l,d))),Pn(s,this._scene,n),t&&(n.push("#define INSTANCES"),Ln(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const _=l.bakedVertexAnimationManager;t&&_&&_.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),a.push("bakedVertexAnimationSettingsInstanced"));const p=n.join("\n");if(o!==p){o=p;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],s=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if(An(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===a.indexOf(e)&&a.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===s.indexOf(e)&&s.push(e)}const l=this._scene.getEngine();r=l.createEffect(e,{attributes:a,uniformsNames:t,uniformBuffersNames:n,samplers:s,defines:p,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d}},l),i.setEffect(r,o)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;i.shadowsEnabled&&s.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Kg.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Kg.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Kg.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Kg.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();r&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===Kg.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r.getSize().width,1/r.getSize().width,this.frustumEdgeFalloff,e)):this._filter===Kg.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r.getSize().width,this._contactHardeningLightSizeUVRatio*r.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/r.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e))}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),de.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(de.Dot(this._lightDirection,de.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),fe.LookAtLHToRef(t,t.add(this._lightDirection),de.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i{throw vt("ShadowGeneratorSceneComponent")};bi.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";bi.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";bi.ShadersStore.depthVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";class $g{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=Vo.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new Ee(1,1,1,1):this.clearColor=new Ee(n?1e8:1,0,0,1),$g._SceneComponentInitialization(this._scene);const a=e.getEngine();this._camera=i,r!==Vo.NEAREST_SAMPLINGMODE&&(1!==t||a._caps.textureFloatLinearFiltering||(r=Vo.NEAREST_SAMPLINGMODE),2!==t||a._caps.textureHalfFloatLinearFiltering||(r=Vo.NEAREST_SAMPLINGMODE));const l=this.isPacked||!a._features.supportExtendedTextureFormats?5:6;this._depthMap=new pl(o??"DepthRenderer",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,l),this._depthMap.wrapU=Vo.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Vo.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{a._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===s.getRenderId())return;const o=i._getWorldMatrixDeterminant()<0;let a=t.overrideMaterialSideOrientation??n.sideOrientation;o&&(a=0===a?1:0);const l=0===a;r.setState(n.backFaceCulling,0,!1,l,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const h=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(h.mustReturn)return;const c=r.getCaps().instancedArrays&&(null!==h.visibleInstances[e._id]&&void 0!==h.visibleInstances[e._id]||t.hasThinInstances),u=this._camera||s.activeCamera;if(this.isReady(e,c)&&u){e._renderId=s.getRenderId();const o=i._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];let a=e._getDrawWrapper();!a&&o&&(a=o._getDrawWrapper());const l=u.mode===Kr.ORTHOGRAPHIC_CAMERA;if(!a)return;const d=a.effect;let _,p;if(r.enableEffect(a),c||t._bind(e,d,n.fillMode),o?o.bindForSubMesh(i.getWorldMatrix(),i,e):(d.setMatrix("viewProjection",s.getTransformMatrix()),d.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&d.setMatrix("view",s.getViewMatrix())),l?(_=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(_=r.useReverseDepthBuffer&&r.isNDCHalfZRange?u.minZ:r.isNDCHalfZRange?0:u.minZ,p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:u.maxZ),d.setFloat2("depthValues",_,_+p),!o){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(d.setTexture("diffuseSampler",e),d.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices){const i=e.getTransformMatrixTexture(t);if(!i)return;d.setTexture("boneSampler",i),d.setFloat("boneTextureWidth",4*(e.bones.length+1))}else d.setMatrices("mBones",e.getTransformMatrices(t))}In(d,n,s),kn(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d),n.pointsCloud&&d.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,d,n.fillMode,h,c,((e,t)=>d.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,s)=>{let r;if(s.length)for(r=0;r4&&(l.push(ys.MatricesIndicesExtraKind),l.push(ys.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),a.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;t?.isUsingTextureForMatrices&&a.push("#define BONETEXTURE")}else a.push("#define NUM_BONE_INFLUENCERS 0");const h=s.morphTargetManager;let c=0;h&&(c=h.numMaxInfluencers||h.numInfluencers,c>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Fn(l,s,c))),o.pointsCloud&&a.push("#define POINTSIZE"),t&&(a.push("#define INSTANCES"),Ln(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&a.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&a.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&a.push("#define PACKED"),Pn(o,r,a);const u=e._getDrawWrapper(void 0,!0),d=u.defines,_=a.join("\n");if(d!==_){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];An(e),u.setEffect(i.createEffect("depth",l,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}$g._SceneComponentInitialization=e=>{throw vt("DepthRendererSceneComponent")};bi.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class qg{constructor(e){this.onAfterReductionPerformed=new X,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Cs(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new qa("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(n);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new qa("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,r.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=s,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const s=new Float32Array(4*e*t),n={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,s,!1),n.min=s[0],n.max=s[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(o,a,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),e._debugPopGroup?.(1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo()))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return rv.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=t+r*s,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*s,a=o-n,l=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Kg.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==Kg.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;const n=r.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===Kg.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,r),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===Kg.FILTER_PCSS){for(let e=0;enew rv(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}rv._FrustumCornersNDCSpace=[new de(-1,1,-1),new de(1,1,-1),new de(1,-1,-1),new de(-1,-1,-1),new de(-1,1,1),new de(1,1,1),new de(1,-1,1),new de(-1,-1,1)],rv.CLASSNAME="CascadedShadowGenerator",rv.DEFAULT_CASCADES_COUNT=4,rv.MIN_CASCADES_COUNT=2,rv.MAX_CASCADES_COUNT=4,rv._SceneComponentInitialization=e=>{throw vt("ShadowGeneratorSceneComponent")},G.AddParser(Rs.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,s=e.shadowGenerators.length;i{let t=e._getComponent(Rs.NAME_SHADOWGENERATOR);t||(t=new nv(e),e._addComponent(t))},Ct.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new ov(e,de.Zero(),t)));class ov extends am{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return yo.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new de(1,0,0);case 1:return new de(-1,0,0);case 2:return new de(0,-1,0);case 3:return new de(0,1,0);case 4:return new de(0,0,1);case 5:return new de(0,0,-1)}return de.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;fe.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}qe([st()],ov.prototype,"shadowAngle",null);class av{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;av.DefaultLogoUrl?t.src=av.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=new Image;if(av.DefaultSpinnerUrl?s.src=av.DefaultSpinnerUrl:s.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${i.w}vh`,s.style.height=`${i.h}vh`,s.style.left=`calc(50% - ${i.w/2}vh)`,s.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(s),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}av.DefaultLogoUrl="",av.DefaultSpinnerUrl="",gn.DefaultLoadingScreenFactory=e=>new av(e);class lv{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),back:this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),left:this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),right:this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),up:this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),down:this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r),size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=n?Math.max(1,Math.round(s/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),_=1/e;let p=0;for(let n=0;nMath.PI;)r-=2*Math.PI;let o=r/Math.PI;const a=n/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*s);h<0?h=0:h>=s&&(h=s-1);const c=s-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}lv.FACE_LEFT=[new de(-1,-1,-1),new de(1,-1,-1),new de(-1,1,-1),new de(1,1,-1)],lv.FACE_RIGHT=[new de(1,-1,1),new de(-1,-1,1),new de(1,1,1),new de(-1,1,1)],lv.FACE_FRONT=[new de(1,-1,-1),new de(1,-1,1),new de(1,1,-1),new de(1,1,1)],lv.FACE_BACK=[new de(-1,-1,1),new de(-1,-1,-1),new de(-1,1,1),new de(-1,1,-1)],lv.FACE_DOWN=[new de(1,1,-1),new de(1,1,1),new de(-1,1,-1),new de(-1,1,1)],lv.FACE_UP=[new de(-1,-1,-1),new de(-1,-1,1),new de(1,-1,-1),new de(1,-1,1)];class hv{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,s,r,n){r>0?(r=this._Ldexp(1,r-136),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return lv.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,a,l,h=t.dataPosition,c=0,u=0,d=0;const _=new ArrayBuffer(4*s),p=new Uint8Array(_),f=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(f);for(;i>0;){if(r=e[h++],n=e[h++],o=e[h++],a=e[h++],2!=r||2!=n||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=s)throw"HDR Bad header format, wrong scan line width";for(c=0,d=0;d<4;d++)for(u=(d+1)*s;c128){if(l=r-128,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)p[c++]=n}else{if(l=r,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(p[c++]=n,--l>0)for(let t=0;t0;){for(l=0;l{this._effectRenderer=new al(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(we.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class uv extends No{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(fe.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,s=!1,r=!0,n=!1,o=!1,a=null,l=null,h=!1){super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=de.Zero(),this.onLoadObservable=new X,e&&(this._coordinatesMode=Vo.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=fe.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),a&&a()},this._onError=l,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=h,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?hs.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):this.getScene()?.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new cv(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=hv.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=b_.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const s=[];let r=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(r=new Uint8Array(this._size*this._size*3));const o=t[uv._FacesMapping[e]];if(this.gammaSpace||n||r)for(let e=0;e255){const e=255/n;t*=e,i*=e,s*=e}r[3*e+0]=t,r[3*e+1]=i,r[3*e+2]=s}n?s.push(n):r?s.push(r):s.push(o)}return s}),null,this._onLoad,this._onError)}clone(){const e=new uv(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let s=null;return e.name&&!e.isRenderTarget&&(s=new uv(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=de.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=de.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}uv._FacesMapping=["right","left","up","down","front","back"],ee("BABYLON.HDRCubeTexture",uv);class dv{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new X,this._onDataLayoutChanged=new X,this._animationPropertiesOverride=null,this._scene=i||se.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=yt.Clone((()=>new dv(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),yt.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new dv(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new ds(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=se.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return pv.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new pv(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=pv.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void we.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new pv(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(dv.Parse(s,t));return i}}pv.EnableTextureStorage=!0,pv.MaxActiveMorphTargetsInVertexAttributeMode=8;class fv{constructor(){this._hasHit=!1,this._hitNormal=de.Zero(),this._hitPoint=de.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class mv extends fv{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=de.Zero(),this._rayToWorld=de.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=de.Distance(this._rayFromWorld,this._hitPoint)}reset(e=de.Zero(),t=de.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}class gv{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw vt("CannonJSPlugin")}constructor(e,t=gv.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new de(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter((function(s){return s.connectedImpostor===t&&s.joint===i&&s.mainImpostor===e}));s.length&&this._physicsPlugin.removeJoint(s[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void we.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(r[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const s=i[t];e.physicsBody[t].set(s.x,s.y,s.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const i=t=>{if(!t.rotationQuaternion)return;const s=t.getPhysicsImpostor();if(s&&s.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),r=t.rotationQuaternion.multiply(this._tmpQuaternion);s.physicsBody&&(this.removePhysicsBody(s),s.physicsBody=null),s.parent=e,s.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(s),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(r.x,r.y,r.z,r.w)),e.physicsBody.mass+=s.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let s;const r=e.joint.jointData,n={pivotA:r.mainPivot?(new this.BJSCANNON.Vec3).set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?(new this.BJSCANNON.Vec3).set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?(new this.BJSCANNON.Vec3).set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?(new this.BJSCANNON.Vec3).set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case da.HingeJoint:case da.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case da.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case da.SpringJoint:{const e=r;s=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case da.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case da.PointToPointJoint:case da.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce)}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==da.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==da.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;s1e3*i));e++);this.time+=s;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}gv.DefaultPluginFactory=()=>new vv;class xv{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=de.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new mv}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){we.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},s=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&s.push(e.physicsImpostor)}));const r=e=>Math.max(e,K),n=new pe;s.forEach((t=>{if(!t.object.rotationQuaternion)return;const s=t.object.rotationQuaternion;n.copyFrom(s),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=n.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case ga.ParticleImpostor:we.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case ga.SphereImpostor:{const e=a.x,t=a.y,s=a.z,n=Math.max(r(e),r(t),r(s))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case ga.CylinderImpostor:{const e=r(a.x)/2,t=r(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case ga.PlaneImpostor:case ga.BoxImpostor:default:{const e=r(a.x),t=r(a.y),s=r(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(s);break}}t.object.rotationQuaternion=s})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case da.BallAndSocketJoint:n="jointBall";break;case da.SpringJoint:{we.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=s;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case da.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case da.PrismaticJoint:n="jointPrisme";break;case da.SliderJoint:n="jointSlide";break;case da.WheelJoint:n="jointWheel";break;case da.HingeJoint:default:n="jointHinge"}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){we.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new de(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new de(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,s){void 0!==i?we.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return we.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){we.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class bv{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new pe,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new de,this._tmpContactNormal=new de,this._tmpVec3=new de,this._tmpMatrix=new fe,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new mv,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):we.Error("AmmoJS is not available. Please make sure you included the js file.")):we.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===ga.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,a;const l=new Array;for(let e=0;e{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData;let r;switch(s.mainPivot||(s.mainPivot=new de(0,0,0)),s.connectedPivot||(s.connectedPivot=new de(0,0,0)),e.joint.type){case da.DistanceJoint:{const e=s.maxDistance;e&&(s.mainPivot=new de(0,-e/2,0),s.connectedPivot=new de(0,e/2,0)),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case da.HingeJoint:{s.mainAxis||(s.mainAxis=new de(0,0,0)),s.connectedAxis||(s.connectedAxis=new de(0,0,0));const e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),n=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);r=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,n);break}case da.BallAndSocketJoint:r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:we.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n,o=i.getVerticesData(ys.PositionKind);if(o||(o=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?pe.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):pe.Identity(),fe.Compose(de.One(),e,t.position).invertToRef(this._tmpMatrix),n=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else fe.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),n=this._tmpMatrix;const a=r.length/3;for(let t=0;t{s+=this._addMeshVerts(e,t,i)}))}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(ys.PositionKind);i||(i=[]);let s=t.getVerticesData(ys.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let e=0;ee*e)).reduce(((e,t)=>e+t)))t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const s=e.getParam("path");if(null===e.getParam("shape"))return we.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=s.length,i=t-1,this._tmpAmmoVectorA.setValue(s[0].x,s[0].y,s[0].z),this._tmpAmmoVectorB.setValue(s[t-1].x,s[t-1].y,s[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(ys.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let t=0;t{s+=this._addHullVerts(e,t,i)}))}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==ga.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const r=this._createShape(t),n=e.parent.getWorldMatrix().clone(),o=new de;n.decompose(o),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*o.x,e.position.y*o.y,e.position.z*o.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,r),t.dispose(),i++}})),i>0){if(e.type!=ga.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,t))}return s}this.bjsAMMO.destroy(s),s=null}switch(e.type){case ga.SphereImpostor:if(xe.WithinEpsilon(r.x,r.y,1e-4)&&xe.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{const e=[new this.bjsAMMO.btVector3(0,0,0)],t=[1];s=new this.bjsAMMO.btMultiSphereShape(e,t,1),s.setLocalScaling(new this.bjsAMMO.btVector3(r.x/2,r.y/2,r.z/2))}break;case ga.CapsuleImpostor:{const e=r.x/2;s=new this.bjsAMMO.btCapsuleShape(e,r.y-2*e)}break;case ga.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case ga.PlaneImpostor:case ga.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case ga.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const r=this._addMeshVerts(t,i,i);s=0==r?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case ga.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),s=new this.bjsAMMO.btCompoundShape):s=t}break;case ga.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case ga.CustomImpostor:s=this._createCustom(e);break;case ga.SoftbodyImpostor:s=this._createSoftbody(e);break;case ga.ClothImpostor:s=this._createCloth(e);break;case ga.RopeImpostor:s=this._createRope(e);break;default:we.Warn("The impostor type is not currently supported by the ammo plugin.")}return s}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>K||Math.abs(s.getOrigin().y()-t.y)>K||Math.abs(s.getOrigin().z()-t.z)>K||Math.abs(s.getRotation().x()-i.x)>K||Math.abs(s.getRotation().y()-i.y)>K||Math.abs(s.getRotation().z()-i.z)>K||Math.abs(s.getRotation().w()-i.w)>K)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(s)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new de(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new de(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(we.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===ga.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):we.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(we.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):we.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(we.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):we.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(we.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):we.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*s));e.physicsBody.appendAnchor(a,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){we.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){we.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}bv._DISABLE_COLLISION_FLAG=4,bv._KINEMATIC_FLAG=2,bv._DISABLE_DEACTIVATION_FLAG=4,G.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},G.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class Tv{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=fe.Identity(),this._target=de.Zero(),this._add=de.Zero(),this._invertYAxis=!1,this.position=de.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(r){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new pl(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const a=i.getEngine().useReverseDepthBuffer;let l;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?fe.LookAtRHToRef:fe.LookAtLHToRef,s=i.useRightHandedSystem?fe.PerspectiveFovRH:fe.PerspectiveFovLH;t(this.position,this._target,de.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=s(Math.PI/2,1,a?i.activeCamera.maxZ:i.activeCamera.minZ,a?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{this._currentSceneUBO=i.getSceneUniformBuffer(),i.getEngine()._debugPushGroup?.(`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),i.getEngine()._debugPopGroup?.(1)}))}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=yt.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let i=0;is||new Tv(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}qe([ht()],Tv.prototype,"_attachedMesh",void 0),qe([lt()],Tv.prototype,"position",void 0);class yv{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class Sv extends yv{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new X,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new Ee(1,1,1,1),this.position=de.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=r.distance))&&(r=a,i))break}return r||new Ss},dr.prototype._internalMultiPickSprites=function(e,t,i){if(!Ss)return null;let s=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;r!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(Rs.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(Rs.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(Rs.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,Re.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,Re.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,Re.CreateNewFromSprite(i.pickedSprite,r,s))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,Re.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,Re.CreateNewFromSprite(i.pickedSprite,n,s)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,Re.CreateNewFromSprite(i.pickedSprite,n,s)),r&&i.pickedSprite.actionManager.processTrigger(6,Re.CreateNewFromSprite(i.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,Re.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}bi.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";bi.ShadersStore.spritesPixelShader="uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.spritesVertexShader="attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \nvColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class Ev{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,s=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Ts(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(ys.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Ts(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(ys.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ys.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[ys.ColorKind]=c,this._createEffects()}_createEffects(){this._drawWrapperBase?.dispose(),this._drawWrapperFog?.dispose(),this._drawWrapperDepth?.dispose(),this._drawWrapperFogDepth?.dispose(),this._drawWrapperBase=new Fi(this._engine),this._drawWrapperFog=new Fi(this._engine),this._drawWrapperDepth=new Fi(this._engine,!1),this._drawWrapperFogDepth=new Fi(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);const e=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[ys.PositionKind,"options","offsets","inverts","cellInfo",ys.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[ys.PositionKind,"options","offsets","inverts","cellInfo",ys.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],e+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,o=this._drawWrapperDepth,a=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(n=this._drawWrapperFog,o=this._drawWrapperFogDepth,a=!0);const l=n.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length);let _=0,p=!0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},r||(r=se.LastCreatedScene),r._getComponent(Rs.NAME_SPRITE)||r._addComponent(new Cv(r)),this._fromPacked=a,this._scene=r;const h=this._scene.getEngine();if(this._spriteRenderer=new Ev(h,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else{if(void 0===s)return void(this._spriteRenderer=null);this.cellWidth=s,this.cellHeight=s}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Vo(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const s=e.substring(0,i-1)+".json",r=()=>{we.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},n=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};hs.LoadFile(s,n,void 0,void 0,!1,r)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=ge.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const a=(o.x-s.x)/(r.x-s.x),l=1-(o.y-s.y)/(r.y-s.y),h=e._xOffset*n.width+a*e._xSize|0,c=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[4*(h+c*n.width)+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=de.Zero(),o=de.Zero();let a=Number.MAX_VALUE,l=null;const h=ge.Vector3[0],c=ge.Vector3[1],u=t.getViewMatrix();let d=e,_=e;for(let t=0;te){if(!this._checkTextureAlpha(r,d,e,n,o))continue;if(_=d,a=e,l=r,s)break}}}}if(l){const e=new Ss;u.invertToRef(ge.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=a;const t=ge.Vector3[2];return t.copyFrom(_.direction),t.normalize(),t.scaleInPlace(a),_.origin.addToRef(t,h),e.pickedPoint=de.TransformCoordinates(h,ge.Matrix[0]),e}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=de.Zero(),n=de.Zero();let o;const a=[],l=ge.Vector3[0].copyFromFloats(0,0,0),h=ge.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{const o=new At;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=Av.Parse(t,i||se.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new Av("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((s,r)=>{const n=new At;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.spriteManager),a=Av.Parse(o,t||se.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Av.SnippetUrl="https://snippet.babylonjs.com",Av.CreateFromSnippetAsync=Av.ParseFromSnippetAsync;var Pv=!0;class Rv{}Rv.LoaderInjectedPhysicsEngine=void 0;let Iv={},Mv={};const Ov=(e,t,i,s)=>{if(!t.materials)return null;for(let r=0,n=t.materials.length;r{for(const s in t)if(e.name===t[s])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},wv=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),Nv=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const s=t._waitingData.lods.ids,r=i.isEnabled(!1);if(t._waitingData.lods.distances){const n=t._waitingData.lods.distances;if(n.length>=s.length){const t=n.length>s.length?n[n.length-1]:0;i.setEnabled(!1);for(let t=0;t0&&i.addLODLevel(t,null),!0===r&&i.setEnabled(!0)}else hs.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},Fv=(e,t,i)=>{if("number"!=typeof e){const s=i.getLastEntryById(e);return s&&null!=t?s.instances[parseInt(t)]:s}const s=Iv[e];return s&&null!=t?s.instances[parseInt(t)]:s},Bv=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):Mv[e],Lv=(e,t,i,s,r=!1)=>{const n=new Eo(e);let o="importScene has failed JSON parse";try{var a=JSON.parse(t);o="";const s=Pa.loggingLevel===Pa.DETAILED_LOGGING;let r,l;if(void 0!==a.environmentTexture&&null!==a.environmentTexture){const t=void 0===a.isPBR||a.isPBR;if(a.environmentTextureType&&"BABYLON.HDRCubeTexture"===a.environmentTextureType){const s=a.environmentTextureSize?a.environmentTextureSize:128,r=new uv((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,s,!0,!t,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(r.rotationY=a.environmentTextureRotationY),e.environmentTexture=r}else if("object"==typeof a.environmentTexture){const t=mm.Parse(a.environmentTexture,e,i);e.environmentTexture=t}else if(a.environmentTexture.endsWith(".env")){const t=new mm((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}else{const t=mm.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}if(!0===a.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,s=a.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,s)}n.environmentTexture=e.environmentTexture}if(void 0!==a.environmentIntensity&&null!==a.environmentIntensity&&(e.environmentIntensity=a.environmentIntensity),void 0!==a.lights&&null!==a.lights)for(r=0,l=a.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})))}if(void 0!==a.multiMaterials&&null!==a.multiMaterials)for(r=0,l=a.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==a.morphTargetManagers&&null!==a.morphTargetManagers)for(const t of a.morphTargetManagers){const i=pv.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==a.skeletons&&null!==a.skeletons)for(r=0,l=a.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)}))}if(void 0!==a.transformNodes&&null!==a.transformNodes)for(r=0,l=a.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(Bv(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=Bv(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,l=e.skeletons.length;r{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,l=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),G.Parse(a,e,n,i),r=0,l=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,n,o,a)=>{let l="importMesh has failed JSON parse";try{var h=JSON.parse(i);l="";const a=Pa.loggingLevel===Pa.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const c=[],u=new Map,d=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(let e=0,i=h.transformNodes.length;e{!0!==e&&h.geometries[i]&&Array.isArray(h.geometries[i])&&h.geometries[i].forEach((r=>{r.id===f.geometryId&&("vertexData"===i&&_n.Parse(r,t,s),e=!0)}))})),!1===e&&we.Warn("Geometry not found for mesh "+f.id)}if(f.materialUniqueId||f.materialId){const e=f.materialUniqueId?_:n;let i=-1!==e.indexOf(f.materialUniqueId||f.materialId);if(!1===i&&void 0!==h.multiMaterials&&null!==h.multiMaterials){const r=(i,r)=>{e.push(i);const n=Ov(r,h,t,s);n&&n.material&&(Mv[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,l+="\n\tMaterial "+n.material.toString(a))};for(let s=0,n=h.multiMaterials.length;sr(e,(t=>t.uniqueId===e)))):n.materials.forEach((e=>r(e,(t=>t.id===e)))),e.push(n.uniqueId||n.id);const s=_o.ParseMultiMaterial(n,t);Mv[n.uniqueId||n.id]=s,s&&(i=!0,l+="\n\tMulti-Material "+s.toString(a));break}}}if(!1===i){e.push(f.materialUniqueId||f.materialId);const i=Ov((e=>f.materialUniqueId&&e.uniqueId===f.materialUniqueId||e.id===f.materialId),h,t,s);i&&i.material?(Mv[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,l+="\n\tMaterial "+i.material.toString(a)):we.Warn("Material not found for mesh "+f.id)}}if(null!==f.skeletonId&&void 0!==f.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(i.indexOf(f.skeletonId)>-1))for(let e=0,s=h.skeletons.length;e-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(p.indexOf(f.morphTargetManagerId)>-1))for(let e=0,i=h.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(Bv(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=Bv(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,i=t.transformNodes.length;e-1&&d.splice(e,1)}f._waitingParentId=null}f._waitingData.lods&&Nv(t,f)}for(const e of d)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(e){const t=wv("importMesh",h?h.producer:"Unknown")+l;if(!a)throw we.Log(t),e;a(t,e)}finally{null!==l&&Pa.loggingLevel!==Pa.NO_LOGGING&&we.Log(wv("importMesh",h?h.producer:"Unknown")+(Pa.loggingLevel!==Pa.MINIMAL_LOGGING?l:"")),Mv={}}return!1},load:(e,t,i,s)=>{let r="importScene has failed JSON parse";try{var n=JSON.parse(t);if(r="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!Pa.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=Ee.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=Ce.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=de.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),n.fogMode&&0!==n.fogMode)switch(e.fogMode=n.fogMode,e.fogColor=Ce.FromArray(n.fogColor),e.fogStart=n.fogStart,e.fogEnd=n.fogEnd,e.fogDensity=n.fogDensity,r+="\tFog mode for scene: ",e.fogMode){case 1:r+="exp\n";break;case 2:r+="exp2\n";break;case 3:r+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===vv.name?t=new vv(void 0,void 0,Rv.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===xv.name?t=new xv(void 0,Rv.LoaderInjectedPhysicsEngine):"ammo"!==n.physicsEngine&&n.physicsEngine!==bv.name||(t=new bv(void 0,Rv.LoaderInjectedPhysicsEngine,void 0)),r="\tPhysics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";const i=n.physicsGravity?de.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!!Lv(e,t,i,s,!0)&&(n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0)}catch(e){const t=wv("importScene",n?n.producer:"Unknown")+r;if(!s)throw we.Log(t),e;s(t,e)}finally{null!==r&&Pa.loggingLevel!==Pa.NO_LOGGING&&we.Log(wv("importScene",n?n.producer:"Unknown")+(Pa.loggingLevel!==Pa.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:(e,t,i,s)=>Lv(e,t,i,s)});class kv{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,gn.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||Ce.White(),this.rightColor=e.rightColor||Ce.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new kv;return Xe.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new kv({isEnabled:e.isEnabled,leftColor:Ce.FromArray(e.leftColor),rightColor:Ce.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}yt._FresnelParametersParser=kv.Parse;class Vv{}Vv.BindSceneUniformBuffer=Vn,Vv.PrepareDefinesForMergedUV=Un,Vv.BindTextureMatrix=Gn,Vv.GetFogState=$n,Vv.PrepareDefinesForMisc=qn,Vv.PrepareDefinesForCamera=lo,Vv.PrepareDefinesForFrameBoundValues=eo,Vv.PrepareDefinesForBones=to,Vv.PrepareDefinesForMorphTargets=io,Vv.PrepareDefinesForBakedVertexAnimation=so,Vv.PrepareDefinesForAttributes=ro,Vv.PrepareDefinesForMultiview=no,Vv.PrepareDefinesForOIT=oo,Vv.PrepareDefinesForPrePass=ao,Vv.PrepareDefinesForLight=Jn,Vv.PrepareDefinesForLights=Zn,Vv.PrepareUniformsAndSamplersForLight=ho,Vv.PrepareUniformsAndSamplersList=co,Vv.HandleFallbacksForShadows=Kn,Vv.PrepareAttributesForMorphTargetsInfluencers=Fn,Vv.PrepareAttributesForMorphTargets=Bn,Vv.PrepareAttributesForBakedVertexAnimation=zn,Vv.PrepareAttributesForBones=Qn,Vv.PrepareAttributesForInstances=jn,Vv.PushAttributesForInstances=Ln,Vv.BindLightProperties=Hn,Vv.BindLight=Xn,Vv.BindLights=Yn,Vv.BindFogParameters=Nn,Vv.BindBonesParameters=Wn,Vv.BindMorphTargetParameters=kn,Vv.BindLogDepth=wn;class Uv extends Yu{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new Ee(0,0,0,1))}}class Gv extends Vm{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new Ce(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}qe([st(),it("_markAllSubMeshesAsLightsDirty")],Gv.prototype,"maxSimultaneousLights",void 0),qe([st(),it("_markAllSubMeshesAsLightsDirty")],Gv.prototype,"disableLighting",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Gv.prototype,"environmentTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"invertNormalMapX",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"invertNormalMapY",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Gv.prototype,"normalTexture",void 0),qe([nt("emissive"),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"emissiveColor",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"emissiveTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Gv.prototype,"occlusionStrength",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Gv.prototype,"occlusionTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Gv.prototype,"alphaCutOff",void 0),qe([st()],Gv.prototype,"doubleSided",null),qe([rt(),it("_markAllSubMeshesAsTexturesDirty",null)],Gv.prototype,"lightmapTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"useLightmapAsShadowmap",void 0);class zv extends Gv{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=yt.Clone((()=>new zv(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=yt.Parse((()=>new zv(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}qe([nt(),it("_markAllSubMeshesAsTexturesDirty","_albedoColor")],zv.prototype,"baseColor",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],zv.prototype,"baseTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],zv.prototype,"metallic",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],zv.prototype,"roughness",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],zv.prototype,"metallicRoughnessTexture",void 0),ee("BABYLON.PBRMetallicRoughnessMaterial",zv);class Wv extends Gv{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=yt.Clone((()=>new Wv(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=yt.Parse((()=>new Wv(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}qe([nt("diffuse"),it("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Wv.prototype,"diffuseColor",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Wv.prototype,"diffuseTexture",void 0),qe([nt("specular"),it("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Wv.prototype,"specularColor",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty","_microSurface")],Wv.prototype,"glossiness",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Wv.prototype,"specularGlossinessTexture",void 0),ee("BABYLON.PBRSpecularGlossinessMaterial",Wv);class Hv extends No{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=fe.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=i=>{if("string"!=typeof i)return;let s,r=null,n=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)r[e]=255;else{const t=n[e];r[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,r,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,r,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new Hv(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new Hv(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}Hv._NoneEmptyLineRegex=/\S+/,ee("BABYLON.ColorGradingTexture",Hv);class Xv extends No{constructor(e,t,i,s=!1,r=!0,n=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Vo.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?hs.SetImmediate((()=>n())):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage((()=>this._loadTexture()),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const s=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);s.generateMipMaps=!this._noMipmap,i.addPendingData(s),s.url=this.url,s.isReady=!1,i.getEngine()._internalTexturesCache.push(s),this._texture=s;const r=document.createElement("canvas");Qi(this.url,(t=>{this._width=t.width,this._height=t.height,r.width=this._width,r.height=this._height;const i=r.getContext("2d");i.drawImage(t,0,0);const s=i.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,r.remove(),e()}),((e,r)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,r)}),i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene();if(!e)return;const t=(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=lv.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const s=t[Xv._FacesMapping[e]];i.push(s)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let s=0;for(let r=0;rt.length)return void we.Error("Unable to load TGA file - Not enough data");i+=s.id_length;let r,n=!1,o=!1,a=!1;switch(s.image_type){case $v:n=!0;case Qv:o=!0;break;case qv:n=!0;case jv:break;case Zv:n=!0;case Kv:a=!0}const l=s.pixel_size>>3,h=s.width*s.height*l;let c,u,d,_,p,f,m;if(o&&(c=t.subarray(i,i+=s.colormap_length*(s.colormap_size>>3))),n){let e,s,n;r=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i>ex){default:case sx:u=0,_=1,m=s.width,d=0,p=1,f=s.height;break;case tx:u=0,_=1,m=s.width,d=s.height-1,p=-1,f=-1;break;case rx:u=s.width-1,_=-1,m=-1,d=0,p=1,f=s.height;break;case ix:u=s.width-1,_=-1,m=-1,d=s.height-1,p=-1,f=-1}const g="_getImageData"+(a?"Grey":"")+s.pixel_size+"bits",v=ax[g](s,c,r,d,p,f,u,_,m);e.getEngine()._uploadDataToTextureDirectly(e,v)}const ax={GetTGAHeader:nx,UploadContent:ox,_getImageData8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=t,u=e.width,d=e.height;let _,p,f,m=0;const g=new Uint8Array(u*d*4);for(f=s;f!==n;f+=r)for(p=o;p!==l;p+=a,m++)_=h[m],g[4*(p+u*f)+3]=255,g[4*(p+u*f)+2]=c[3*_+0],g[4*(p+u*f)+1]=c[3*_+1],g[4*(p+u*f)+0]=c[3*_+2];return g},_getImageData16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p,f=0;const m=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(_=o;_!==l;_+=a,f+=2){d=h[f+0]+(h[f+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(_+c*p)+0]=e,m[4*(_+c*p)+1]=t,m[4*(_+c*p)+2]=i,m[4*(_+c*p)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=3)f[4*(d+c*_)+3]=255,f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+1]=h[p+1],f[4*(d+c*_)+0]=h[p+2];return f},_getImageData32bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=4)f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+1]=h[p+1],f[4*(d+c*_)+0]=h[p+2],f[4*(d+c*_)+3]=h[p+3];return f},_getImageDataGrey8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p,f=0;const m=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(_=o;_!==l;_+=a,f++)d=h[f],m[4*(_+c*p)+0]=d,m[4*(_+c*p)+1]=d,m[4*(_+c*p)+2]=d,m[4*(_+c*p)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=2)f[4*(d+c*_)+0]=h[p+0],f[4*(d+c*_)+1]=h[p+0],f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+3]=h[p+1];return f}};class lx{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=nx(s);i(r.width,r.height,t.generateMipMaps,!1,(()=>{ox(t,s)}))}}gn._TextureLoaders.push(new lx);class hx{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=hv.RGBE_ReadHeader(s),n=hv.RGBE_ReadPixels(s,r),o=r.width*r.height,a=new Float32Array(4*o);for(let e=0;e{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}}function cx(){let e=null;function t(e,t,i,s,r){const n=e.getImageTranscodedSizeInBytes(t,i,s);let o=new Uint8Array(n);return e.transcodeImage(o,t,i,s,1,0)?(r&&(o=function(e,t,i,s){const r=new Uint16Array(4),n=new Uint16Array(i*s),o=i/4,a=s/4;for(let t=0;t>2&3],n[h++]=r[l>>4&3],n[h++]=r[l>>6&3]}}return n}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,s=i.data.imageData,r=new BASIS.BasisFile(s),n=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),s=[];for(let t=0;t{let i;switch(e){case _x.cTFETC1:i=36196;break;case _x.cTFBC1:i=33776;break;case _x.cTFBC4:i=33779;break;case _x.cTFASTC_4x4:i=37808;break;case _x.cTFETC2:i=37496;break;case _x.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i};let mx=null,gx=null,vx=0;const xx=e=>{gx=e},bx=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,s)=>{(mx||(mx=new Promise(((e,t)=>{gx?e(gx):hs.LoadFileAsync(hs.GetBabylonScriptURL(px.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const s=URL.createObjectURL(new Blob([`(${cx})()`],{type:"application/javascript"}));gx=new Worker(s),function(e,t,i){return new Promise(((s,r)=>{const n=t=>{"init"===t.data.action?(e.removeEventListener("message",n),s(e)):"error"===t.data.action&&r(t.data.error||"error initializing worker")};e.addEventListener("message",n),e.postMessage({action:"init",url:i?hs.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(gx,i,px.JSModuleURL).then(e,t)})).catch(t)}))),mx).then((()=>{const r=vx++,n=t=>{"transcode"===t.data.action&&t.data.id===r&&(gx.removeEventListener("message",n),t.data.success?e(t.data):s("Transcode is not supported on this device"))};gx.addEventListener("message",n);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),gx.postMessage({action:"transcode",id:r,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{s(e)}))}))},Tx=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},yx=(e,t)=>{const i=e.getEngine();for(let s=0;s{i._releaseTexture(t),Tx(e,i)}))}else{e.width=r.width,e.height=r.height,e.generateMipMaps=t.fileInfo.images[s].levels.length>1;const n=Sx.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,Tx(e,i),t.fileInfo.images[s].levels.forEach(((t,r)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,s,r)})),!i._features.basisNeedsPOT||xe.Log2(e.width)%1==0&&xe.Log2(e.height)%1==0||(hs.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=Vo.CLAMP_ADDRESSMODE,e._cachedWrapV=Vo.CLAMP_ADDRESSMODE)}}},Sx={JSModuleURL:px.JSModuleURL,WasmModuleURL:px.WasmModuleURL,GetInternalFormatFromBasisFormat:fx,TranscodeAsync:bx,LoadTextureFromTranscodeResult:yx};Object.defineProperty(Sx,"JSModuleURL",{get:function(){return px.JSModuleURL},set:function(e){px.JSModuleURL=e}}),Object.defineProperty(Sx,"WasmModuleURL",{get:function(){return px.WasmModuleURL},set:function(e){px.WasmModuleURL=e}});class Cx{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};bx(e,o).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;yx(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()})).catch((e=>{hs.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,r&&r(e)}))}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};bx(e,r).then((e=>{const s=e.fileInfo.images[0].levels[0],r=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(s.width,s.height,r,-1!==e.format,(()=>{yx(t,e)}))})).catch((e=>{hs.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),hs.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}}gn._TextureLoaders.push(new Cx);class Ex extends pl{get isSupported(){return this._engine?.getCaps().drawBuffersExtension??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}class Ax{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Px{constructor(e,t,i,s){return this.name=e,this.meshes=t,this.scene=s,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??ys.UVKind,this.options.uvsOut=this.options.uvsOut??ys.UVKind,this.options.layout=this.options.layout??Px.LAYOUT_STRIP,this.options.layout===Px.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Px.SUBUV_WRAP,this.options.paddingMode===Px.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new Ee(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new ue(1,1).divide(t);let s=0;const r=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(a,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{s++,d.update(!1);const i=_.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*p.x,t.y*p.y),d.dispose(),n.update(!1),s==r)return c(),void e()},m=o[u]||"_blank";if(n&&null!==n[m]){const e=n[m],t=new Image;t.src=e instanceof Sc?e.getContext().canvas.toDataURL("image/png"):e.url,hs.SetCorsBehavior(t.src,t),t.onload=()=>{_.fillStyle="rgba(0,0,0,0)",_.fillRect(0,0,h,h),d.update(!1),_.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)_.drawImage(t,0,0,t.width,t.height,l+a*e[i],l+a*e[i+1]-h,a,a);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},s=Object.keys(this.sets),r=Object.keys(this.options);try{for(let r=0;r{try{this.setFragment(this._texturePath)}catch(e){we.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",s=new At;s.open("GET",i),s.addEventListener("load",(()=>{if(200===s.status||s.responseText&&s.responseText.length>0)try{this._config=JSON.parse(s.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch(e){t()}else t()}),!1),s.addEventListener("error",(()=>{t()}),!1);try{s.send()}catch(e){we.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=.03*t.getAnimationRatio(),this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e{}))}clone(){return yt.Clone((()=>{const e=this.getScene(),t=this._texture,i=new Mx(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===Ai.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}class Ox extends Vo{constructor(e,t,i,s,r,n,o=!0,a=!1,l=Vo.TRILINEAR_SAMPLINGMODE,h=0,c){super(null,n,!o,a),this.format=r,this._texture=n.getEngine().createRawTexture3D(e,t,i,s,r,o,a,l,null,h,c),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class Dx extends pl{constructor(e,t,i,s){super(e,t,i,s,!0),this.refractionPlane=new ir(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((()=>{this.getScene().clipPlane=this.refractionPlane})),this.onAfterRenderObservable.add((()=>{this.getScene().clipPlane=null}))}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Dx(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}class wx extends wo{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){this._renderTarget?.dispose(!0),this._renderTarget=null,e||super.dispose()}}class Nx extends Da{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Nx&&e._blockName===this._blockName?Ta.Compatible:Ta.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class Fx extends wa{constructor(e){super(e,ba.Vertex),this.registerInput("matricesIndices",xa.Vector4),this.registerInput("matricesWeights",xa.Vector4),this.registerInput("matricesIndicesExtra",xa.Vector4,!0),this.registerInput("matricesWeightsExtra",xa.Vector4,!0),this.registerInput("world",xa.Matrix),this.registerOutput("output",xa.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name&&t(e)));i||(i=new Wa("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name&&t(e)));i||(i=new Wa("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.World&&t(e)));i||(i=new Wa("world"),i.setAsSystemValue(Ea.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){Wn(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&to(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const s=this._outputs[0],r=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",e.compilationString+=this._declareOutput(s,e)+` = ${r.associatedVariableName} * ${i};\n`,e.compilationString+="#else\n",e.compilationString+=this._declareOutput(s,e)+` = ${r.associatedVariableName};\n`,e.compilationString+="#endif\n",this}}ee("BABYLON.BonesBlock",Fx);class Bx extends wa{constructor(e){super(e,ba.Vertex),this.registerInput("world0",xa.Vector4),this.registerInput("world1",xa.Vector4),this.registerInput("world2",xa.Vector4),this.registerInput("world3",xa.Vector4),this.registerInput("world",xa.Matrix,!0),this.registerOutput("output",xa.Matrix),this.registerOutput("instanceID",xa.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=(()=>!0)){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name&&t(e)));i||(i=new Wa("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name&&t(e)));i||(i=new Wa("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name&&t(e)));i||(i=new Wa("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name&&t(e)));i||(i=new Wa("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name&&t(e)));i||(i=new Wa("world"),i.setAsSystemValue(Ea.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!r?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!r?.getRenderingMesh().hasThinInstances),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,a=this.world3;return e.compilationString+="#ifdef INSTANCES\n",e.compilationString+=this._declareOutput(i,e)+` = mat4(${r.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\n`,e.compilationString+="#ifdef THIN_INSTANCES\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\n`,e.compilationString+="#endif\n",t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(s,e)+" = float(gl_InstanceID);\n":e.compilationString+=this._declareOutput(s,e)+" = 0.0;\n",e.compilationString+="#else\n",e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName};\n`,e.compilationString+=this._declareOutput(s,e)+" = 0.0;\n",e.compilationString+="#endif\n",this}}ee("BABYLON.InstancesBlock",Bx);class Lx extends wa{constructor(e){super(e,ba.Vertex),this.registerInput("position",xa.Vector3),this.registerInput("normal",xa.Vector3),this.registerInput("tangent",xa.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(xa.Color4|xa.Vector4|xa.Vector3),this.registerInput("uv",xa.Vector2),this.registerOutput("positionOutput",xa.Vector3),this.registerOutput("normalOutput",xa.Vector3),this.registerOutput("tangentOutput",xa.Vector4),this.registerOutput("uvOutput",xa.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Wa("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Wa("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&t(e)));i||(i=new Wa("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Wa("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;t?.isUsingTextureForTargets&&(t.numMaxInfluencers||t.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&io(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(kn(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,_=s.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,f=p&&p.supportsNormals&&s.NORMAL,m=p&&p.supportsTangents&&s.TANGENT,g=p&&p.supportsUVs&&s.UV1;let v="";if(p?.isUsingTextureForTargets&&_>0&&(v+="float vertexID;\n"),v+="#ifdef MORPHTARGETS\n",p?.isUsingTextureForTargets)v+="for (int i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n",v+="if (i >= morphTargetCount) break;\n",v+="vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\n",v+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${r.associatedVariableName}) * morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",f&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${a.associatedVariableName}) * morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * morphTargetInfluences[i];\n`,o.type===xa.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n"),v+="}\n";else for(let e=0;e<_;e++)v+=`${l.associatedVariableName} += (position${e} - ${r.associatedVariableName}) * morphTargetInfluences[${e}];\n`,f&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (normal${e} - ${n.associatedVariableName}) * morphTargetInfluences[${e}];\n`,v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName}.xy += (uv_${e} - ${a.associatedVariableName}.xy) * morphTargetInfluences[${e}];\n`,v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (tangent${e} - ${o.associatedVariableName}.xyz) * morphTargetInfluences[${e}];\n`,o.type===xa.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n");if(v+="#endif\n",d.compilationString=d.compilationString.replace(this._repeatableContentAnchor,v),_>0)for(let e=0;e<_;e++)d.attributes.push(ys.PositionKind+e),f&&d.attributes.push(ys.NormalKind+e),m&&d.attributes.push(ys.TangentKind+e),g&&d.attributes.push(ys.UVKind+"_"+e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);const t=this.position,i=this.normal,s=this.tangent,r=this.uv,n=this.positionOutput,o=this.normalOutput,a=this.tangentOutput,l=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetCount"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${this._declareOutput(n,e)} = ${t.associatedVariableName};\n`,e.compilationString+="#ifdef NORMAL\n",e.compilationString+=`${this._declareOutput(o,e)} = ${i.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${this._declareOutput(o,e)} = vec3(0., 0., 0.);\n`,e.compilationString+="#endif\n",e.compilationString+="#ifdef TANGENT\n",e.compilationString+=`${this._declareOutput(a,e)} = ${s.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${this._declareOutput(a,e)} = vec4(0., 0., 0., 0.);\n`,e.compilationString+="#endif\n",e.compilationString+="#ifdef UV1\n",e.compilationString+=`${this._declareOutput(l,e)} = ${r.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${this._declareOutput(l,e)} = vec2(0., 0.);\n`,e.compilationString+="#endif\n",this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}}ee("BABYLON.MorphTargetsBlock",Lx);class kx extends wa{constructor(e){super(e,ba.Vertex),this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerOutput("direction",xa.Vector3),this.registerOutput("color",xa.Color3),this.registerOutput("intensity",xa.Float),this.registerOutput("shadowBias",xa.Float),this.registerOutput("shadowNormalBias",xa.Float),this.registerOutput("shadowDepthScale",xa.Float),this.registerOutput("shadowDepthRange",xa.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let s=this.light;const r=t.getScene();if(!s&&r.lights.length&&(s=this.light=r.lights[0],this._forcePrepareDefines=!0),!s||!s.isEnabled)return e.setFloat3(this._lightDataUniformName,0,0,0),void e.setFloat4(this._lightColorUniformName,0,0,0,0);s.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,s.diffuse,s.intensity);const n=s.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(n?e.setFloat3(this._lightShadowUniformName,n.bias,n.normalBias,n.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange)if(n&&r.activeCamera){const t=s;e.setFloat2(this._lightShadowExtraUniformName,t.getDepthMinZ(r.activeCamera),t.getDepthMinZ(r.activeCamera)+t.getDepthMaxZ(r.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;const s=this.light;i.setValue(this._lightTypeDefineName,!!(s&&s instanceof ov),!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=this.direction,i=this.color,s=this.intensity,r=this.shadowBias,n=this.shadowNormalBias,o=this.shadowDepthScale,a=this.shadowDepthRange;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+=`#ifdef ${this._lightTypeDefineName}\n`,e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});\n`,e.compilationString+="#else\n",e.compilationString+=this._declareOutput(t,e)+` = ${this._lightDataUniformName};\n`,e.compilationString+="#endif\n",e.compilationString+=this._declareOutput(i,e)+` = ${this._lightColorUniformName}.rgb;\n`,e.compilationString+=this._declareOutput(s,e)+` = ${this._lightColorUniformName}.a;\n`,(r.hasEndpoints||n.hasEndpoints||o.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,"vec3"),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${this._lightShadowUniformName}.x;\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${this._lightShadowUniformName}.y;\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${this._lightShadowUniformName}.z;\n`)),a.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,"vec2"),e.compilationString+=this._declareOutput(a,e)+` = ${this._lightShadowUniformName};\n`),this}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId))}}ee("BABYLON.LightInformationBlock",kx);class Vx extends wa{constructor(e){super(e,ba.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",xa.AutoDetect),this.registerOutput("output",xa.Color4),this.registerOutput("rgb",xa.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Color4|xa.Vector3|xa.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");const t=this.color,i=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),t.connectedPoint?.isConnected&&(t.connectedPoint.type===xa.Color4||t.connectedPoint.type===xa.Vector4?e.compilationString+=`${this._declareOutput(i,e)} = ${t.associatedVariableName};\n`:e.compilationString+=`${this._declareOutput(i,e)} = vec4(${t.associatedVariableName}, 1.0);\n`,e.compilationString+="#ifdef IMAGEPROCESSINGPOSTPROCESS\n",this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);\n`),e.compilationString+="#else\n",e.compilationString+="#ifdef IMAGEPROCESSING\n",this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);\n`),e.compilationString+=`${i.associatedVariableName} = applyImageProcessing(${i.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+="#endif\n",this.rgb.hasEndpoints&&(e.compilationString+=this._declareOutput(this.rgb,e)+` = ${this.output.associatedVariableName}.xyz;\n`)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\n`,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertInputToLinearSpace=e.convertInputToLinearSpace??!0}}qe([Ba("Convert input to linear space",Sa.Boolean,"ADVANCED")],Vx.prototype,"convertInputToLinearSpace",void 0),ee("BABYLON.ImageProcessingBlock",Vx);class Ux extends wa{constructor(e){super(e,ba.Fragment,!0),this.registerInput("normal",xa.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(xa.Color4|xa.Vector4|xa.Vector3),this.registerInput("tangent",xa.Vector4,!1),this.registerInput("world",xa.Matrix,!1),this.registerOutput("TBN",xa.Object,ba.Fragment,new Nx("TBN",this,ya.Output,Ux,"TBNBlock")),this.registerOutput("row0",xa.Vector3,ba.Fragment),this.registerOutput("row1",xa.Vector3,ba.Fragment),this.registerOutput("row2",xa.Vector3,ba.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return ba.Fragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===Ea.World&&t(e)));i||(i=new Wa("world"),i.setAsSystemValue(Ea.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Wa("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===xa.Vector4&&t(e)));i||(i=new Wa("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){const s=this.normal,r=this.tangent;let n=s.isConnected;s.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(s.connectInputBlock?.name)&&(n=!1);let o=r.isConnected;r.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(r.connectInputBlock?.name)&&(o=!1);const a=n&&o;i.setValue("TBNBLOCK",a,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,a=this.row2;return e.target===ba.Fragment&&(e.compilationString+=`\n // ${this.name}\n vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz;\n vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz);\n vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n mat3 ${r.associatedVariableName} = mat3(${s.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal);\n `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]);\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]);\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]);\n`),e.sharedData.blocksWithDefines.push(this)),this}}ee("BABYLON.TBNBlock",Ux);class Gx extends wa{constructor(e){super(e,ba.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",xa.Vector4,!1),this.registerInput("worldNormal",xa.Vector4,!1),this.registerInput("worldTangent",xa.Vector4,!0),this.registerInput("uv",xa.Vector2,!1),this.registerInput("normalMapColor",xa.Color3,!1),this.registerInput("strength",xa.Float,!1),this.registerInput("viewDirection",xa.Vector3,!0),this.registerInput("parallaxScale",xa.Float,!0),this.registerInput("parallaxHeight",xa.Float,!0),this.registerInput("TBN",xa.Object,!0,ba.VertexAndFragment,new Nx("TBN",this,ya.Input,Ux,"TBNBlock")),this.registerInput("world",xa.Matrix,!0),this.registerOutput("output",xa.Vector4),this.registerOutput("uvOffset",xa.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Wa("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Wa("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let o=null;this.normalMapColor.connectedPoint&&(o=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const a=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const c={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},u=this.TBN;u.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n mat3 vTBN = ${u.associatedVariableName};\n #endif\n `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${r.associatedVariableName}.xyz);\n`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz);\n`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`,e.compilationString+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\n"),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[c,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const d=a&&o?`texture2D(${o}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${a&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${a?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:a?this.viewDirection.associatedVariableName:"vec3(0.)"},c]}),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}qe([Ba("Invert X axis",Sa.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Gx.prototype,"invertX",void 0),qe([Ba("Invert Y axis",Sa.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Gx.prototype,"invertY",void 0),qe([Ba("Use parallax occlusion",Sa.Boolean)],Gx.prototype,"useParallaxOcclusion",void 0),qe([Ba("Object Space Mode",Sa.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Gx.prototype,"useObjectSpaceNormalMap",void 0),ee("BABYLON.PerturbNormalBlock",Gx);class zx extends wa{constructor(e){super(e,ba.Fragment,!0),this.registerInput("value",xa.Float,!0),this.registerInput("cutoff",xa.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard;\n`,this}}ee("BABYLON.DiscardBlock",zx);class Wx extends wa{constructor(e){super(e,ba.Fragment),this.registerOutput("output",xa.Float,ba.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===ba.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+" = gl_FrontFacing ? 1.0 : 0.0;\n",this}}ee("BABYLON.FrontFacingBlock",Wx);class Hx extends wa{constructor(e){super(e,ba.Fragment),this.registerInput("input",xa.AutoDetect,!1),this.registerOutput("dx",xa.BasedOnInput),this.registerOutput("dy",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName});\n`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName});\n`),this}}ee("BABYLON.DerivativeBlock",Hx);class Xx extends wa{constructor(e){super(e,ba.Fragment),this.registerOutput("xy",xa.Vector2,ba.Fragment),this.registerOutput("xyz",xa.Vector3,ba.Fragment),this.registerOutput("xyzw",xa.Vector4,ba.Fragment),this.registerOutput("x",xa.Float,ba.Fragment),this.registerOutput("y",xa.Float,ba.Fragment),this.registerOutput("z",xa.Float,ba.Fragment),this.registerOutput("w",xa.Float,ba.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(const i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name};\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===ba.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}ee("BABYLON.FragCoordBlock",Xx);class Yx extends wa{constructor(e){super(e,ba.Fragment),this.registerOutput("xy",xa.Vector2,ba.Fragment),this.registerOutput("x",xa.Float,ba.Fragment),this.registerOutput("y",xa.Float,ba.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const s of this._outputs)s.hasEndpoints&&(i+=`${this._declareOutput(s,e)} = ${t}.${s.name};\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===ba.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}}ee("BABYLON.ScreenSizeBlock",Yx);class Qx extends wa{constructor(e){super(e,ba.Fragment),this.registerInput("vector",xa.AutoDetect),this.registerInput("worldViewProjection",xa.Matrix),this.registerOutput("output",xa.Vector2),this.registerOutput("x",xa.Float),this.registerOutput("y",xa.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.WorldViewProjection&&t(e)));i||(i=new Wa("worldViewProjection"),i.setAsSystemValue(Ea.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case xa.Vector3:e.compilationString+=`vec4 ${r} = ${s} * vec4(${t.associatedVariableName}, 1.0);\n`;break;case xa.Vector4:e.compilationString+=`vec4 ${r} = ${s} * ${t.associatedVariableName};\n`}return e.compilationString+=`${r}.xy /= ${r}.w;`,e.compilationString+=`${r}.xy = ${r}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${r}.xy;\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${r}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${r}.y;\n`),this}}ee("BABYLON.ScreenSpaceBlock",Qx);class jx extends wa{constructor(e){super(e,ba.Fragment),this.registerInput("input",xa.Vector2),this.registerInput("strength",xa.Float),this.registerInput("center",xa.Vector2),this.registerInput("offset",xa.Vector2),this.registerOutput("output",xa.Vector2),this.registerOutput("x",xa.Float),this.registerOutput("y",xa.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Wa("center");e.value=new ue(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Wa("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Wa("offset");e.value=new ue(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=`\n vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n float ${i} = ${this.strength.associatedVariableName} * length(${t});\n float ${s} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n float ${r} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n vec2 ${n} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n};\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y;\n`),this}}ee("BABYLON.TwirlBlock",jx);class Kx extends wa{constructor(e){super(e,ba.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",xa.Float),this.registerInput("worldPosition",xa.Vector3),this.registerInput("worldNormal",xa.Vector3),this.registerInput("worldTangent",xa.AutoDetect,!0),this.registerOutput("output",xa.Vector4),this.registerOutput("xyz",xa.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||we.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(normal, tangent);\n mat3 TBN = mat3(tangent, biTangent, normal);\n ",s=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ",r=`\n vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {\n ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""}\n ${this.automaticNormalizationNormal?"normal = normalize(normal);":""}\n ${i}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(normal, worlddX);\n vec3 crossY = cross(normal, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * normal) - inToNormal);\n ${s}\n return vec4(result, 0.);\n }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",r,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName});\n`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}qe([Ba("Generate in world space instead of tangent space",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kx.prototype,"generateInWorldSpace",void 0),qe([Ba("Force normalization for the worldNormal input",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kx.prototype,"automaticNormalizationNormal",void 0),qe([Ba("Force normalization for the worldTangent input",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kx.prototype,"automaticNormalizationTangent",void 0),ee("BABYLON.HeightToNormalBlock",Kx);class $x extends wa{constructor(e){super(e,ba.Fragment,!0),this.registerInput("depth",xa.Float,!0),this.registerInput("worldPos",xa.Vector4,!0),this.registerInput("viewProjection",xa.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName};\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n float v = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n gl_FragDepth = v;\n \n `:we.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}ee("BABYLON.FragDepthBlock",$x);class qx extends wa{constructor(e){super(e,ba.Fragment),this.registerInput("worldPosition",xa.Vector4,!1),this.registerInput("viewProjection",xa.Matrix,!1),this.registerInput("worldNormal",xa.AutoDetect,!0),this.registerOutput("depth",xa.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};\n`,e.compilationString+="vec3 vPositionWSM;\n",e.compilationString+="float vDepthMetricSM = 0.0;\n",e.compilationString+="float zSM;\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.);\n`,this}}ee("BABYLON.ShadowMapBlock",qx);class Zx extends wa{constructor(e){super(e,ba.Fragment,!0),this.registerInput("viewDepth",xa.Float,!0),this.registerInput("worldPosition",xa.AutoDetect,!0),this.registerInput("viewNormal",xa.AutoDetect,!0),this.registerInput("reflectivity",xa.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(xa.Vector3|xa.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(xa.Vector3|xa.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(xa.Vector3|xa.Vector4|xa.Color3|xa.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth,r=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="#ifdef PREPASS_DEPTH\r\n",s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=" gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_POSITION\r\n",t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===xa.Vector4?t.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_NORMAL\r\n",i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===xa.Vector4?i.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===xa.Vector4?r.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this}}ee("BABYLON.PrePassOutputBlock",Zx);class Jx extends wa{constructor(e){super(e,ba.VertexAndFragment,!1),this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerInput("view",xa.Matrix,!1,ba.Vertex),this.registerInput("input",xa.AutoDetect,!1,ba.Fragment),this.registerInput("fogColor",xa.AutoDetect,!1,ba.Fragment),this.registerOutput("output",xa.Color3,ba.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.View&&t(e)));i||(i=new Wa("view"),i.setAsSystemValue(Ea.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.FogColor&&t(e)));i||(i=new Wa("fogColor",void 0,xa.Color3),i.setAsSystemValue(Ea.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&$n(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===ba.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});const t=e._getFreeVariableName("fog"),i=this.input,s=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const r=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+="#ifdef FOG\n",e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});\n`,e.compilationString+=this._declareOutput(r,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${s.associatedVariableName}.rgb;\n`,e.compilationString+=`#else\n${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb;\n`,e.compilationString+="#endif\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\n`}return this}}ee("BABYLON.FogBlock",Jx);class eb extends wa{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,we.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ba.Fragment:ba.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ba.Fragment:ba.Vertex}constructor(e){super(e,ba.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerInput("worldNormal",xa.Vector4,!1,ba.Fragment),this.registerInput("cameraPosition",xa.Vector3,!1,ba.Fragment),this.registerInput("glossiness",xa.Float,!0,ba.Fragment),this.registerInput("glossPower",xa.Float,!0,ba.Fragment),this.registerInput("diffuseColor",xa.Color3,!0,ba.Fragment),this.registerInput("specularColor",xa.Color3,!0,ba.Fragment),this.registerInput("view",xa.Matrix,!0),this.registerOutput("diffuseOutput",xa.Color3,ba.Fragment),this.registerOutput("specularOutput",xa.Color3,ba.Fragment),this.registerOutput("shadow",xa.Float,ba.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.CameraPosition&&t(e)));i||(i=new Wa("cameraPosition"),i.setAsSystemValue(Ea.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Jn(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else Zn(s,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;ho(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Xn(this.light,this._lightId,s,e,!0):Yn(s,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,"vec4")&&(e.compilationString+=`${s} = ${t.associatedVariableName};\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==ba.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=`//${this.name}`,i=this.worldPosition;let s=i.associatedVariableName;this.generateOnlyFragmentCode?(s=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${s};\n`,t),e.compilationString+=`${s} = ${i.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):s="v_"+s+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${s});\n`),e.compilationString+="lightingInfo info;\n",e.compilationString+="float shadow = 1.;\n",e.compilationString+="float aggShadow = 0.;\n",e.compilationString+="float numLights = 0.;\n",e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\n`,e.compilationString+="vec3 diffuseBase = vec3(0., 0., 0.);\n",e.compilationString+="vec3 specularBase = vec3(0., 0., 0.);\n",e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:s+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${s}.xyz`}),0===this._lightId&&(e.compilationString+="aggShadow = aggShadow / numLights;\n");const r=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(r,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\n`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\n`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+" = aggShadow;\n"),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}qe([Ba("Generate only fragment code",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:eb._OnGenerateOnlyFragmentCodeChanged}})],eb.prototype,"generateOnlyFragmentCode",void 0),ee("BABYLON.LightBlock",eb);class tb extends wa{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??se.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,ba.VertexAndFragment),this.registerOutput("source",xa.Object,ba.VertexAndFragment,new Nx("source",this,ya.Output,tb,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===ba.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Tl.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}ee("BABYLON.ImageSourceBlock",tb);class ib extends wa{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??se.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _IsPrePassTextureBlock(e){return"PrePassTextureBlock"===e?.getClassName()}get _isSourcePrePass(){return ib._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!ib._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??se.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??se.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?ba.Fragment:ba.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",xa.AutoDetect,!1,ba.VertexAndFragment),this.registerInput("source",xa.Object,!0,ba.VertexAndFragment,new Nx("source",this,ya.Input,tb,"ImageSourceBlock")),this.registerInput("layer",xa.Float,!0),this.registerInput("lod",xa.Float,!0),this.registerOutput("rgba",xa.Color4,ba.Neutral),this.registerOutput("rgb",xa.Color3,ba.Neutral),this.registerOutput("r",xa.Float,ba.Neutral),this.registerOutput("g",xa.Float,ba.Neutral),this.registerOutput("b",xa.Float,ba.Neutral),this.registerOutput("a",xa.Float,ba.Neutral),this.registerOutput("level",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return ba.Fragment;if(!this.uv.isConnected)return ba.VertexAndFragment;if(this.uv.sourceBlock.isInput)return ba.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===ba.Fragment)return ba.Fragment;if(e.target===ba.Vertex)return ba.VertexAndFragment;if(e.target===ba.Neutral||e.target===ba.VertexAndFragment){const t=e.ownerBlock;if(t.target===ba.Fragment)return ba.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return ba.VertexAndFragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected)if(e.mode===il.PostProcess){const i=e.getBlockByPredicate((e=>"uv"===e.name&&t(e)));i&&i.connectTo(this)}else{const i=e.mode===il.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===i&&t(e)));s||(s=new Wa("uv"),s.setAsAttribute(i)),s.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==ba.Fragment}_injectVertexCode(e){const t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0));\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,e.compilationString+="#endif\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){let t=e;const i=this._texture?._texture?.is2DArray??!1,s=this._texture?._texture?.is3D??!1;return(i||s)&&(t=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),t}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){const t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix});\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix});\n`,e.compilationString+="#endif\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ba.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==ba.Fragment?this._generateTextureLookup(e):e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix});\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ba.Fragment)return;return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===ba.Fragment)return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i);let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===ba.Vertex||this._fragmentOnly||e.target===ba.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===ba.Fragment||this._isMixed&&e.target===ba.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==ba.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&(this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!Tl.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}ee("BABYLON.TextureBlock",ib);class sb extends wa{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??se.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ba.Fragment:ba.VertexAndFragment)}constructor(e){super(e,ba.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Wa("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.World&&t(e)));i||(i=new Wa("world"),i.setAsSystemValue(Ea.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.View&&t(e)));i||(i=new Wa("view"),i.setAsSystemValue(Ea.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();s&&s.getTextureMatrix&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===s.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===s.coordinatesMode,!0),i.setValue(this._defineCubicName,3===s.coordinatesMode||6===s.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===s.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===s.coordinatesMode,!0),i.setValue(this._definePlanarName,2===s.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===s.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===s.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,s){const r=this._getTexture();if(i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize)){const t=r;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===ba.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`,t+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\n`,t+="#endif\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${r});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${r});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\n`;return s||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\n`,i+="\n #else\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\n`,i+="#endif\n",i}writeOutputs(e,t){let i="";if(e.target===ba.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${this._declareOutput(s,e)} = ${t}.${s.name};\n`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Tl.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=mm.Parse(e.texture,t,i):this.texture=Vo.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}qe([Ba("Generate only fragment code",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:sb._OnGenerateOnlyFragmentCodeChanged}})],sb.prototype,"generateOnlyFragmentCode",void 0),ee("BABYLON.ReflectionTextureBaseBlock",sb);class rb extends sb{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,we.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,we.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?ba.Fragment:ba.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ba.Fragment:ba.Vertex}constructor(e){super(e),this.registerInput("position",xa.AutoDetect,!1,ba.Vertex),this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerInput("worldNormal",xa.Vector4,!1,ba.Fragment),this.registerInput("world",xa.Matrix,!1,ba.Vertex),this.registerInput("cameraPosition",xa.Vector3,!1,ba.Fragment),this.registerInput("view",xa.Matrix,!1,ba.Fragment),this.registerOutput("rgb",xa.Color3,ba.Fragment),this.registerOutput("rgba",xa.Color4,ba.Fragment),this.registerOutput("r",xa.Float,ba.Fragment),this.registerOutput("g",xa.Float,ba.Fragment),this.registerOutput("b",xa.Float,ba.Fragment),this.registerOutput("a",xa.Float,ba.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=(()=>!0)){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.CameraPosition&&t(e)));i||(i=new Wa("cameraPosition"),i.setAsSystemValue(Ea.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==ba.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}ee("BABYLON.ReflectionTextureBlock",rb);class nb extends wa{constructor(e){super(e,ba.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",xa.AutoDetect,!1,ba.VertexAndFragment),this.registerOutput("depth",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?ba.VertexAndFragment:ba.Fragment:ba.VertexAndFragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===xa.Vector3?"3":t.type===xa.Vector4?"4":"2"))),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ba.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}else this.uv.ownerBlock.target!==ba.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ba.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target,ba.Fragment,e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==ba.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.isConnectedInFragmentShader))){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}qe([Ba("Use non linear depth",Sa.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],nb.prototype,"useNonLinearDepth",void 0),qe([Ba("Store Camera space Z",Sa.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],nb.prototype,"storeCameraSpaceZ",void 0),qe([Ba("Force 32 bits float",Sa.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e?.disableDepthRenderer()}})],nb.prototype,"force32itsFloat",void 0),ee("BABYLON.SceneDepthBlock",nb);class ob extends wa{constructor(e){super(e,ba.VertexAndFragment,!0),this.registerInput("worldPosition",xa.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return ba.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const s=e.getScene(),r=!!(t.clipPlane??s.clipPlane),n=!!(t.clipPlane2??s.clipPlane2),o=!!(t.clipPlane3??s.clipPlane3),a=!!(t.clipPlane4??s.clipPlane4),l=!!(t.clipPlane5??s.clipPlane5),h=!!(t.clipPlane6??s.clipPlane6);i.setValue("CLIPPLANE",r,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",a,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){i&&In(e,t,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==ba.Fragment){const i=this.worldPosition;return e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),void e._emitUniformFromString("vClipPlane6","vec4")}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}ee("BABYLON.ClipPlanesBlock",ob);class ab extends wa{get texture(){return null}set texture(e){}constructor(e,t=ba.VertexAndFragment){super(e,t,!1),this.registerOutput("position",xa.Object,ba.VertexAndFragment,new Nx("position",this,ya.Output,tb,"ImageSourceBlock")),this.registerOutput("depth",xa.Object,ba.VertexAndFragment,new Nx("depth",this,ya.Output,tb,"ImageSourceBlock")),this.registerOutput("normal",xa.Object,ba.VertexAndFragment,new Nx("normal",this,ya.Output,tb,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==ba.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const i=t.getScene().enablePrePassRenderer();if(!i)return;const s=i.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[i.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[i.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[i.getIndex(6)]))}}ee("BABYLON.PrePassTextureBlock",ab);class lb extends wa{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==ba.VertexAndFragment)return t.target;if(e.connectedPoint.target!==ba.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,ba.Neutral),this._endpoints=[],this.registerInput("input",xa.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some((e=>e.output.isConnectedInFragmentShader))}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}ee("BABYLON.NodeMaterialTeleportInBlock",lb);class hb extends wa{constructor(e){super(e,ba.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",xa.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName};\n`)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}ee("BABYLON.NodeMaterialTeleportOutBlock",hb);class cb extends el{constructor(e){super(e)}getClassName(){return"AddBlock"}_buildBlock(e){return super._buildBlock(e),e.compilationString+=this._declareOutput(this.output,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\n`,this}}ee("BABYLON.AddBlock",cb);class ub extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.AutoDetect),this.registerInput("factor",xa.Float),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\n`,this}}ee("BABYLON.ScaleBlock",ub);class db extends wa{constructor(e){super(e,ba.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}qe([Ba("Minimum",Sa.Float)],db.prototype,"minimum",void 0),qe([Ba("Maximum",Sa.Float)],db.prototype,"maximum",void 0),ee("BABYLON.ClampBlock",db);class _b extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[0].excludedConnectionPointTypes.push(xa.Vector2),this._inputs[1].excludedConnectionPointTypes.push(xa.Float),this._inputs[1].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xa.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\n`,this}}ee("BABYLON.CrossBlock",_b);class pb extends wa{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),this._outputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=this._declareOutput(t,e)+";\n"})),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=t.connectedPoint?.ownerBlock?.samplerName??t.associatedVariableName:e.compilationString+=t.associatedVariableName,s=!0})),this._outputs.forEach(((t,i)=>{(i>0||s)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=ba[e.target],e.inParameters?.forEach(((e,t)=>{const i=xa[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,xa.Object,!0,ba.VertexAndFragment,new Nx(e.name,this,ya.Input,tb,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),e.outParameters?.forEach(((e,t)=>{this.registerOutput(e.name,xa[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),e.inLinkedConnectionTypes?.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.CameraPosition&&t(e)));i||(i=new Wa("cameraPosition"),i.setAsSystemValue(Ea.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\n`,this}}ee("BABYLON.ViewDirectionBlock",Cb);class Eb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("worldNormal",xa.Vector4),this.registerInput("viewDirection",xa.Vector3),this.registerInput("bias",xa.Float),this.registerInput("power",xa.Float),this.registerOutput("fresnel",xa.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new Cb("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Wa("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Wa("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}ee("BABYLON.FresnelBlock",Eb);class Ab extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}ee("BABYLON.MaxBlock",Ab);class Pb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}ee("BABYLON.MinBlock",Pb);class Rb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xa.Float),this._inputs[1].excludedConnectionPointTypes.push(xa.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\n`,this}}ee("BABYLON.DistanceBlock",Rb);class Ib extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerOutput("output",xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName});\n`,this}}ee("BABYLON.LengthBlock",Ib);class Mb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName};\n`,this}}ee("BABYLON.NegateBlock",Mb);class Ob extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerInput("power",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}ee("BABYLON.PowBlock",Ob);class Db extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("seed",xa.AutoDetect),this.registerOutput("output",xa.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4|xa.Color3|xa.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy);\n`,this}}ee("BABYLON.RandomNumberBlock",Db);class wb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("x",xa.Float),this.registerInput("y",xa.Float),this.registerOutput("output",xa.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`,this}}ee("BABYLON.ArcTan2Block",wb);class Nb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerInput("edge0",xa.Float),this.registerInput("edge1",xa.Float),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName});\n`,this}}ee("BABYLON.SmoothStepBlock",Nb);class Fb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===xa.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName});\n`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName};\n`,this}}ee("BABYLON.ReciprocalBlock",Fb);class Bb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerInput("reference",xa.AutoDetect),this.registerInput("distance",xa.Float),this.registerInput("replacement",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xa.Float),this._inputs[1].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[3].excludedConnectionPointTypes.push(xa.Float),this._inputs[3].excludedConnectionPointTypes.push(xa.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+";\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\n`,e.compilationString+="} else {\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\n`,e.compilationString+="}\n",this}}ee("BABYLON.ReplaceColorBlock",Bb);class Lb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerInput("steps",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(xa.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\n`,this}}var kb;ee("BABYLON.PosterizeBlock",Lb),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(kb||(kb={}));class Vb extends wa{constructor(e){super(e,ba.Neutral),this.kind=kb.SawTooth,this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case kb.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`;break;case kb.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`;break;case kb.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}ee("BABYLON.WaveBlock",Vb);class Ub{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class Gb extends wa{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,ba.Neutral),this.colorSteps=[new Ub(0,Ce.Black()),new Ub(1,Ce.White())],this.onValueChangedObservable=new X,this.registerInput("gradient",xa.AutoDetect),this.registerOutput("output",xa.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Float|xa.Vector2|xa.Vector3|xa.Vector4|xa.Color3|xa.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){const t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=this._declareOutput(t,e)+" = vec3(0., 0., 0.);\n");const i=e._getFreeVariableName("gradientTempColor"),s=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)};\n`,e.compilationString+=`float ${s};\n`;let r=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==xa.Float&&(r+=".x");for(let t=1;t!0)){if(!this.intensity.isConnected){const e=new Wa("Refraction intensity",ba.Fragment,xa.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.View&&t(e)));i||(i=new Wa("view"),i.setAsSystemValue(Ea.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){super.bind(e,t,i);const s=this._getTexture();if(!s)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),e.setMatrix(this._refractionMatrixName,s.getRefractionTextureMatrix());let r=1;s.isCube||s.depth&&(r=s.depth);const n=this.volumeIndexOfRefraction.connectInputBlock?.value??this.indexOfRefractionConnectionPoint.connectInputBlock?.value??1.5;e.setFloat4(this._vRefractionInfosName,s.level,1/n,r,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset,1/n);const o=s.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,xe.Log2(o)),s.boundingBoxSize){const t=s;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=mm.Parse(e.texture,t,i):this.texture=Vo.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}qe([Ba("Link refraction to transparency",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],tT.prototype,"linkRefractionWithTransparency",void 0),qe([Ba("Invert refraction Y",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],tT.prototype,"invertRefractionY",void 0),qe([Ba("Use thickness as depth",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],tT.prototype,"useThicknessAsDepth",void 0),ee("BABYLON.RefractionBlock",tT);class iT extends wa{constructor(e){super(e,ba.Fragment),this._isUnique=!0,this.registerInput("thickness",xa.Float,!1,ba.Fragment),this.registerInput("tintColor",xa.Color3,!0,ba.Fragment),this.registerInput("translucencyIntensity",xa.Float,!0,ba.Fragment),this.registerInput("translucencyDiffusionDist",xa.Color3,!0,ba.Fragment),this.registerInput("refraction",xa.Object,!0,ba.Fragment,new Nx("refraction",this,ya.Input,tT,"RefractionBlock")),this.registerInput("dispersion",xa.Float,!0,ba.Fragment),this.registerOutput("subsurface",xa.Object,ba.Fragment,new Nx("subsurface",this,ya.Output,iT,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Wa("SubSurface thickness",ba.Fragment,xa.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,s){let r="";const n=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",a=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",l=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t?.refraction.isConnected?t?.refraction.connectedPoint?.ownerBlock:null,c=h?.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",u=h?.intensity.isConnected?h.intensity.associatedVariableName:"1.",d=h?.view.isConnected?h.view.associatedVariableName:"",_=t?.dispersion.isConnected?t?.dispersion.associatedVariableName:"0.0";return r+=h?.getCode(e)??"",r+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${n});\n vec4 vTintColor = vec4(${o}, ${c});\n vec3 vSubSurfaceIntensity = vec3(${u}, ${a}, 0.);\n float dispersion = ${_};\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${i?._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${i?._cubeSamplerName},\n ${i?._vReflectionFilteringInfoName},\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n surfaceAlbedo,\n #endif\n #ifdef SS_REFRACTION\n ${s}.xyz,\n viewDirectionW,\n ${d},\n ${h?._vRefractionInfosName??""},\n ${h?._refractionMatrixName??""},\n ${h?._vRefractionMicrosurfaceInfosName??""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${h?._defineLODRefractionAlpha??"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${h?._defineLinearSpecularRefraction??"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n ${h?._2DSamplerName??""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${h?._vRefractionFilteringInfoName??""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #ifdef SS_DISPERSION\n dispersion,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${l},\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n`,r}_buildBlock(e){return e.target===ba.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}ee("BABYLON.SubSurfaceBlock",iT);const sT={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class rT extends wa{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,we.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ba.Fragment:ba.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ba.Fragment:ba.Vertex}constructor(e){super(e,ba.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Ce.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerInput("worldNormal",xa.Vector4,!1,ba.Fragment),this.registerInput("view",xa.Matrix,!1),this.registerInput("cameraPosition",xa.Vector3,!1,ba.Fragment),this.registerInput("perturbedNormal",xa.Vector4,!0,ba.Fragment),this.registerInput("baseColor",xa.Color3,!0,ba.Fragment),this.registerInput("metallic",xa.Float,!1,ba.Fragment),this.registerInput("roughness",xa.Float,!1,ba.Fragment),this.registerInput("ambientOcc",xa.Float,!0,ba.Fragment),this.registerInput("opacity",xa.Float,!0,ba.Fragment),this.registerInput("indexOfRefraction",xa.Float,!0,ba.Fragment),this.registerInput("ambientColor",xa.Color3,!0,ba.Fragment),this.registerInput("reflection",xa.Object,!0,ba.Fragment,new Nx("reflection",this,ya.Input,Zb,"ReflectionBlock")),this.registerInput("clearcoat",xa.Object,!0,ba.Fragment,new Nx("clearcoat",this,ya.Input,Jb,"ClearCoatBlock")),this.registerInput("sheen",xa.Object,!0,ba.Fragment,new Nx("sheen",this,ya.Input,$b,"SheenBlock")),this.registerInput("subsurface",xa.Object,!0,ba.Fragment,new Nx("subsurface",this,ya.Input,iT,"SubSurfaceBlock")),this.registerInput("anisotropy",xa.Object,!0,ba.Fragment,new Nx("anisotropy",this,ya.Input,qb,"AnisotropyBlock")),this.registerInput("iridescence",xa.Object,!0,ba.Fragment,new Nx("iridescence",this,ya.Input,eT,"IridescenceBlock")),this.registerOutput("ambientClr",xa.Color3,ba.Fragment),this.registerOutput("diffuseDir",xa.Color3,ba.Fragment),this.registerOutput("specularDir",xa.Color3,ba.Fragment),this.registerOutput("clearcoatDir",xa.Color3,ba.Fragment),this.registerOutput("sheenDir",xa.Color3,ba.Fragment),this.registerOutput("diffuseInd",xa.Color3,ba.Fragment),this.registerOutput("specularInd",xa.Color3,ba.Fragment),this.registerOutput("clearcoatInd",xa.Color3,ba.Fragment),this.registerOutput("sheenInd",xa.Color3,ba.Fragment),this.registerOutput("refraction",xa.Color3,ba.Fragment),this.registerOutput("lighting",xa.Color3,ba.Fragment),this.registerOutput("shadow",xa.Float,ba.Fragment),this.registerOutput("alpha",xa.Float,ba.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.CameraPosition&&t(e)));i||(i=new Wa("cameraPosition"),i.setAsSystemValue(Ea.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.View&&t(e)));i||(i=new Wa("view"),i.setAsSystemValue(Ea.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===Vm.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Vm.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const r=e.getScene();if(r.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&lc.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Jn(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else Zn(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,no(r,i)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;ho(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Xn(this.light,this._lightId,s,e,!0):Yn(s,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const r=this._scene.ambientColor;r&&e.setColor3("ambientFromScene",r);const n=s.useRightHandedSystem===(null!=s._mirroredCameraPosition);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=this.indexOfRefraction.connectInputBlock?.value??1.5,a=Math.pow((o-1)/(o+1),2);this._metallicReflectanceColor.scaleToRef(a*this._metallicF0Factor,Ae.Color3[0]);const l=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,Ae.Color3[0],l),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,"vec4")&&(e.compilationString+=`${s} = ${t.associatedVariableName};\n`);const r=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;r&&(r.viewConnectionPoint=this.view),e.compilationString+=r?.handleVertexSide(e)??"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\n",e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n`,t}_buildBlock(e){super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=Sm(this._scene));const t=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==ba.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const i=`//${this.name}`,s=this.perturbedNormal;let r=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${r};\n`,i),e.compilationString+=`${r} = ${this.worldPosition.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n",e.compilationString+="#endif\n"):r="v_"+r,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity","vec4"),t?.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}.xyz);\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\n`,e.compilationString+=`vec3 normalW = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const n=this.anisotropy.isConnected?this.anisotropy.connectedPoint?.ownerBlock:null;n&&(n.worldPositionConnectionPoint=this.worldPosition,n.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=n.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,n?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:t?._vReflectionFilteringInfoName??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?this.sheen.connectedPoint?.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"}]});const a=this.iridescence.isConnected?this.iridescence.connectedPoint?.ownerBlock:null;e.compilationString+=eT.GetCode(a),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const l=this.clearcoat.isConnected?this.clearcoat.connectedPoint?.ownerBlock:null,h=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,c=this.perturbedNormal.isConnected&&(this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected,u=this.anisotropy.isConnected&&(this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;let d=c||!this.perturbedNormal.isConnected&&u;e.compilationString+=Jb.GetCode(e,l,t,r,h,d,this.worldNormal.associatedVariableName),h&&(d=l?.worldTangent.isConnected??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:d?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const _=this.subsurface.isConnected?this.subsurface.connectedPoint?.ownerBlock:null,p=this.subsurface.isConnected?(this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock:null;p&&(p.viewConnectionPoint=this.view,p.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=iT.GetCode(e,_,t,r),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:p?._define3DName??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:p?._defineLODRefractionAlpha??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:p?._defineLinearSpecularRefraction??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:p?._defineOppositeZ??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+="#endif\n";const f=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let m=Vm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===m.indexOf(".")&&(m+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:f+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:m}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:r},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]});for(const t of this._outputs)if(t.hasEndpoints){const i=sT[t.name];if(i){const[s,r]=i;r&&(e.compilationString+=`#if ${r}\n`),e.compilationString+=`${this._declareOutput(t,e)} = ${s};\n`,r&&(e.compilationString+="#else\n",e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.);\n`,e.compilationString+="#endif\n")}else we.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}qe([Ba("Direct lights",Sa.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],rT.prototype,"directIntensity",void 0),qe([Ba("Environment lights",Sa.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],rT.prototype,"environmentIntensity",void 0),qe([Ba("Specular highlights",Sa.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],rT.prototype,"specularIntensity",void 0),qe([Ba("Light falloff",Sa.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Vm.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Vm.LIGHTFALLOFF_GLTF},{label:"Standard",value:Vm.LIGHTFALLOFF_STANDARD}]})],rT.prototype,"lightFalloff",void 0),qe([Ba("Alpha Testing",Sa.Boolean,"OPACITY")],rT.prototype,"useAlphaTest",void 0),qe([Ba("Alpha CutOff",Sa.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],rT.prototype,"alphaTestCutoff",void 0),qe([Ba("Alpha blending",Sa.Boolean,"OPACITY")],rT.prototype,"useAlphaBlending",void 0),qe([Ba("Radiance over alpha",Sa.Boolean,"RENDERING",{notifiers:{update:!0}})],rT.prototype,"useRadianceOverAlpha",void 0),qe([Ba("Specular over alpha",Sa.Boolean,"RENDERING",{notifiers:{update:!0}})],rT.prototype,"useSpecularOverAlpha",void 0),qe([Ba("Specular anti-aliasing",Sa.Boolean,"RENDERING",{notifiers:{update:!0}})],rT.prototype,"enableSpecularAntiAliasing",void 0),qe([Ba("Realtime filtering",Sa.Boolean,"RENDERING",{notifiers:{update:!0}})],rT.prototype,"realTimeFiltering",void 0),qe([Ba("Realtime filtering quality",Sa.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],rT.prototype,"realTimeFilteringQuality",void 0),qe([Ba("Energy Conservation",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"useEnergyConservation",void 0),qe([Ba("Radiance occlusion",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"useRadianceOcclusion",void 0),qe([Ba("Horizon occlusion",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"useHorizonOcclusion",void 0),qe([Ba("Unlit",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"unlit",void 0),qe([Ba("Force normal forward",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"forceNormalForward",void 0),qe([Ba("Generate only fragment code",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:rT._OnGenerateOnlyFragmentCodeChanged}})],rT.prototype,"generateOnlyFragmentCode",void 0),qe([Ba("Debug mode",Sa.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],rT.prototype,"debugMode",void 0),qe([Ba("Split position",Sa.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],rT.prototype,"debugLimit",void 0),qe([Ba("Output factor",Sa.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],rT.prototype,"debugFactor",void 0),ee("BABYLON.PBRMetallicRoughnessBlock",rT);class nT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(xa.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}ee("BABYLON.ModBlock",nT);class oT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("row0",xa.Vector4),this.registerInput("row1",xa.Vector4),this.registerInput("row2",xa.Vector4),this.registerInput("row3",xa.Vector4),this.registerOutput("output",xa.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Wa("row0");e.value=new _e(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Wa("row1");e.value=new _e(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Wa("row2");e.value=new _e(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Wa("row3");e.value=new _e(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName});\n`,this}}var aT,lT,hT,cT,uT,dT;ee("BABYLON.MatrixBuilder",oT),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(aT||(aT={}));class _T extends wa{constructor(e){super(e,ba.Neutral),this.condition=aT.LessThan,this.registerInput("a",xa.Float),this.registerInput("b",xa.Float),this.registerInput("true",xa.AutoDetect,!0),this.registerInput("false",xa.AutoDetect,!0),this.registerOutput("output",xa.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=xa.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case aT.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${s};\n`;break;case aT.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${s};\n`;break;case aT.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${s};\n`}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${aT[this.condition]};\n`}}ee("BABYLON.ConditionalBlock",_T);class pT extends wa{constructor(e){super(e,ba.Neutral),this.octaves=6,this.registerInput("seed",xa.AutoDetect),this.registerInput("chaos",xa.AutoDetect,!0),this.registerInput("offsetX",xa.Float,!0),this.registerInput("offsetY",xa.Float,!0),this.registerInput("offsetZ",xa.Float,!0),this.registerOutput("output",xa.Float),this._inputs[0].acceptedConnectionPointTypes.push(xa.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(xa.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;const t=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode","\n\n float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise(in vec2 x, in vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise(in vec3 x, in vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }","// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,"\n float fbm(in vec2 st, in vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise(st, chaos);\n st *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm(in vec3 x, in vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n for (int i = 0; i < OCTAVES; ++i) {\n value += amplitude * cloudNoise(x, chaos);\n x = x * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }".replace(/fbm/gi,t).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const i=e._getFreeVariableName("st"),s=this.seed.connectedPoint?.type===xa.Vector2?"vec2":"vec3";e.compilationString+=`${s} ${i} = ${this.seed.associatedVariableName};\n`,this.offsetX.isConnected&&(e.compilationString+=`${i}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`),this.offsetY.isConnected&&(e.compilationString+=`${i}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`),this.offsetZ.isConnected&&"vec3"===s&&(e.compilationString+=`${i}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`);let r="";return r=this.chaos.isConnected?this.chaos.associatedVariableName:this.seed.connectedPoint?.type===xa.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${t}(${i}, ${r});\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}qe([Ba("Octaves",Sa.Int)],pT.prototype,"octaves",void 0),ee("BABYLON.CloudBlock",pT);class fT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("seed",xa.Vector2),this.registerInput("offset",xa.Float),this.registerInput("density",xa.Float),this.registerOutput("output",xa.Float),this.registerOutput("cells",xa.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 seed, float offset){\n mat2 m = mat2(15.27, 47.63, 99.41, 89.98);\n vec2 uv = fract(sin(m * seed) * 46839.32);\n return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);\n }\n ";e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 g = floor(seed * density);\n vec2 f = fract(seed * density);\n float t = 8.0;\n vec3 res = vec3(8.0, 0.0, 0.0);\n\n for(int y=-1; y<=1; y++)\n {\n for(int x=-1; x<=1; x++)\n {\n vec2 lattice = vec2(x,y);\n vec2 randomOffset = voronoiRandom(lattice + g, offset);\n float d = distance(lattice + randomOffset, f);\n if(d < res.x)\n {\n res = vec3(d, randomOffset.x, randomOffset.y);\n outValue = res.x;\n cells = res.y;\n }\n }\n }\n }\n ",e._emitFunction("voronoi",t,"// Voronoi");const i=e._getFreeVariableName("tempOutput"),s=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0;\n`,e.compilationString+=`float ${s} = 0.0;\n`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${s});\n`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i};\n`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${s};\n`),this}}ee("BABYLON.VoronoiNoiseBlock",fT);class mT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==ba.VertexAndFragment)return t.target;if(e.connectedPoint.target!==ba.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName};\n`,this}}ee("BABYLON.ElbowBlock",mT);class gT extends wa{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??se.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){return this.sourceY.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}get textureZ(){return this.sourceZ?.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){return this._getImageSourceBlock(this.sourceY)?.samplerName??null}get samplerZName(){return this._getImageSourceBlock(this.sourceZ)?.samplerName??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??se.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??se.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,ba.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",xa.AutoDetect,!1),this.registerInput("normal",xa.AutoDetect,!1),this.registerInput("sharpness",xa.Float,!0),this.registerInput("source",xa.Object,!0,ba.VertexAndFragment,new Nx("source",this,ya.Input,tb,"ImageSourceBlock")),this.registerInput("sourceY",xa.Object,!0,ba.VertexAndFragment,new Nx("sourceY",this,ya.Input,tb,"ImageSourceBlock")),t||this.registerInput("sourceZ",xa.Object,!0,ba.VertexAndFragment,new Nx("sourceZ",this,ya.Input,tb,"ImageSourceBlock")),this.registerOutput("rgba",xa.Color4,ba.Neutral),this.registerOutput("rgb",xa.Color3,ba.Neutral),this.registerOutput("r",xa.Float,ba.Neutral),this.registerOutput("g",xa.Float,ba.Neutral),this.registerOutput("b",xa.Float,ba.Neutral),this.registerOutput("a",xa.Float,ba.Neutral),this.registerOutput("level",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,s=this.samplerZName??t,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),a=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),c=e._getFreeVariableName("uvx"),u=e._getFreeVariableName("uvy"),d=e._getFreeVariableName("uvz");e.compilationString+=`\n vec3 ${h} = ${this.normal.associatedVariableName}.xyz;\n\n vec2 ${c} = ${this.position.associatedVariableName}.yz;\n vec2 ${u} = ${this.position.associatedVariableName}.zx;\n vec2 ${d} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${c}.xy = ${c}.yx;\n\n if (${h}.x >= 0.0) {\n ${c}.x = -${c}.x;\n }\n if (${h}.y < 0.0) {\n ${u}.y = -${u}.y;\n }\n if (${h}.z < 0.0) {\n ${d}.x = -${d}.x;\n }\n `),e.compilationString+=`\n vec4 ${n} = texture2D(${t}, ${c});\n vec4 ${o} = texture2D(${i}, ${u});\n vec4 ${a} = texture2D(${s}, ${d});\n \n // blend weights\n vec3 ${l} = pow(abs(${h}), vec3(${r}));\n\n // blend and return\n vec4 ${this._tempTextureRead} = (${n}*${l}.x + ${o}*${l}.y + ${a}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); \n `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!Tl.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}qe([Ba("Project as cube",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],gT.prototype,"projectAsCube",void 0),ee("BABYLON.TriPlanarBlock",gT);class vT extends gT{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dpdx"),n=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),a=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),d=e._getFreeVariableName("y");e.compilationString+=`\n // grab coord derivatives for texturing\n vec3 ${r} = dFdx(${this.position.associatedVariableName}.xyz);\n vec3 ${n} = dFdy(${this.position.associatedVariableName}.xyz);\n vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ivec3 ${a} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) :\n (${o}.y>${o}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine minor axis (in x; yz are following axis)\n ivec3 ${l} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) :\n (${o}.y<${o}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine median axis (in x; yz are following axis)\n ivec3 ${h} = ivec3(3) - ${l} - ${a};\n \n // project+fetch\n vec4 ${c} = textureGrad( ${t}, vec2( ${this.position.associatedVariableName}[${a}.y], ${this.position.associatedVariableName}[${a}.z]), \n vec2(${r}[${a}.y],${r}[${a}.z]), \n vec2(${n}[${a}.y],${n}[${a}.z]) );\n vec4 ${u} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), \n vec2(${r}[${h}.y],${r}[${h}.z]),\n vec2(${n}[${h}.y],${n}[${h}.z]) );\n \n // blend factors\n vec2 ${d} = vec2(${o}[${a}.x],${o}[${h}.x]);\n // make local support\n ${d} = clamp( (${d}-0.5773)/(1.0-0.5773), 0.0, 1.0 );\n // shape transition\n ${d} = pow( ${d}, vec2(${s}/8.0) );\n // blend and return\n vec4 ${this._tempTextureRead} = (${c}*${d}.x + ${u}*${d}.y) / (${d}.x + ${d}.y);\n `}}ee("BABYLON.BiPlanarBlock",vT);class xT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.Matrix),this.registerOutput("output",xa.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName});\n`,this}}ee("BABYLON.MatrixDeterminantBlock",xT);class bT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.Matrix),this.registerOutput("output",xa.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName});\n`,this}}ee("BABYLON.MatrixTransposeBlock",bT),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(lT||(lT={}));class TT extends wa{constructor(e){super(e,ba.Neutral),this.attributeType=lT.None,this.registerInput("input",xa.AutoDetect),this.registerInput("fallback",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{if(this.attributeType)return;const t=e.ownerBlock;if(t instanceof Wa&&t.isAttribute)switch(t.name){case"color":this.attributeType=lT.VertexColor;break;case"normal":this.attributeType=lT.Normal;break;case"tangent":this.attributeType=lT.Tangent;break;case"uv":this.attributeType=lT.UV1;break;case"uv2":this.attributeType=lT.UV2;break;case"uv3":this.attributeType=lT.UV3;break;case"uv4":this.attributeType=lT.UV4;break;case"uv5":this.attributeType=lT.UV5;break;case"uv6":this.attributeType=lT.UV6}else if(t instanceof Lx)switch(this.input.connectedPoint?.name){case"normalOutput":this.attributeType=lT.Normal;break;case"tangentOutput":this.attributeType=lT.Tangent;break;case"uvOutput":this.attributeType=lT.UV1}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case lT.VertexColor:t="VERTEXCOLOR_NME";break;case lT.Normal:t="NORMAL";break;case lT.Tangent:t="TANGENT";break;case lT.UV1:t="UV1";break;case lT.UV2:t="UV2";break;case lT.UV3:t="UV3";break;case lT.UV4:t="UV4";break;case lT.UV5:t="UV5";break;case lT.UV6:t="UV6"}const i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t}\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\n`,t&&(e.compilationString+="#else\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\n`,e.compilationString+="#endif\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??lT.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\n`,e}}qe([Ba("Attribute lookup",Sa.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:lT.None},{label:"Normal",value:lT.Normal},{label:"Tangent",value:lT.Tangent},{label:"Vertex Color",value:lT.VertexColor},{label:"UV1",value:lT.UV1},{label:"UV2",value:lT.UV2},{label:"UV3",value:lT.UV3},{label:"UV4",value:lT.UV4},{label:"UV5",value:lT.UV5},{label:"UV6",value:lT.UV6}]})],TT.prototype,"attributeType",void 0),ee("BABYLON.MeshAttributeExistsBlock",TT),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(hT||(hT={}));class yT extends wa{constructor(e){super(e,ba.Neutral),this.type=hT.EaseInOutSine,this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[0].excludedConnectionPointTypes.push(xa.Object),this._inputs[0].excludedConnectionPointTypes.push(xa.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if("float"===t)return this._duplicateEntryDirect(e);const i=parseInt(t.replace("vec",""));let s=`\n vec${i} ret = vec${i}(0.0);\n `;for(let t=1;t<=i;t++)s+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return s+="return ret;\n",s}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="",r="";switch(this.input.type){case xa.Float:r="float";break;case xa.Vector2:r="vec2";break;case xa.Vector3:case xa.Color3:r="vec3";break;case xa.Vector4:case xa.Color4:r="vec4"}switch(s=hT[this.type]+"_"+r,this.type){case hT.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case hT.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case hT.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case hT.EaseInQuad:i="return v * v";break;case hT.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case hT.EaseInOutQuad:{const e="VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInCubic:i="return v * v * v";break;case hT.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,r);break}case hT.EaseInOutCubic:{const e="VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInQuart:i="return v * v * v * v";break;case hT.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,r);break}case hT.EaseInOutQuart:{const e="VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInQuint:i="return v * v * v * v * v";break;case hT.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,r);break}case hT.EaseInOutQuint:{const e="VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInExpo:{const e="VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)";i=this._duplicateVector(e,r);break}case hT.EaseOutExpo:{const e="VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)";i=this._duplicateVector(e,r);break}case hT.EaseInOutExpo:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,r);break}case hT.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,r);break}case hT.EaseInOutCirc:{const e="VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case hT.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,r);break}case hT.EaseInOutBack:{const e="VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))";i=this._duplicateVector(e,r);break}case hT.EaseOutElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0";i=this._duplicateVector(e,r);break}case hT.EaseInOutElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0";i=this._duplicateVector(e,r);break}}return e._emitFunction(s,`${r} ${s}(${r} v) {${i};}\n`,""),e.compilationString+=this._declareOutput(t,e)+` = ${s}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${hT[this.type]};\n`}}ee("BABYLON.CurveBlock",yT);class ST{optimize(e,t){}}class CT{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(void 0!==i)return i.get(t)}set(e,t,i){let s=this.mm.get(e);void 0===s&&this.mm.set(e,s=new Map),s.set(t,i)}}class ET{get standalone(){return this._options?.standalone??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){return this._options?.doNotInjectCode??!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??se.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new CT,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add((e=>{const t=e.subMesh?.getMesh();t&&!this._meshes.has(t)&&this._meshes.set(t,t.onDisposeObservable.add((e=>{const t=this._subMeshToEffect.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value;t?.getMesh()===e&&(this._subMeshToEffect.delete(t),this._deleteDepthWrapperEffect(t))}}))),this._subMeshToEffect.get(e.subMesh)?.[0]!==e.effect&&(this._subMeshToEffect.set(e.subMesh,[e.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(e.subMesh))}))}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach((e=>{e.mainDrawWrapper.effect?.dispose()})),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){const s=this._subMeshToDepthWrapper.mm.get(e)?.get(t);if(!s)return null;let r=s.drawWrapper[i];return r||(r=s.drawWrapper[i]=new Fi(this._scene.getEngine()),r.setEffect(s.mainDrawWrapper.effect,s.mainDrawWrapper.defines)),r}isReadyForSubMesh(e,t,i,s,r){return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,s))&&(this._makeEffect(e,t,i,r)?.isReady()??!1)}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;e.onDisposeObservable.remove(i)}}_makeEffect(e,t,i,s){const r=this._scene.getEngine(),n=this._subMeshToEffect.get(e);if(!n)return null;const[o,a]=n;let l=this._subMeshToDepthWrapper.get(e,i);if(!l){const t=new Fi(r);t.defines=e._getDrawWrapper(a)?.defines??null,l={drawWrapper:[],mainDrawWrapper:t,depthDefines:"",token:ns()},l.drawWrapper[s]=t,this._subMeshToDepthWrapper.set(e,i,l)}const h=t.join("\n");if(l.mainDrawWrapper.effect&&h===l.depthDefines)return l.mainDrawWrapper.effect;l.depthDefines=h;const c=o.getUniformNames().slice();let u=o.vertexSourceCodeBeforeMigration,d=o.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const e=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",t=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",i=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",s="#include",r="#include";u=o.shaderLanguage===ui.GLSL?u.replace(/void\s+?main/g,`\n${r}\nvoid main`):u.replace(/@vertex/g,`\n${r}\n@vertex`),u=u.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,e),u=-1!==u.indexOf("#define SHADOWDEPTH_METRIC")?u.replace(/#define SHADOWDEPTH_METRIC/g,t):u.replace(/}\s*$/g,t+"\n}"),u=u.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const n=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,a=-1!==d.indexOf("#define SHADOWDEPTH_FRAGMENT");let l="";n?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,i):l=i+"\n",d=d.replace(/void\s+?main/g,Ti.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\nvoid main"),a?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,s):l+=s+"\n",l&&(d=d.replace(/}\s*$/g,l+"}")),c.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}l.mainDrawWrapper.effect=r.createEffect({vertexSource:u,fragmentSource:d,vertexToken:l.token,fragmentToken:l.token},{attributes:o.getAttributesNames(),uniformsNames:c,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:h+"\n"+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters(),shaderLanguage:o.shaderLanguage},r);for(let e=0;e0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof de){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach((e=>{t.push(Array.from(e))})),t}return[]}static OmitZeroLengthPredicate(e,t,i){const s=[];return t.subtract(e).lengthSquared()>0&&s.push([e,t]),i.subtract(t).lengthSquared()>0&&s.push([t,i]),e.subtract(i).lengthSquared()>0&&s.push([i,e]),0===s.length?null:s}static OmitDuplicatesPredicate(e,t,i,s){const r=[];return BT._SearchInPoints(e,t,s)||r.push([e,t]),BT._SearchInPoints(t,i,s)||r.push([t,i]),BT._SearchInPoints(i,e,s)||r.push([i,e]),0===r.length?null:r}static _SearchInPoints(e,t,i){for(const s of i)for(let i=0;i{const r=e.getVerticesData(ys.PositionKind),n=e.getIndices();if(r&&n)for(let o=0,a=0;o[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?BT.ToVector3Array(e):e;const i=ge.Vector3[0];let s=0;for(let e=0;e{e.length>t?BT.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{s.push(e)})):(s.push(e.point1),s.push(e.point2))})),s}static SegmentizeLineBySegmentCount(e,t){const i="number"==typeof e[0]?BT.ToVector3Array(e):e,s=BT.GetLineLength(i)/t;return BT.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const a=e.length;for(let t=0;t[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],a=Vd(e,t,i,s);for(const e of a){for(const t of e.paths){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,r);o.push(e)}if(n)for(const t of e.holes){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,r);o.push(e)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(4*e.length);for(let i=0,s=0;i{BT.DisposeEmptyColorsTexture()})),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const t=this._scene.activeCamera;if(!t)throw Error("GreasedLinePluginMaterial requires an active camera.");{const i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}const i=ge.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}const t=ge.Vector4[0];t.x=BT.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=ge.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=BT.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",this.colorsTexture??FT.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===dT.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return kT.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){const e={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:`\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ${uT.COLOR_MODE_SET}.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ${uT.COLOR_MODE_ADD}.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ${uT.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.);\n #endif\n if (grlColorMode == ${uT.COLOR_MODE_SET}.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ${uT.COLOR_MODE_ADD}.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ${uT.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n `}:null}dispose(){this.colorsTexture?.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&s===e.length&&!i){const t=BT.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else this.colorsTexture?.dispose(),this.colorsTexture=BT.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}else this.colorsTexture?.dispose()}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){super.parse(e,t,i);const s=e.greasedLineMaterialOptions;this.colorsTexture?.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=BT.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):BT.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){const t=e;t.colorsTexture?.dispose(),this._colors&&(t.colorsTexture=BT.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}kT.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",ee(`BABYLON.${kT.GREASED_LINE_MATERIAL_NAME}`,kT);bi.ShadersStore.greasedLinePixelShader="precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}\n";bi.ShadersStore.greasedLineVertexShader="precision highp float;\n#include\nattribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";class VT extends Yu{constructor(e,t,i){const s=[`COLOR_DISTRIBUTION_TYPE_LINE ${dT.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${dT.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${uT.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${uT.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${uT.COLOR_MODE_MULTIPLY}.`],r=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&s.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(s.push("GREASED_LINE_CAMERA_FACING"),r.push("grl_previousAndSide","grl_nextAndCounters")):(r.push("grl_slopes"),r.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:r,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:s}),this._color=Ce.White(),this._colorsDistributionType=dT.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:FT.DEFAULT_COLOR};const n=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?FT.DEFAULT_WIDTH_ATTENUATED:FT.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Ce.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??dT.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??Wo.NEAREST_NEAREST,this.colorMode=i.colorMode??uT.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new ue(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=BT.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),n.onDisposeObservable.add((()=>{BT.DisposeEmptyColorsTexture()}))}dispose(){this._colorsTexture?.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new ue(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&s===e.length&&!i){const t=BT.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else this._colorsTexture?.dispose(),this.colorsTexture=BT.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}else this._colorsTexture?.dispose()}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",BT.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",BT.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",BT.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??FT.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){const s=e.greasedLineMaterialOptions;this._colorsTexture?.dispose(),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),s.colors?this.colorsTexture=BT.CreateColorsTexture(`${this.name}-colors-texture`,s.colors,this.colorsSampling,this.getScene()):this.colorsTexture=BT.PrepareEmptyColorsTexture(t),this._cameraFacing=s.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const UT=[new Ce(.98,.26,.38),new Ce(.47,.75,.3),new Ce(0,.26,.77),new Ce(.97,.6,.76),new Ce(.19,.63,.78),new Ce(.98,.8,.6),new Ce(.65,.43,.15),new Ce(.15,.47,.22),new Ce(.67,.71,.86),new Ce(.09,.46,.56),new Ce(.8,.98,.02),new Ce(.39,.29,.13),new Ce(.53,.63,.06),new Ce(.95,.96,.41),new Ce(1,.72,.94),new Ce(.63,.08,.31),new Ce(.66,.96,.95),new Ce(.22,.14,.19),new Ce(.14,.65,.59),new Ce(.93,1,.68),new Ce(.93,.14,.44),new Ce(.47,.86,.67),new Ce(.85,.07,.78),new Ce(.53,.64,.98),new Ce(.43,.37,.56),new Ce(.71,.65,.25),new Ce(.66,.19,.01),new Ce(.94,.53,.12),new Ce(.41,.44,.44),new Ce(.24,.71,.96),new Ce(.57,.28,.56),new Ce(.44,.98,.42)];var GT;!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(GT||(GT={}));class zT extends Oa{constructor(){super(...arguments),this.DBG_MODE=GT.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class WT extends gc{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new zT;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new Ce(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Ce(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Ce(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Ce(.8,.8,.8),this.vertexColor=t.vertexColor??new Ce(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Ce(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Ce(.5,.5,.5),this._materialColor=WT.MaterialColors[WT._PluginCount++%WT.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().webGLVersion)return we.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=GT.VERTICES&&this._mode!=GT.TRIANGLES&&this._mode!=GT.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||we.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif"}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(UV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(UV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}}static Reset(){this._PluginCount=0,this.MaterialColors=UT}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){const t=e.getVerticesDataKinds(),s=e.getIndices(),r={};for(const i of t)r[i]=e.getVerticesData(i);i=function(){e.setIndices(s);for(const i of t){const t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,r[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let e=0;enew XT(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return yt.Parse((()=>new XT(e.name,t)),e,t,i)}}ee("BABYLON.GaussianSplattingMaterial",XT),Object.defineProperty(yc.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new PT(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Vm.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new PT(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});class YT{constructor(e,t){this.radius=e,this.theta=t,this.radius=e,this.theta=t}getClassName(){return"Polar"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t}add(e){const t=new YT(0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t){return this.radius+=e,this.theta+=t,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t}subtract(e){const t=new YT(0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i){return i.radius=this.radius-e,i.theta=this.theta-t,i}subtractFromFloats(e,t){const i=new YT(0,0);return this.subtractFromFloatsToRef(e,t,i),i}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t}multiply(e){const t=new YT(0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t}divide(e){const t=new YT(0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new YT(this.radius,this.theta)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this}copyFromFloats(e,t){return this.radius=e,this.theta=t,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t}scale(e){const t=new YT(0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t){return this.radius=e,this.theta=t,this}setAll(e){return this.set(e,e),this}toVector2ToRef(e){const t=this.radius*Math.cos(this.theta),i=this.radius*Math.sin(this.theta);return e.set(t,i),e}toVector2(){const e=new ue(0,0);return this.toVector2ToRef(e)}static FromVector2ToRef(e,t){const i=Math.sign(e.y)*Math.acos(e.x/e.length());return t.radius=e.length(),t.theta=i,t}static FromVector2(e){const t=new YT(0,0);return YT.FromVector2ToRef(e,t),t}static FromArray(e){return new YT(e[0],e[1])}}class QT{constructor(e,t,i){this.radius=e,this.theta=t,this.phi=i,this.radius=e,this.theta=t,this.phi=i}getClassName(){return"Spherical"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta,this.phi]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t.phi=this.phi+e.phi,t}add(e){const t=new QT(0,0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t,i){return this.radius+=e,this.theta+=t,this.phi+=i,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t.phi=this.phi-e.phi,t}subtract(e){const t=new QT(0,0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i,s){return s.radius=this.radius-e,s.theta=this.theta-t,s.phi=this.phi-i,s}subtractFromFloats(e,t,i){const s=new QT(0,0,0);return this.subtractFromFloatsToRef(e,t,i,s),s}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t.phi=this.phi*e.phi,t}multiply(e){const t=new QT(0,0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t.phi=this.phi/e.phi,t}divide(e){const t=new QT(0,0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new QT(this.radius,this.theta,this.phi)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this.phi=e.phi,this}copyFromFloats(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t.phi=this.phi*e,t}scale(e){const t=new QT(0,0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}setAll(e){return this.set(e,e,e),this}toVector3ToRef(e){const t=this.radius*Math.sin(this.theta)*Math.cos(this.phi),i=this.radius*Math.cos(this.theta),s=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,s),e}toVector3(){const e=new de(0,0,0);return this.toVector3ToRef(e)}static FromVector3ToRef(e,t){return t.radius=e.length(),t.theta=Math.acos(e.y/t.radius),t.phi=Math.atan2(e.z,e.x),t}static FromVector3(e){const t=new QT(0,0,0);return QT.FromVector3ToRef(e,t),t}static FromArray(e){return new QT(e[0],e[1],e[2])}}class jT{constructor(e,t=2,i=3,s=1,r=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=s,this._height=r,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,s=0;for(;e>0;)i/=t,s+=i*(e%t),e=~~(e/t);return s}}function KT(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)}}`}function $T(e,t){return`{X: ${e._x.toFixed(t)} Y: ${e._y.toFixed(t)} Z: ${e._z.toFixed(t)}}`}function qT(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)} Z: ${e.z.toFixed(t)} W: ${e.w.toFixed(t)}}`}function ZT(e,t,i,s,r){let n=null,o=null,a=null;try{let l;n=new e.Decoder,o=new e.DecoderBuffer,o.Init(t,t.byteLength);const h=n.GetEncodedGeometryType(o);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=n.DecodeBufferToMesh(o,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),r=4*i,h=e._malloc(r);try{n.GetTrianglesUInt32Array(t,r,h);const o=new Uint32Array(i);o.set(new Uint32Array(e.HEAPF32.buffer,h,i)),s(o)}finally{e._free(h)}a=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=n.DecodeBufferToPointCloud(o,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());a=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=a.num_points(),u=(t,i,s,n)=>{const o=n.data_type(),a=n.num_components(),l=n.normalized(),h=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[o];if(!d)throw new Error(`Invalid data type ${o}`);const _=c*a,p=_*d.typedArrayConstructor.BYTES_PER_ELEMENT,f=e._malloc(p);try{t.GetAttributeDataArrayForAllPoints(i,n,o,p,f);const e=new d.typedArrayConstructor(d.heap.buffer,f,_);r(s,e.slice(),a,u,h,l)}finally{e._free(f)}};if(i)for(const e in i){const t=i[e],s=n.GetAttributeByUniqueId(a,t);u(n,a,e,s)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=n.GetAttributeId(a,t[e]);if(-1!==i){const t=n.GetAttribute(a,i);u(n,a,e,t)}}}return c}finally{a&&e.destroy(a),o&&e.destroy(o),n&&e.destroy(n)}}function JT(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary}),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=ZT(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,s,r,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:s,byteStride:r,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}class ey{static get DecoderAvailable(){const e=ey.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return ey._Default||(ey._Default=new ey),ey._Default}constructor(e=ey.DefaultNumWorkers){const t=ey.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,s="number"==typeof e?e:e.numWorkers,r=s&&"function"==typeof Worker&&"function"==typeof URL,n=r||!r&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?hs.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):hs.LoadFileAsync(hs.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?hs.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=o.wasmBinaryPromise.then((e=>{const t=`${ZT}(${JT})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new Jm(s,(()=>function(e,t,i){return new Promise(((s,r)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",o),r(t)},o=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",o),s(e))};e.addEventListener("error",n),e.addEventListener("message",o);const a=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:a}},[a])}))}(new Worker(i),e,o.url)))})):this._decoderModulePromise=o.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await hs.LoadBabylonScriptAsync(o.url)}return await(i=e,s=t.jsModule,new Promise((e=>{(s||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,s}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}_decodeMeshAsync(e,t,i){const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((r,n)=>{e.push(((e,o)=>{let a=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),n(t),o()},c=t=>{const s=t.data;switch(s.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),r({indices:a,attributes:l,totalVertices:s.totalVertices}),o();break;case"indices":a=s.data;break;case"attribute":l.push({kind:s.kind,data:s.data,size:s.size,byteOffset:s.byteOffset,byteStride:s.byteStride,normalized:(n=s.kind,u=s.normalized,i&&void 0!==i[n]?(u!==i[n]&&we.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):u)})}var n,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=s.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const r=[],n=ZT(e.module,s,t,(e=>{i=e}),((e,t,i,s,n,o)=>{r.push({kind:e,data:t,size:i,byteOffset:s,byteStride:n,normalized:o})}));return{indices:i,attributes:r,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const r=await this._decodeMeshAsync(i,s),n=new _n(e,t);r.indices&&n.setIndices(r.indices);for(const e of r.attributes)n.setVerticesBuffer(new ys(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,r){const n=await this._decodeMeshAsync(i,s,r),o=new _n(e,t);n.indices&&o.setIndices(n.indices);for(const e of n.attributes)o.setVerticesBuffer(new ys(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this._decodeMeshAsync(e,t),s=new cn;i.indices&&(s.indices=i.indices);for(const e of i.attributes){const t=ys.GetFloatData(e.data,e.size,ys.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);s.set(t,e.kind)}return s}}ey.Configuration={decoder:{wasmUrl:`${hs._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${hs._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${hs._DefaultCdnUrl}/draco_decoder_gltf.js`}},ey.DefaultNumWorkers=ey.GetDefaultNumWorkers(),ey._Default=null;class ty{static get Default(){return ty._Default||(ty._Default=new ty),ty._Default}constructor(){const e=ty.Configuration.decoder;this._decoderModulePromise=hs.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then((()=>{const n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,s,r),n}))}}ty.Configuration={decoder:{url:`${hs._DefaultCdnUrl}/meshopt_decoder.js`}},ty._Default=null;let iy=0;class sy{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){return new sy(this.pos.clone(),this.normal.clone(),this.uv?.clone(),this.vertColor?.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new sy(de.Lerp(this.pos,e.pos,t),de.Lerp(this.normal,e.normal,t),this.uv&&e.uv?ue.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?Ee.Lerp(this.vertColor,e.vertColor,t):void 0)}}class ry{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(0===s.lengthSquared()||0===r.lengthSquared())return null;const n=de.Normalize(de.Cross(s,r));return new ry(n,de.Dot(n,e))}clone(){return new ry(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let n=0;const o=[];let a,l;for(a=0;ary.EPSILON?1:0;n|=t,o.push(t)}switch(n){case 0:(de.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const t=[],i=[];for(a=0;a=3&&(n=new ny(t,e.shared),n.plane&&s.push(n)),i.length>=3&&(n=new ny(i,e.shared),n.plane&&r.push(n));break}}}}ry.EPSILON=1e-5;class ny{constructor(e,t){this.vertices=e,this.shared=t,this.plane=ry.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new ny(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class oy{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new oy;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map((e=>e.clone())),e}invert(){for(let e=0;ee.clone())),e.copyTransformAttributes(this),e}union(e){const t=new oy(this.clone()._polygons),i=new oy(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),ay._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new oy(this._polygons),i=new oy(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new oy(this.clone()._polygons),i=new oy(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),ay._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new oy(this._polygons),i=new oy(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new oy(this.clone()._polygons),i=new oy(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),ay._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new oy(this._polygons),i=new oy(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map((e=>{e.flip()}))}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const s=this._polygons,r=[],n=[],o=[];let a=null,l=null;const h=de.Zero(),c=de.Zero(),u=ue.Zero(),d=new Ee(0,0,0,0),_=[0,0,0],p={};let f;for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId)),this.toVertexData((e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),a=o[e.shared.meshId][e.shared.subMeshId]}),(()=>{a.indexStart=Math.min(n,a.indexStart),a.indexEnd=Math.max(n,a.indexEnd),n++})).applyToMesh(s),i){let e,t=0;s.subMeshes=[];for(const i in o){e=-1;for(const r in o[i])a=o[i][r],ln.CreateFromIndices(a.materialIndex+t,a.indexStart,a.indexEnd-a.indexStart+1,s),e=Math.max(a.materialIndex,e);t+=++e}}return s}toMesh(e,t=null,i,s){const r=this.buildMeshGeometry(e,i,s);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r}}bi.ShadersStore.meshUVSpaceRendererVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}";bi.ShadersStore.meshUVSpaceRendererPixelShader="precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";bi.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";bi.ShadersStore.meshUVSpaceRendererMaskerPixelShader="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";bi.ShadersStore.meshUVSpaceRendererFinaliserPixelShader="precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";bi.ShadersStore.meshUVSpaceRendererFinaliserVertexShader="precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}\n";class ly{static _GetShader(e){if(!e._meshUVSpaceRendererShader){const t=new Yu("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererShader?.dispose(),e._meshUVSpaceRendererShader=null})),e._meshUVSpaceRendererShader=t}return e._meshUVSpaceRendererShader}static _GetMaskShader(e){if(!e._meshUVSpaceRendererMaskShader){const t=new Yu("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"]});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererMaskShader?.dispose(),e._meshUVSpaceRendererMaskShader=null})),e._meshUVSpaceRendererMaskShader=t}return e._meshUVSpaceRendererMaskShader}static _IsRenderTargetTexture(e){return void 0!==e.renderList}constructor(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this.clearColor=new Ee(0,0,0,0),this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1,...i}}isReady(){this.texture||this._createDiffuseRTT();const e=ly._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=this._maskTexture?.isReadyForRendering()??!0,i=this._finalPostProcess?.isReady()??!0;return e&&t&&i}renderTexture(e,t,i,s,r=0){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),ly._IsRenderTargetTexture(this.texture)){const n=this._createProjectionMatrix(t,i,s,r),o=ly._GetShader(this._scene);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",n),this.texture.render()}}clear(){if(ly._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const e=this._scene.getEngine();e.bindFramebuffer(this.texture.renderTarget),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this.texture.renderTarget)}if(this._finalPostProcess?.inputTexture){const e=this._scene.getEngine();e.bindFramebuffer(this._finalPostProcess?.inputTexture),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this._finalPostProcess?.inputTexture)}}dispose(){this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,this._maskTexture?.dispose(),this._maskTexture=null,this._finalPostProcess?.dispose(),this._finalPostProcess=null}_configureUserCreatedRTT(){this._configureUserCreatedTexture=!1,ly._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,ly._GetShader(this._scene)),this.texture.onClearObservable.add((()=>{})),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,ly._GetShader(this._scene)),this.texture=e,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),e.addPostProcess(this._finalPostProcess))}_createMaskTexture(){this._maskTexture||(this._maskTexture=new pl(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,0,!1,2,void 0,void 0,void 0,6),this._maskTexture.clearColor=new Ee(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,ly._GetMaskShader(this._scene)),this._maskTexture.refreshRate=pl.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new qa(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,1,this._scene.getEngine(),!1,null,this._options.textureType),this._finalPostProcess.onApplyObservable.add((e=>{e.setTexture("maskTextureSampler",this._maskTexture),e.setFloat2("textureSize",this._options.width,this._options.height)})))}_createRenderTargetTexture(e,t){const i=new pl(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.renderParticles=!1,i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce((()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add((()=>{}))})),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,s=0){const r=-Math.atan2(t.z,t.x)-Math.PI/2,n=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,n),a=e.add(t.scale(.5*i.z)),l=fe.RotationYawPitchRoll(r,o,s).multiply(fe.Translation(a.x,a.y,a.z)),h=fe.Invert(l),c=fe.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),u=fe.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return h.multiply(c).multiply(u)}}bo._TrailMeshParser=(e,t)=>hy.Parse(e,t);class hy extends bo{constructor(e,t,i,s=1,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=s,this._length=r,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<=this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=de.Zero(),this._sectionNormalVectors[e]=de.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new cn,t=[],i=[],s=[],r=[];let n=de.Zero();n=this._generator instanceof Sn&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<=this._sectionPolygonPointsCount;e++){const i=e!==this._sectionPolygonPointsCount?e*o:0;t.push(n.x+Math.cos(i)*this.diameter,n.y+Math.sin(i)*this.diameter,n.z),r.push(e/this._sectionPolygonPointsCount,0)}for(let e=1;e<=this._length;e++){for(let i=0;i<=this._sectionPolygonPointsCount;i++){const s=i!==this._sectionPolygonPointsCount?i*o:0;t.push(n.x+Math.cos(s)*this.diameter,n.y+Math.sin(s)*this.diameter,n.z),r.push(i/this._sectionPolygonPointsCount,e/this._length)}const i=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let e=0;e<=this._sectionPolygonPointsCount;e++)s.push(i+e,i+e+this._sectionPolygonPointsCount,i+e+this._sectionPolygonPointsCount+1),s.push(i+e,i+e+this._sectionPolygonPointsCount+1,i+e+1)}cn.ComputeNormals(t,s,i),e.positions=t,e.normals=i,e.indices=s,e.uvs=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(ys.PositionKind),t=this.getVerticesData(ys.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*(this._sectionPolygonPointsCount+1);i{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,s)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,s()}))};us.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,dy.QUADRATIC,new wy(e.mesh)}}var dy,_y,py,fy,my,gy,vy,xy,by,Ty,yy,Sy,Cy,Ey,Ay,Py,Ry;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(dy||(dy={}));class Iy{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class My{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new Oy,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class Oy{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,s,r,n,o,a,l){return this.data[e]*this.data[r]*this.data[l]+this.data[i]*this.data[s]*this.data[a]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[a]-this.data[t]*this.data[s]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new Oy;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new Oy(Oy.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class Dy{constructor(e,t){this.vertexId=e,this.triangleId=t}}class wy{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=K}simplify(e,t){this._initDecimatedMesh(),us.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),s=this._triangles[t];if(s&&!(s.error[3]>i||s.deleted||s.isDirty))for(let e=0;e<3;++e)if(s.error[e]{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)continue;n.q=o.q.add(n.q),n.updatePosition(a);const c=this._references.length;r=this._updateTriangles(n,n,t,r),r=this._updateTriangles(n,o,i,r);const u=this._references.length-c;if(u<=n.triangleCount){if(u)for(let e=0;en-r<=s))}),0)};us.Run(this.decimationIterations,(e=>{n-r<=s?e.breakLoop():o(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(ys.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=e=>{if(i)for(let t=0;t{if(!s)return;const t=e+n.verticesStart,i=de.FromArray(s,3*t),r=o(i)||new My(i,this._vertices.length);r.originalOffsets.push(t),r.id===this._vertices.length&&this._vertices.push(r),a.push(r.id)}),(()=>{us.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,(e=>{if(!r)return;const t=3*(n.indexStart/3+e),i=r[t+0],s=r[t+1],o=r[t+2],l=this._vertices[a[i-n.verticesStart]],h=this._vertices[a[s-n.verticesStart]],c=this._vertices[a[o-n.verticesStart]],u=new Iy([l,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){us.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=de.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(Oy.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-de.Dot(t.normal,t._vertices[0].position)))}),(()=>{us.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,s,r;for(i=0;i{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const _=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[s.originalOffset+e];let i=s._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(s._vertices[e].id+i+p)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(ys.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(ys.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(ys.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(ys.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach((e=>{ln.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),ln.AddToMesh(v.materialIndex,p,d,_,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new bo(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,s,r){for(let n=0;n.999)return!0;const d=de.Cross(c,u).normalize();if(s[n]=!1,de.Dot(d,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let s=0;sBy.Parse(e,t);class By extends Fy{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(BT.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach((t=>{for(let i=0;i{i+=2*e.length,s+=2*(e.length-3),r+=4*e.length/3,n+=8*e.length/3}));const o=new Float32Array(i),a=i>65535?new Uint32Array(s):new Uint16Array(s),l=new Float32Array(r),h=new Float32Array(n),c=new Float32Array(n);let u=0,d=0,_=0,p=0,f=0;e.forEach((e=>{const i=BT.GetLineLengthArray(e),s=i[i.length-1];for(let i=0,s=0;s>1]/s;if(this._options.uvs)for(let e=0;eLy.Parse(e,t);class Ly extends Fy{constructor(e,t,i,s){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(BT.ConvertPoints(i.points),i,!!s)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const r=Ly._ConvertToRibbonPath(e,n.ribbonOptions,this._scene.useRightHandedSystem,i?i[t]:i);s=this._preprocess(r,s,n)}))}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const s=[],r=[],n=e[0];for(let t=0;t2)for(let e=0;e0&&(o[0]+=1,o[1]+=1),r.push(o[1]+(e%2!=0?i:0),o[0],o[2]),a&&r.push(o[0],o[1]+(e%2!=0?i:0),o[2])}else for(let e=0;ee.y&&e.x>e.z?i?Ly._RightHandedForwardReadOnlyQuaternion:Ly._LeftHandedForwardReadOnlyQuaternion:Ly._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(o,o,o),r.push(c.add(h)),n.push(c.subtract(h))}s||(r.push(a[a.length-1].add(h)),n.push(a[a.length-1].subtract(h)))}return[r,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&1!==i?.x?e.y===t.y?Ly.DIRECTION_XZ:e.z===t.z?Ly.DIRECTION_XY:Ly.DIRECTION_XZ:Ly.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];Xe.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),Xe.DeepCopy(i,s,["instance"],void 0,!0);const n=new Ly(e,this._scene,s,r);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,s=e.name,r=e.pathOptions;return new Ly(s,t,i,r)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let s=0;s{o+=e.length/3}));const a=Uy(o,t.widths??[],t.widthDistribution),l=i?.colors?Gy(o,i.colors,i.colorDistribution,i.color??FT.DEFAULT_COLOR):void 0,h={points:n,updatable:t.updatable,widths:a,lazy:t.lazy,ribbonOptions:t.ribbonOptions,uvs:t.uvs,colorPointers:t.colorPointers};if(h.ribbonOptions&&h.ribbonOptions.pointsMode===_y.POINTS_MODE_POINTS&&(h.ribbonOptions.width=i.width??h.ribbonOptions.width??FT.DEFAULT_WIDTH),t.instance)if(r=t.instance,r instanceof Ly)r.addPoints(n,h);else{const e=r.widths;if(e){const t=e.slice();for(const e of a)t.push(e);r.widths=t}else r.widths=a;if(r.addPoints(n),t.uvs){const e=r.uvs;if(e){const i=new Float32Array(e.length+t.uvs.length);i.set(e,0),i.set(t.uvs,e.length),r.uvs=i}else r.uvs=t.uvs}}else if(r=h.ribbonOptions?new Ly(e,s,h):new By(e,s,h),i){const n={materialType:i.materialType,dashCount:i.dashCount,dashOffset:i.dashOffset,dashRatio:i.dashRatio,resolution:i.resolution,sizeAttenuation:i.sizeAttenuation,useColors:i.useColors,useDash:i.useDash,visibility:i.visibility,width:i.width,color:i.color,colorMode:i.colorMode,colorsSampling:i.colorsSampling,colorDistributionType:i.colorDistributionType,colors:l,cameraFacing:!t.ribbonOptions,colorsTexture:i.colorsTexture};if(i.createAndAssignMaterial){const i=ky(e,n,s);r.material=i,t.ribbonOptions?.facesMode===py.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING&&(i.backFaceCulling=!1)}}if(l&&t.instance&&t.instance.greasedLineMaterial){const e=t.instance.greasedLineMaterial.colors;if(e){const i=e.concat(l);t.instance.greasedLineMaterial.setColors(i,r.isLazy())}}return r}function Uy(e,t,i,s=1,r=1){const n=e-t.length/2,o=[];if(n<0)return t.slice(0,2*e);if(n>0){if(t.length%2!=0&&t.push(s),i===gy.WIDTH_DISTRIBUTION_START_END){const e=Math.floor(t.length/2);for(let i=0,s=0;i0){if(i===my.COLOR_DISTRIBUTION_START_END){const e=Math.floor(t.length/2);for(let i=0;i=this._thinInstanceDataStorage.instancesCount)return!1;const s=this._thinInstanceDataStorage.matrixData;return t.copyToArray(s,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},bo.prototype.thinInstanceSetAttributeAt=function(e,t,i,s=!0){return e===ys.ColorKind&&(e=ys.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),s&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(bo.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),bo.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const s=new Ts(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(s.createVertexBuffer(e+t,4*t,4));return s},bo.prototype.thinInstanceSetBuffer=function(e,t,i=0,s=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,s),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,s))):(e===ys.ColorKind&&(e=ys.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new ys(this.getEngine(),t,e,!s,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},bo.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===ys.ColorKind&&(e=ys.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},bo.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===ys.ColorKind&&(e=ys.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},bo.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){return this.isConnected?this._connectedPoint?._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=vy.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new X,this.onDisconnectionObservable=new X,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===xy.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==vy.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?xy.Compatible:xy.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return xy.TypeIncompatible;let s=i,r=t;return this.direction===by.Input&&(s=t,r=i),s.isAnAncestorOf(r)?xy.HierarchyIssue:xy.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t0){if(!this._outputs.some((e=>e.hasEndpoints))&&!this.isDebug)return!1;this.outputs.forEach((e=>e._resetCounters()))}this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&we.Log(`Building ${this.name} [${this.getClassName()}]`);const t=zt.Now;this._buildBlock(e),this._buildExecutionTime=zt.Now-t;for(const t of this._outputs)for(const i of t.endpoints){const t=i.ownerBlock;t&&t.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((e=>{const t=this.inputs.find((t=>t.name===e.name));if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)t.value=e.value;else{const i=te(e.valueType);i&&(t.value=i.FromArray(e.value))}})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`);const r=this.getClassName();if("GeometryInputBlock"===r){const e=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e});\n`}else s+=`var ${this._codeVariableName} = new BABYLON.${r}("${this.name}");\n`;s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=te(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}qe([st("comment")],Wy.prototype,"comments",void 0);class Hy extends Wy{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",vy.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}ee("BABYLON.GeometryOutputBlock",Hy),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(Ty||(Ty={}));class Xy{constructor(){this._rotationMatrix=new fe,this._scalingMatrix=new fe,this._positionMatrix=new fe,this._scalingRotationMatrix=new fe,this._transformMatrix=new fe,this._tempVector3=new de,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case Ty.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?de.FromArray(this.geometryContext.positions,3*i):de.Zero();case Ty.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?de.FromArray(this.geometryContext.normals,3*i):de.Zero();case Ty.Colors:return this.geometryContext&&this.geometryContext.colors?_e.FromArray(this.geometryContext.colors,4*i):_e.Zero();case Ty.Tangents:return this.geometryContext&&this.geometryContext.tangents?_e.FromArray(this.geometryContext.tangents,4*i):_e.Zero();case Ty.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?ue.FromArray(this.geometryContext.uvs,2*i):ue.Zero();case Ty.UV2:return this.geometryContext&&this.geometryContext.uvs2?ue.FromArray(this.geometryContext.uvs2,2*i):ue.Zero();case Ty.UV3:return this.geometryContext&&this.geometryContext.uvs3?ue.FromArray(this.geometryContext.uvs3,2*i):ue.Zero();case Ty.UV4:return this.geometryContext&&this.geometryContext.uvs4?ue.FromArray(this.geometryContext.uvs4,2*i):ue.Zero();case Ty.UV5:return this.geometryContext&&this.geometryContext.uvs5?ue.FromArray(this.geometryContext.uvs5,2*i):ue.Zero();case Ty.UV6:return this.geometryContext&&this.geometryContext.uvs6?ue.FromArray(this.geometryContext.uvs6,2*i):ue.Zero();case Ty.VertexID:return i;case Ty.FaceID:return this.executionContext.getExecutionFaceIndex();case Ty.LoopID:return this.executionContext.getExecutionLoopIndex();case Ty.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Ty.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Ty.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case vy.Vector2:return new ue(i,i);case vy.Vector3:return new de(i,i,i);case vy.Vector4:return new _e(i,i,i,i)}return null}adaptInput(e,t,i){if(!e.isConnected)return e.value||i;const s=e.getConnectedValue(this);if(e._connectedPoint?.type===t)return s;switch(t){case vy.Vector2:return new ue(s,s);case vy.Vector3:return new de(s,s,s);case vy.Vector4:return new _e(s,s,s,s)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;for(const t of this.noContextualData)e+=`Contextual input ${Ty[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,s,r){fe.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),fe.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),fe.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${Ty[this._contextualSource]};\n`;const t=[];let i="";switch(this.type){case vy.Float:case vy.Int:i=`${this.value}`;break;case vy.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case vy.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case vy.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),this.type!==vy.Float&&this.type!==vy.Int||t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=te(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}ee("BABYLON.GeometryInputBlock",Yy);class Qy extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",vy.Float,!0,1),this.registerInput("width",vy.Float,!0,0),this.registerInput("height",vy.Float,!0,0),this.registerInput("depth",vy.Float,!0,0),this.registerInput("subdivisions",vy.Int,!0,1),this.registerInput("subdivisionsX",vy.Int,!0,0),this.registerInput("subdivisionsY",vy.Int,!0,0),this.registerInput("subdivisionsZ",vy.Int,!0,0),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new Yy("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new Yy("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new Yy("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),s=this.subdivisionsX.getConnectedValue(e),r=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),s&&(t.widthSegments=s),r&&(t.heightSegments=r),n&&(t.depthSegments=n),Tu(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Qy.prototype,"evaluateContext",void 0),ee("BABYLON.BoxBlock",Qy);class jy{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=jy._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new X,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return hs.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise((t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){const i=e&&e.editorURL?e.editorURL:jy.EditorURL;hs.LoadBabylonScript(i,(()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const s=zt.Now;this._initializeBlock(this.outputBlock,i);const r=new Xy;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=jy._BuildIdGenerator++),this._buildExecutionTime=zt.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new bo(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const t of e.blocks){const e=te(t.customType);if(e){const s=new e;s._deserialize(t),i[t.id]=s,this.attachedBlocks.push(s)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,s=t._tempEntryPointUniqueId;if(s){const e=i[s];e&&e.attachToEndpoint(t)}}for(let s=0;se.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const e of s)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const e in i)r[e]=i[e].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+="// Connections\n",s+=this.outputBlock._dumpCodeForOutputConnections(e),s+="// Output nodes\n",s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`,s+="nodeGeometry.build();\n"),s}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new Qy("Box");e.autoConfigure();const t=new Hy("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=yt.Clone((()=>new jy(e)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:yt.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new jy(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=yt.Parse((()=>new jy(e.name)),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(jy.CreateDefault("blank")):new Promise(((s,r)=>{const n=new At;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(o.nodeGeometry);t||(t=yt.Parse((()=>new jy(e)),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),s(t)}catch(e){r(e)}}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}jy._BuildIdGenerator=0,jy.EditorURL=`${hs._DefaultCdnUrl}/v${gn.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,jy.SnippetUrl="https://snippet.babylonjs.com",qe([st()],jy.prototype,"name",void 0),qe([st("comment")],jy.prototype,"comment",void 0);class Ky extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=K,this.registerInput("geometry",vy.Geometry),this.registerOutput("output",vy.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e),i=[],s={};for(let e=0;es[e])),r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Ky.prototype,"evaluateContext",void 0),qe([Ba("Epsilon",Sa.Float,"ADVANCED",{notifiers:{rebuild:!0}})],Ky.prototype,"epsilon",void 0),ee("BABYLON.GeometryOptimizeBlock",Ky);class $y extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",vy.Float,!0,1),this.registerInput("width",vy.Float,!0,0),this.registerInput("height",vy.Float,!0,0),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new Yy("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new Yy("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),ea(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],$y.prototype,"evaluateContext",void 0),ee("BABYLON.PlaneBlock",$y);class qy extends Wy{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",vy.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh)return void(this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null);const e=cn.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=cn.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=cn.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}qe([Ba("Serialize cached data",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],qy.prototype,"serializedCachedData",void 0),ee("BABYLON.MeshBlock",qy);class Zy extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",vy.Float,!0,1),this.registerInput("radiusX",vy.Float,!0,0),this.registerInput("radiusY",vy.Float,!0,0),this.registerInput("radiusZ",vy.Float,!0,0),this.registerInput("subdivisions",vy.Int,!0,4),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new Yy("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),yl(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Zy.prototype,"evaluateContext",void 0),ee("BABYLON.IcoSphereBlock",Zy);class Jy extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",vy.Int,!0,32),this.registerInput("diameter",vy.Float,!0,1),this.registerInput("diameterX",vy.Float,!0,0),this.registerInput("diameterY",vy.Float,!0,0),this.registerInput("diameterZ",vy.Float,!0,0),this.registerInput("arc",vy.Float,!0,1),this.registerInput("slice",vy.Float,!0,1),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Yy("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),Cu(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Jy.prototype,"evaluateContext",void 0),ee("BABYLON.SphereBlock",Jy);class eS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",vy.Float,!0,1),this.registerInput("height",vy.Float,!0,1),this.registerInput("subdivisions",vy.Int,!0,1),this.registerInput("subdivisionsX",vy.Int,!0,0),this.registerInput("subdivisionsY",vy.Int,!0,0),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new Yy("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),Lc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],eS.prototype,"evaluateContext",void 0),ee("BABYLON.GridBlock",eS);class tS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",vy.Float,!0,1),this.registerInput("thickness",vy.Float,!0,.5),this.registerInput("tessellation",vy.Int,!0,16),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Yy("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),Hc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],tS.prototype,"evaluateContext",void 0),ee("BABYLON.TorusBlock",tS);class iS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",vy.Float,!0,25),this.registerInput("diameter",vy.Float,!0,1),this.registerInput("diameterTop",vy.Float,!0,-1),this.registerInput("diameterBottom",vy.Float,!0,-1),this.registerInput("subdivisions",vy.Int,!0,1),this.registerInput("tessellation",vy.Int,!0,24),this.registerInput("arc",vy.Float,!0,1),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Yy("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),au(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],iS.prototype,"evaluateContext",void 0),ee("BABYLON.CylinderBlock",iS);class sS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",vy.Float,!0,1),this.registerInput("radius",vy.Float,!0,.25),this.registerInput("tessellation",vy.Int,!0,16),this.registerInput("subdivisions",vy.Int,!0,2),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new Yy("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),Pu(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],sS.prototype,"evaluateContext",void 0),ee("BABYLON.CapsuleBlock",sS);class rS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",vy.Float,!0,.5),this.registerInput("tessellation",vy.Int,!0,64),this.registerInput("arc",vy.Float,!0,1),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new Yy("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),wu(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],rS.prototype,"evaluateContext",void 0),ee("BABYLON.DiscBlock",rS);class nS extends Wy{constructor(e){super(e),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}ee("BABYLON.NullBlock",nS);class oS extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("positions",vy.Vector3),this.registerOutput("output",vy.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.normals||(this._vertexData.normals=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);const t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.colors||(this._vertexData.colors=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.tangents||(this._vertexData.tangents=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndexthis._updateInputOutputTypes())),this.left.onDisconnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onDisconnectionObservable.add((()=>this._updateInputOutputTypes()))]}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;const t=this.left,i=this.right;if(!t.isConnected||!i.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const s=t.type===vy.Float||t.type===vy.Int,r=i.type===vy.Float||i.type===vy.Int,n=s&&r;switch(this.operation){case yy.Add:e=n?e=>t.getConnectedValue(e)+i.getConnectedValue(e):s?e=>e.adapt(t,i.type).add(i.getConnectedValue(e)):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case yy.Subtract:e=n?e=>t.getConnectedValue(e)-i.getConnectedValue(e):s?e=>e.adapt(t,i.type).subtract(i.getConnectedValue(e)):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case yy.Multiply:e=n?e=>t.getConnectedValue(e)*i.getConnectedValue(e):s?e=>e.adapt(t,i.type).multiply(i.getConnectedValue(e)):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case yy.Divide:e=n?e=>t.getConnectedValue(e)/i.getConnectedValue(e):s?e=>e.adapt(t,i.type).divide(i.getConnectedValue(e)):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case yy.Min:if(n)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else{const[r,n]=s?[i,t]:[t,i];switch(r.type){case vy.Vector2:e=e=>ue.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case vy.Vector3:e=e=>de.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case vy.Vector4:e=e=>_e.Minimize(r.getConnectedValue(e),e.adapt(n,r.type))}}break;case yy.Max:if(!n){const[r,n]=s?[i,t]:[t,i];switch(r.type){case vy.Vector2:e=e=>ue.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case vy.Vector3:e=e=>de.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case vy.Vector4:e=e=>_e.Maximize(r.getConnectedValue(e),e.adapt(n,r.type))}break}e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e))}this.output._storedFunction=i=>t.type===vy.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${yy[this.operation]};\n`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===vy.Int||this.left.type===vy.Float&&this.right.type!==vy.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[vy.Int,vy.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==vy.Int&&t.type!==vy.Float||e.acceptedConnectionPointTypes.push(vy.Vector2,vy.Vector3,vy.Vector4))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}qe([Ba("Operation",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:yy.Add},{label:"Subtract",value:yy.Subtract},{label:"Multiply",value:yy.Multiply},{label:"Divide",value:yy.Divide},{label:"Max",value:yy.Max},{label:"Min",value:yy.Min}]})],uS.prototype,"operation",void 0),ee("BABYLON.MathBlock",uS);class dS extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("fromMin",vy.Float,!0,0),this.registerInput("fromMax",vy.Float,!0,1),this.registerInput("toMin",vy.Float,!0,0),this.registerInput("toMax",vy.Float,!0,1),this.registerOutput("output",vy.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(vy.Vector2),this._inputs[0].excludedConnectionPointTypes.push(vy.Vector3),this._inputs[0].excludedConnectionPointTypes.push(vy.Vector4),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=(t-i)/(s-i)*(this.toMax.getConnectedValue(e)-r)+r;return this.output.type===vy.Int?Math.floor(n):n}}}ee("BABYLON.MapRangeBlock",dS),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(Sy||(Sy={}));class _S extends Wy{constructor(e){super(e),this.test=Sy.Equal,this.registerInput("left",vy.Float),this.registerInput("right",vy.Float,!0,0),this.registerInput("ifTrue",vy.AutoDetect,!0,1),this.registerInput("ifFalse",vy.AutoDetect,!0,0),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=vy.Float,this._inputs[0].acceptedConnectionPointTypes.push(vy.Int),this._inputs[1].acceptedConnectionPointTypes.push(vy.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);let s=!1;switch(this.test){case Sy.Equal:s=xe.WithinEpsilon(t,i,K);break;case Sy.NotEqual:s=t!==i;break;case Sy.LessThan:s=ti;break;case Sy.LessOrEqual:s=t<=i;break;case Sy.GreaterOrEqual:s=t>=i;break;case Sy.Xor:s=!!t&&!i||!t&&!!i;break;case Sy.Or:s=!!t||!!i;break;case Sy.And:s=!!t&&!!i}return s};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${Sy[this.test]};\n`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}qe([Ba("Test",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:Sy.Equal},{label:"NotEqual",value:Sy.NotEqual},{label:"LessThan",value:Sy.LessThan},{label:"GreaterThan",value:Sy.GreaterThan},{label:"LessOrEqual",value:Sy.LessOrEqual},{label:"GreaterOrEqual",value:Sy.GreaterOrEqual},{label:"Xor",value:Sy.Xor},{label:"Or",value:Sy.Or},{label:"And",value:Sy.And}]})],_S.prototype,"test",void 0),ee("BABYLON.ConditionBlock",_S),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(Cy||(Cy={}));class pS extends Wy{constructor(e){super(e),this._currentLockId=-1,this.lockMode=Cy.None,this.registerInput("min",vy.AutoDetect),this.registerInput("max",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[1].excludedConnectionPointTypes.push(vy.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new Yy("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new Yy("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case vy.Int:case vy.Float:e=e=>{const t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case vy.Vector2:e=e=>{const t=this.min.getConnectedValue(e)||ue.Zero(),i=this.max.getConnectedValue(e)||ue.Zero();return new ue(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case vy.Vector3:e=e=>{const t=this.min.getConnectedValue(e)||de.Zero(),i=this.max.getConnectedValue(e)||de.Zero();return new de(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case vy.Vector4:e=e=>{const t=this.min.getConnectedValue(e)||_e.Zero(),i=this.max.getConnectedValue(e)||_e.Zero();return new _e(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==Cy.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case Cy.InstanceID:i=t.getContextualValue(Ty.InstanceID,!0)||0;break;case Cy.LoopID:i=t.getContextualValue(Ty.LoopID,!0)||0}return this._currentLockId===i&&this.lockMode!==Cy.None||(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${Cy[this.lockMode]};\n`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}qe([Ba("LockMode",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:Cy.None},{label:"LoopID",value:Cy.LoopID},{label:"InstanceID",value:Cy.InstanceID}]})],pS.prototype,"lockMode",void 0),ee("BABYLON.RandomBlock",pS);class fS extends Wy{constructor(e){super(e),this.registerInput("offset",vy.Vector3,!0,de.Zero()),this.registerInput("scale",vy.Float,!0,1),this.registerInput("octaves",vy.Float,!0,2,0,16),this.registerInput("roughness",vy.Float,!0,.5,0,1),this.registerOutput("output",vy.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,s){const r=15&e,n=r<8?t:i,o=r<4?i:12===r||14==r?t:s;return this._negateIf(n,r&n)+this._negateIf(o,2&r)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,a,l,h,c){const u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+s*l))+c*(d*(r*u+n*l)+h*(o*u+a*l))}_perlinNoise(e){const t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),s=(0|e.z)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,a=this._fade(r),l=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),a,l,h)}_perlinSigned(e){return.982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new de(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,a=1,l=0,h=0;const c=0|(e=xe.Clamp(e,0,15));for(let e=0;e<=c;e++)h+=this._perlin(n.scale(o))*a,l+=a,a*=xe.Clamp(t,0,1),o*=2;const u=e-Math.floor(e);if(0==u)return h/l;let d=h+this._perlin(n.scale(o))*a;return h/=l,d/=l+a,(1-u)*h+u*d}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Ty.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}}ee("BABYLON.NoiseBlock",fS);class mS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",vy.Geometry),this.registerInput("geometry1",vy.Geometry,!0),this.registerInput("geometry2",vy.Geometry,!0),this.registerInput("geometry3",vy.Geometry,!0),this.registerInput("geometry4",vy.Geometry,!0),this.registerOutput("output",vy.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{let t=this.geometry0.getConnectedValue(e);const i=[];if(!t)return null;if(t=t.clone(),this.geometry1.isConnected){const t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){const t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){const t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){const t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mS.prototype,"evaluateContext",void 0),ee("BABYLON.MergeGeometryBlock",mS);class gS extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",vy.Geometry,!0),this.registerInput("geometry1",vy.Geometry,!0),this.registerInput("geometry2",vy.Geometry,!0),this.registerInput("geometry3",vy.Geometry,!0),this.registerInput("geometry4",vy.Geometry,!0),this.registerInput("geometry5",vy.Geometry,!0),this.registerInput("geometry6",vy.Geometry,!0),this.registerInput("geometry7",vy.Geometry,!0),this.registerInput("geometry8",vy.Geometry,!0),this.registerInput("geometry9",vy.Geometry,!0),this.registerOutput("output",vy.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,s){if(e.isConnected){const r=e.getConnectedValue(t);if(!r)return;r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=e=>{const t=[];return this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],gS.prototype,"evaluateContext",void 0),ee("BABYLON.GeometryCollectionBlock",gS);class vS extends Wy{constructor(e){super(e),this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}ee("BABYLON.GeometryElbowBlock",vS);class xS extends Wy{constructor(e){super(e),this.registerInput("geometry",vy.Geometry),this.registerOutput("output",vy.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),cn.ComputeNormals(t.positions,t.indices,t.normals),t}}}ee("BABYLON.ComputeNormalsBlock",xS);class bS extends Wy{constructor(e){super(e),this.registerInput("xyzw ",vy.Vector4,!0),this.registerInput("xyz ",vy.Vector3,!0),this.registerInput("xy ",vy.Vector2,!0),this.registerInput("zw ",vy.Vector2,!0),this.registerInput("x ",vy.Float,!0),this.registerInput("y ",vy.Float,!0),this.registerInput("z ",vy.Float,!0),this.registerInput("w ",vy.Float,!0),this.registerOutput("xyzw",vy.Vector4),this.registerOutput("xyz",vy.Vector3),this.registerOutput("xy",vy.Vector2),this.registerOutput("zw",vy.Vector2),this.registerOutput("x",vy.Float),this.registerOutput("y",vy.Float),this.registerOutput("z",vy.Float),this.registerOutput("w",vy.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,_=this.xOut,p=this.yOut,f=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),s.isConnected&&(u=s.getConnectedValue(e)),r.isConnected&&(d=r.getConnectedValue(e)),n.isConnected){const t=n.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(o.isConnected){const t=o.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(a.isConnected){const t=a.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new _e(h,c,u,d)};h._storedFunction=e=>g(e),c._storedFunction=e=>{const t=g(e);return new de(t.x,t.y,t.z)},u._storedFunction=e=>{const t=g(e);return new ue(t.x,t.y)},d._storedFunction=e=>{const t=g(e);return new ue(t.z,t.w)},_._storedFunction=e=>g(e).x,p._storedFunction=e=>g(e).y,f._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}ee("BABYLON.VectorConverterBlock",bS);class TS extends Wy{constructor(e){super(e),this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize():this.output._storedValue=null}}ee("BABYLON.NormalizeVectorBlock",TS);class yS extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("id",vy.Int,!0,0),this.registerOutput("output",vy.Geometry),this.id.acceptedConnectionPointTypes.push(vy.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;const i=new hn;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],yS.prototype,"evaluateContext",void 0),ee("BABYLON.SetMaterialIDBlock",yS),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians",e[e.Fract=19]="Fract",e[e.Exp2=20]="Exp2"}(Ey||(Ey={}));class SS extends Wy{constructor(e){super(e),this.operation=Ey.Cos,this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case Ey.Cos:t=e=>Math.cos(e);break;case Ey.Sin:t=e=>Math.sin(e);break;case Ey.Abs:t=e=>Math.abs(e);break;case Ey.Exp:t=e=>Math.exp(e);break;case Ey.Exp2:t=e=>Math.pow(2,e);break;case Ey.Round:t=e=>Math.round(e);break;case Ey.Floor:t=e=>Math.floor(e);break;case Ey.Ceiling:t=e=>Math.ceil(e);break;case Ey.Sqrt:t=e=>Math.sqrt(e);break;case Ey.Log:t=e=>Math.log(e);break;case Ey.Tan:t=e=>Math.tan(e);break;case Ey.ArcTan:t=e=>Math.atan(e);break;case Ey.ArcCos:t=e=>Math.acos(e);break;case Ey.ArcSin:t=e=>Math.asin(e);break;case Ey.Sign:t=e=>Math.sign(e);break;case Ey.Negate:t=e=>-e;break;case Ey.OneMinus:t=e=>1-e;break;case Ey.Reciprocal:t=e=>1/e;break;case Ey.ToRadians:t=e=>e*Math.PI/180;break;case Ey.ToDegrees:t=e=>180*e/Math.PI;break;case Ey.Fract:t=e=>e>=0?e-Math.floor(e):e-Math.ceil(e)}if(!t)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case vy.Int:case vy.Float:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return t(i)};break;case vy.Vector2:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new ue(t(i.x),t(i.y))};break;case vy.Vector3:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new de(t(i.x),t(i.y),t(i.z))};break;case vy.Vector4:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new _e(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${Ey[this.operation]};\n`}}qe([Ba("Operation",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Ey.Cos},{label:"Sin",value:Ey.Sin},{label:"Abs",value:Ey.Abs},{label:"Exp",value:Ey.Exp},{label:"Exp2",value:Ey.Exp2},{label:"Round",value:Ey.Round},{label:"Floor",value:Ey.Floor},{label:"Ceiling",value:Ey.Ceiling},{label:"Sqrt",value:Ey.Sqrt},{label:"Log",value:Ey.Log},{label:"Tan",value:Ey.Tan},{label:"ArcTan",value:Ey.ArcTan},{label:"ArcCos",value:Ey.ArcCos},{label:"ArcSin",value:Ey.ArcSin},{label:"Sign",value:Ey.Sign},{label:"Negate",value:Ey.Negate},{label:"OneMinus",value:Ey.OneMinus},{label:"Reciprocal",value:Ey.Reciprocal},{label:"ToDegrees",value:Ey.ToDegrees},{label:"ToRadians",value:Ey.ToRadians},{label:"Fract",value:Ey.Fract}]})],SS.prototype,"operation",void 0),ee("BABYLON.GeometryTrigonometryBlock",SS);class CS extends Wy{constructor(e){super(e),this._rotationMatrix=new fe,this._scalingMatrix=new fe,this._translationMatrix=new fe,this._scalingRotationMatrix=new fe,this._transformMatrix=new fe,this.evaluateContext=!0,this.registerInput("value",vy.AutoDetect),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("translation",vy.Vector3,!0,de.Zero()),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.value.getConnectedValue(e);if(!t)return null;let i;if(this.matrix.isConnected)i=this.matrix.getConnectedValue(e);else{const t=this.scaling.getConnectedValue(e),s=this.rotation.getConnectedValue(e),r=this.translation.getConnectedValue(e);fe.ScalingToRef(t.x,t.y,t.z,this._scalingMatrix),fe.RotationYawPitchRollToRef(s.y,s.x,s.z,this._rotationMatrix),fe.TranslationToRef(r.x,r.y,r.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),i=this._transformMatrix}switch(this.value.type){case vy.Geometry:{const e=t.clone();return e.transform(i),e}case vy.Vector2:return ue.Transform(t,i);case vy.Vector3:return de.TransformCoordinates(t,i);case vy.Vector4:return _e.TransformCoordinates(t,i)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CS.prototype,"evaluateContext",void 0),ee("BABYLON.GeometryTransformBlock",CS);class ES extends Wy{constructor(e){super(e),this.registerInput("angle",vy.Float,!1,0),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Yy("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>fe.RotationX(this.angle.getConnectedValue(e))}}ee("BABYLON.RotationXBlock",ES);class AS extends Wy{constructor(e){super(e),this.registerInput("angle",vy.Float,!1,0),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Yy("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>fe.RotationY(this.angle.getConnectedValue(e))}}ee("BABYLON.RotationYBlock",AS);class PS extends Wy{constructor(e){super(e),this.registerInput("angle",vy.Float,!1,0),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Yy("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>fe.RotationZ(this.angle.getConnectedValue(e))}}ee("BABYLON.RotationZBlock",PS);class RS extends Wy{constructor(e){super(e),this.registerInput("scale",vy.Vector3,!1,de.One()),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new Yy("Scale");e.value=new de(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.scale.getConnectedValue(e);return fe.Scaling(t.x,t.y,t.z)}}}ee("BABYLON.ScalingBlock",RS);class IS extends Wy{constructor(e){super(e),this.registerInput("source",vy.Vector3,!0,de.Up()),this.registerInput("target",vy.Vector3,!0,de.Left()),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),s=new fe;return t.normalize(),i.normalize(),fe.RotationAlignToRef(t,i,s,!0),s}}}ee("BABYLON.AlignBlock",IS);class MS extends Wy{constructor(e){super(e),this.registerInput("translation",vy.Vector3,!1,de.Zero()),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new Yy("Translation");e.value=new de(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.translation.getConnectedValue(e);return fe.Translation(t.x,t.y,t.z)}}}ee("BABYLON.TranslationBlock",MS);class OS extends Wy{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("instance",vy.Geometry,!0),this.registerInput("density",vy.Float,!0,1,0,1),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.scaling.acceptedConnectionPointTypes.push(vy.Float),this.registerOutput("output",vy.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=this._vertexData.positions.length/3;const i=[],s=new de,r=[];let n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexr)continue;s.fromArray(n,3*this._currentIndex);const o=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(o,s,t,i)}else{const t=e.adaptInput(this.scaling,vy.Vector3,de.OneReadOnly),r=this.rotation.getConnectedValue(e)||de.ZeroReadOnly;e._instantiate(o,s,r,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{const e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"};\n`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],OS.prototype,"evaluateContext",void 0),qe([Ba("Remove duplicated positions",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],OS.prototype,"removeDuplicatedPositions",void 0),ee("BABYLON.InstantiateOnVerticesBlock",OS);class DS extends Wy{constructor(e){super(e),this._currentPosition=new de,this._currentUV=new ue,this._vertex0=new de,this._vertex1=new de,this._vertex2=new de,this._tempVector0=new de,this._tempVector1=new de,this._uv0=new ue,this._uv1=new ue,this._uv2=new ue,this.evaluateContext=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("instance",vy.Geometry,!0),this.registerInput("count",vy.Int,!0,256),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.scaling.acceptedConnectionPointTypes.push(vy.Float),this.registerOutput("output",vy.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),de.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=this._vertexData.indices.length/3,r=i/s;let n=0;const o=[];let a=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),s=Math.random();if(i>s){const e=i;i=s,s=e}const l=i,h=s-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length){n-=r;continue}const u=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,o)}else{const t=e.adaptInput(this.scaling,vy.Vector3,de.OneReadOnly),i=this.rotation.getConnectedValue(e)||de.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,o)}a++,this._currentLoopIndex++}}if(o.length)if(1===o.length)this._vertexData=o[0];else{const e=o.splice(0,1)[0];this._vertexData=e.merge(o,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],DS.prototype,"evaluateContext",void 0),ee("BABYLON.InstantiateOnFacesBlock",DS);class wS extends Wy{constructor(e){super(e),this._currentPosition=new de,this._vertex0=new de,this._vertex1=new de,this._vertex2=new de,this.evaluateContext=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("instance",vy.Geometry,!0),this.registerInput("count",vy.Int,!0,256),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.scaling.acceptedConnectionPointTypes.push(vy.Float),this.registerOutput("output",vy.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=[],r=an(this._vertexData.positions,0,this._vertexData.positions.length/3),n=r.minimum,o=r.maximum,a=new de(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let r=0;r0&&h++}if(h%2==0){r--;continue}if(t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length)continue;const c=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,s)}else{const t=e.adaptInput(this.scaling,vy.Vector3,de.OneReadOnly),i=this.rotation.getConnectedValue(e)||de.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,s)}this._currentLoopIndex++}if(s.length)if(1===s.length)this._vertexData=s[0];else{const e=s.splice(0,1)[0];this._vertexData=e.merge(s,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],wS.prototype,"evaluateContext",void 0),ee("BABYLON.InstantiateOnVolumeBlock",wS);class NS extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",vy.Geometry,!0),this.registerInput("count",vy.Int,!0,1),this.registerOutput("output",vy.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],NS.prototype,"evaluateContext",void 0);class FS extends NS{constructor(e){super(e),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("position",vy.Vector3,!0,de.Zero()),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.scaling.acceptedConnectionPointTypes.push(vy.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=fe.Identity(),r=de.Zero(),n=de.Zero(),o=de.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=fe.Identity(),r=fe.Identity(),n=fe.Identity(),o=de.Zero(),a=de.Zero(),l=de.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}ee("BABYLON.IntFloatConverterBlock",kS);class VS extends Wy{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];const t=e=>{const t=this.input.getConnectedValue(e);if(null==t)return this.log.push(["null",""]),t;switch(this.input.type){case vy.Vector2:this.log.push([KT(t,4),t.toString()]);break;case vy.Vector3:this.log.push([$T(t,4),t.toString()]);break;case vy.Vector4:this.log.push([qT(t,4),t.toString()]);break;default:this.log.push([t.toString(),t.toString()])}return t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}ee("BABYLON.DebugBlock",VS);class US extends Wy{constructor(e){super(e),this.registerInput("geometry",vy.Geometry),this.registerOutput("output",vy.Geometry),this.registerOutput("id",vy.Int),this.registerOutput("collectionId",vy.Int),this.registerOutput("verticesCount",vy.Int),this.registerOutput("facesCount",vy.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected)return this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,void(this.output._storedFunction=null);this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}ee("BABYLON.GeometryInfoBlock",US),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(Ay||(Ay={}));class GS extends Wy{constructor(e){super(e),this.mapping=Ay.Spherical,this.registerInput("position",vy.Vector3),this.registerInput("normal",vy.Vector3),this.registerInput("center",vy.Vector3,!0,de.Zero()),this.registerOutput("uv",vy.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected)return this.uv._storedFunction=null,void(this.uv._storedValue=null);const e=de.Zero(),t=t=>{const i=this.position.getConnectedValue(t)||de.Zero(),s=this.normal.getConnectedValue(t)||de.Zero(),r=this.center.getConnectedValue(t),n=ue.Zero();switch(this.mapping){case Ay.Spherical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,0===e.x&&0===e.z||(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case Ay.Cylindrical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case Ay.Cubic:{const e=Math.abs(s.x),t=Math.abs(s.y),o=Math.abs(s.z),a=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));let l=0,h=0;e>=t&&e>=o?(l=i.y/a-r.y,h=i.z/a-r.z):t>=e&&t>=o?(l=i.x/a-r.x,h=i.z/a-r.z):(l=i.x/a-r.x,h=i.y/a-r.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${Ay[this.mapping]};\n`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}qe([Ba("Mapping",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:Ay.Spherical},{label:"Cylindrical",value:Ay.Cylindrical},{label:"Cubic",value:Ay.Cubic}]})],GS.prototype,"mapping",void 0),ee("BABYLON.MappingBlock",GS);class zS extends Wy{constructor(e){super(e),this.registerInput("matrix0",vy.Matrix),this.registerInput("matrix1",vy.Matrix),this.registerOutput("output",vy.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}}ee("BABYLON.MatrixComposeBlock",zS);class WS extends Wy{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",vy.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}ee("BABYLON.TeleportInBlock",WS);class HS extends Wy{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",vy.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}ee("BABYLON.TeleportOutBlock",HS);class XS extends Wy{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",vy.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise(((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const e=n.getImageData(0,0,s.width,s.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},s.src=e}))}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise(((t,i)=>{if(!e.isReady())return void e.onLoadObservable.addOnce((()=>this.extractFromTextureAsync(e).then(t).catch(i)));const s=e.getSize();g_.GetTextureDataAsync(e,s.width,s.height).then((async e=>{const i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=e=>{const t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;const i=this.coordinates.getConnectedValue(e);if(!i)return null;const s=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),r=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(s*(t.width-1)),o=Math.floor(r*(t.height-1)),a=n+t.width*o;return _e.FromArray(t.data,4*a)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};\n`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}qe([Ba("Clamp Coordinates",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],YS.prototype,"clampCoordinates",void 0),ee("BABYLON.GeometryTextureFetchBlock",YS);class QS extends Wy{constructor(e){super(e),this.registerInput("geometry",vy.Geometry),this.registerOutput("min",vy.Vector3),this.registerOutput("max",vy.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?an(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?an(t.positions,0,t.positions.length/3).maximum:null}}}ee("BABYLON.BoundingBlock",QS),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(Py||(Py={}));class jS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.operation=Py.Intersect,this.registerInput("geometry0",vy.Geometry),this.registerInput("geometry1",vy.Geometry),this.registerOutput("output",vy.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{const t=this.geometry0.getConnectedValue(e),i=this.geometry1.getConnectedValue(e);if(!t||!i)return null;const s=t.positions.length/3;!t.normals&&i.normals&&(t.normals=new Array(t.positions.length)),!i.normals&&t.normals&&(i.normals=new Array(i.positions.length)),!t.uvs&&i.uvs&&(t.uvs=new Array(2*s)),!i.uvs&&t.uvs&&(i.uvs=new Array(2*s)),!t.colors&&i.colors&&(t.colors=new Array(4*s)),!i.colors&&t.colors&&(i.colors=new Array(4*s));const r=ay.FromVertexData(t),n=ay.FromVertexData(i);let o;switch(this.operation){case Py.Intersect:o=r.intersect(n);break;case Py.Subtract:o=r.subtract(n);break;case Py.Union:o=r.union(n)}return o.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${Py[this.operation]};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],jS.prototype,"evaluateContext",void 0),qe([Ba("Operation",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:Py.Intersect},{label:"Subtract",value:Py.Subtract},{label:"Union",value:Py.Union}]})],jS.prototype,"operation",void 0),ee("BABYLON.BooleanGeometryBlock",jS);class KS extends Wy{constructor(e){super(e),this.registerInput("x",vy.AutoDetect),this.registerInput("y",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.atan2(e,t);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),s=this.y.getConnectedValue(t);switch(this.x.type){case vy.Int:case vy.Float:return e(i,s);case vy.Vector2:return new ue(e(i.x,s.x),e(i.y,s.y));case vy.Vector3:return new de(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case vy.Vector4:return new _e(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0}}}ee("BABYLON.GeometryArcTan2Block",KS);class $S extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerInput("gradient",vy.Float),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case vy.Int:case vy.Float:return e(r,i,s);case vy.Vector2:return new ue(e(r,i.x,s.x),e(r,i.y,s.y));case vy.Vector3:return new de(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));case vy.Vector4:return new _e(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w))}return 0},this}}ee("BABYLON.GeometryLerpBlock",$S);class qS extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerInput("gradient",vy.Float),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case vy.Int:case vy.Float:return e(r,i,s);case vy.Vector2:{const t=new ue(e(r,i.x,s.x),e(r,i.y,s.y));return t.normalize(),t}case vy.Vector3:{const t=new de(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));return t.normalize(),t}case vy.Vector4:{const t=new _e(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w));return t.normalize(),t}}return 0},this}}ee("BABYLON.GeometryNLerpBlock",qS);class ZS extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("edge",vy.Float),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e{const i=this.value.getConnectedValue(t),s=this.edge.getConnectedValue(t);switch(this.value.type){case vy.Int:case vy.Float:return e(i,s);case vy.Vector2:return new ue(e(i.x,s),e(i.y,s));case vy.Vector3:return new de(e(i.x,s),e(i.y,s),e(i.z,s));case vy.Vector4:return new _e(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}ee("BABYLON.GeometryStepBlock",ZS);class JS extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("edge0",vy.Float),this.registerInput("edge1",vy.Float),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>{const s=Math.max(0,Math.min((e-t)/(i-t),1));return s*s*(3-2*s)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge0.getConnectedValue(t),r=this.edge1.getConnectedValue(t);switch(this.value.type){case vy.Int:case vy.Float:return e(i,s,r);case vy.Vector2:return new ue(e(i.x,s,r),e(i.y,s,r));case vy.Vector3:return new de(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r));case vy.Vector4:return new _e(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r),e(i.w,s,r))}return 0},this}}ee("BABYLON.GeometrySmoothStepBlock",JS);class eC extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e-Math.floor(e/t)*t;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t);switch(this.left.type){case vy.Int:case vy.Float:return e(i,s);case vy.Vector2:return new ue(e(i.x,s.x),e(i.y,s.y));case vy.Vector3:return new de(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case vy.Vector4:return new _e(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0},this}}ee("BABYLON.GeometryModBlock",eC);class tC extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("power",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.pow(e,t);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.power.getConnectedValue(t);switch(this.value.type){case vy.Int:case vy.Float:return e(i,s);case vy.Vector2:return new ue(e(i.x,s),e(i.y,s));case vy.Vector3:return new de(e(i.x,s),e(i.y,s),e(i.z,s));case vy.Vector4:return new _e(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}ee("BABYLON.GeometryPowBlock",tC);class iC extends Wy{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>Math.max(this.minimum,Math.min(e,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case vy.Int:case vy.Float:return e(i);case vy.Vector2:return new ue(e(i.x),e(i.y));case vy.Vector3:return new de(e(i.x),e(i.y),e(i.z));case vy.Vector4:return new _e(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}qe([Ba("Minimum",Sa.Float)],iC.prototype,"minimum",void 0),qe([Ba("Maximum",Sa.Float)],iC.prototype,"maximum",void 0),ee("BABYLON.GeometryClampBlock",iC);class sC extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerOutput("output",vy.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Int),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Vector2),this._inputs[1].excludedConnectionPointTypes.push(vy.Int),this._inputs[1].excludedConnectionPointTypes.push(vy.Float),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case vy.Vector3:return de.Cross(t,i);case vy.Vector4:return de.Cross(t.toVector3(),i.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryCrossBlock",sC),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(Ry||(Ry={}));class rC extends Wy{constructor(e){super(e),this.type=Ry.EaseInOutSine,this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);let e;switch(this.type){case Ry.EaseInSine:e=e=>1-Math.cos(3.1415*e/2);break;case Ry.EaseOutSine:e=e=>Math.sin(3.1415*e/2);break;case Ry.EaseInOutSine:e=e=>-(Math.cos(3.1415*e)-1)/2;break;case Ry.EaseInQuad:e=e=>e*e;break;case Ry.EaseOutQuad:e=e=>(1-e)*(1-e);break;case Ry.EaseInOutQuad:e=e=>e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;break;case Ry.EaseInCubic:e=e=>e*e*e;break;case Ry.EaseOutCubic:e=e=>1-Math.pow(1-e,3);break;case Ry.EaseInOutCubic:e=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;break;case Ry.EaseInQuart:e=e=>e*e*e*e;break;case Ry.EaseOutQuart:e=e=>1-Math.pow(1-e,4);break;case Ry.EaseInOutQuart:e=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;break;case Ry.EaseInQuint:e=e=>e*e*e*e*e;break;case Ry.EaseOutQuint:e=e=>1-Math.pow(1-e,5);break;case Ry.EaseInOutQuint:e=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;break;case Ry.EaseInExpo:e=e=>0===e?0:Math.pow(2,10*e-10);break;case Ry.EaseOutExpo:e=e=>1===e?1:1-Math.pow(2,-10*e);break;case Ry.EaseInOutExpo:e=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;break;case Ry.EaseInCirc:e=e=>1-Math.sqrt(1-Math.pow(e,2));break;case Ry.EaseOutCirc:e=e=>Math.sqrt(1-Math.pow(e-1,2));break;case Ry.EaseInOutCirc:e=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;break;case Ry.EaseInBack:e=e=>2.70158*e*e*e-1.70158*e*e;break;case Ry.EaseOutBack:e=e=>2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2);break;case Ry.EaseInOutBack:e=e=>e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2;break;case Ry.EaseInElastic:e=e=>0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75));break;case Ry.EaseOutElastic:e=e=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1;break;case Ry.EaseInOutElastic:e=e=>0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case vy.Float:return e(i);case vy.Vector2:return new ue(e(i.x),e(i.y));case vy.Vector3:return new de(e(i.x),e(i.y),e(i.z));case vy.Vector4:return new _e(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${Ry[this.type]};\n`}}qe([Ba("Type",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:Ry.EaseInSine},{label:"EaseOutSine",value:Ry.EaseOutSine},{label:"EaseInOutSine",value:Ry.EaseInOutSine},{label:"EaseInQuad",value:Ry.EaseInQuad},{label:"EaseOutQuad",value:Ry.EaseOutQuad},{label:"EaseInOutQuad",value:Ry.EaseInOutQuad},{label:"EaseInCubic",value:Ry.EaseInCubic},{label:"EaseOutCubic",value:Ry.EaseOutCubic},{label:"EaseInOutCubic",value:Ry.EaseInOutCubic},{label:"EaseInQuart",value:Ry.EaseInQuart},{label:"EaseOutQuart",value:Ry.EaseOutQuart},{label:"EaseInOutQuart",value:Ry.EaseInOutQuart},{label:"EaseInQuint",value:Ry.EaseInQuint},{label:"EaseOutQuint",value:Ry.EaseOutQuint},{label:"EaseInOutQuint",value:Ry.EaseInOutQuint},{label:"EaseInExpo",value:Ry.EaseInExpo},{label:"EaseOutExpo",value:Ry.EaseOutExpo},{label:"EaseInOutExpo",value:Ry.EaseInOutExpo},{label:"EaseInCirc",value:Ry.EaseInCirc},{label:"EaseOutCirc",value:Ry.EaseOutCirc},{label:"EaseInOutCirc",value:Ry.EaseInOutCirc},{label:"EaseInBack",value:Ry.EaseInBack},{label:"EaseOutBack",value:Ry.EaseOutBack},{label:"EaseInOutBack",value:Ry.EaseInOutBack},{label:"EaseInElastic",value:Ry.EaseInElastic},{label:"EaseOutElastic",value:Ry.EaseOutElastic},{label:"EaseInOutElastic",value:Ry.EaseInOutElastic}]})],rC.prototype,"type",void 0),ee("BABYLON.GeometryCurveBlock",rC);class nC extends Wy{constructor(e){super(e),this.registerInput("color",vy.Vector3),this.registerInput("level",vy.Float,!0,0),this.registerOutput("output",vy.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.color.isConnected?(this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),s=.5*(Math.min(t.x,t.y,t.z)+Math.max(t.x,t.y,t.z));return new de(t.x*(1-i)+s*i,t.y*(1-i)+s*i,t.z*(1-i)+s*i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryDesaturateBlock",nC);class oC extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("steps",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(vy.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let s=i;if(this.steps.type===vy.Float)switch(this.value.type){case vy.Vector2:s=new ue(i,i);break;case vy.Vector3:s=new de(i,i,i);break;case vy.Vector4:s=new _e(i,i,i,i)}switch(this.value.type){case vy.Vector2:return new ue(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y));case vy.Vector3:return new de(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z));case vy.Vector4:return new _e(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z),t.w/(1/s.w)*(1/s.w));default:return Math.floor(t/(1/i)*(1/i))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryPosterizeBlock",oC);class aC extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("reference",vy.AutoDetect),this.registerInput("distance",vy.Float),this.registerInput("replacement",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Float),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[3].excludedConnectionPointTypes.push(vy.Float),this._inputs[3].excludedConnectionPointTypes.push(vy.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),s=this.distance.getConnectedValue(e),r=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryDistanceBlock",lC);class hC extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerOutput("output",vy.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Int),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Float),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryDotBlock",hC);class cC extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerOutput("output",vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Int),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected?(this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryLengthBlock",cC);class uC extends Wy{constructor(e){super(e),this.registerInput("input",vy.Vector2),this.registerInput("angle",vy.Float),this.registerOutput("output",vy.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new ue(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryRotate2dBlock",uC);class dC extends bo{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=fe.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const s=new cn;s.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],s.indices=[0,1,2,0,2,3],s.applyToMesh(this),this.subMeshes=[],new ln(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new XT(this.name+"_material",this._scene),this.material=this._material);const s=this.getScene().getFrameId();if(s!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const e=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(e-1)>=.01&&(this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),s=i.indexOf("end_header\n");if(s<0||!i)return e;const r=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let n=0;const o={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},a=[],l=i.slice(0,s).split("\n").filter((e=>e.startsWith("property ")));for(const e of l){const[,t,i]=e.split(" ");if(a.push({name:i,type:t,offset:n}),!o[t])return we.Error(`Unsupported property type: ${t}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0);n+=o[t]}const h=.28209479177387814,c=new DataView(e,s+11),u=new ArrayBuffer(32*r),d=new pe;for(let e=0;e{this._loadData(dC.ConvertPLYToSplat(e))}))}dispose(e){this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._material?.dispose(!1,!0),this._material=null,this._worker?.terminate(),this._worker=null,super.dispose(e)}_loadData(e){if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),s=t.length/32;this._vertexCount=s;const r=this._getTextureSize(s),n=r.x*r.y,o=new Float32Array(3*n),a=new Float32Array(3*n),l=new Float32Array(3*n),h=ge.Matrix[0],c=ge.Matrix[1],u=ge.Quaternion[0],d=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),_=new de(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let e=0;enew Wo(e,t,i,s,this._scene,!1,!1,2,1),g=e=>{const t=e.length/3,i=new Float32Array(4*t);for(let s=0;s{this._depthMix=e.data.depthMix;const t=new Uint32Array(e.data.depthMix.buffer);for(let e=0;ei&&(we.Error("GaussianSplatting texture size: ("+i+", "+s+"), maxTextureSize: "+i),s=i),new ue(i,s)}}dC._CreateWorker=function(e){let t,i,s,r,n=0;e.onmessage=o=>{if(o.data.positions)t=o.data.positions,n=o.data.vertexCount;else{const a=o.data.view;if(!t||!a)throw new Error("positions or view is not defined!");i=o.data.depthMix,s=new Uint32Array(i.buffer),r=new Float32Array(i.buffer);for(let e=0;e{this.update(.001*s.getEngine().getDeltaTime()*e.timeFactor)}))}addAgent(e,t,i){const s=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;s.radius=t.radius,s.height=t.height,s.maxAcceleration=t.maxAcceleration,s.maxSpeed=t.maxSpeed,s.collisionQueryRange=t.collisionQueryRange,s.pathOptimizationRange=t.pathOptimizationRange,s.separationWeight=t.separationWeight,s.updateFlags=7,s.obstacleAvoidanceType=0,s.queryFilterType=0,s.userData=0;const r=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),s);return this.transforms.push(i),this.agents.push(r),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new de(0,0,0)),r}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new de(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new de(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new de(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=K)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=K)this.recastCrowd.update(e);else{let s=Math.floor(e/t);i&&s>i&&(s=i),s<1&&(s=1);const r=e/s;for(let e=0;eo&&i.ynew fC(e,t,i);class fC{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=fC._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,fC.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,hs.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new At;navigator.onLine&&(s=!0,r=r+(null==r.match(/\?/)?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",(()=>{if(200===n.status||fC._ValidateXHRData(n,1))try{const t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&fC._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{if(s){s=!1;const e=i();n.open("GET",e),n.send()}else t()}),!1);try{n.send()}catch(t){we.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{we.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){we.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=fC._ReturnFullUrlLocation(e),s=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let r;s&&"function"==typeof URL?(r=URL.createObjectURL(s.data),t.onerror=()=>{we.Error("Error loading image from blob URL: "+r+" switching back to web url: "+e),t.src=e},t.src=r):i()};const n=r.objectStore("textures").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{we.Error("Error loading texture "+e+" from DB."),t.src=e}}else we.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const s=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(fC._IsUASupportingBlobStorage){const r=new At;r.open("GET",e),r.responseType="blob",r.addEventListener("load",(()=>{if(200===r.status&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const e=n.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{s()}}catch(i){25===i.code&&(fC._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),r.addEventListener("error",(()=>{we.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),r.send()}else t.src=e}else we.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{we.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){we.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else we.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{we.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){we.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=fC._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s,r;s=-1!==e.indexOf(".babylon")?"scenes":"textures";const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=e=>{r=e.target.result},o.onerror=()=>{we.Error("Error loading file "+e+" from DB."),i()}}else we.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new At;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&fC._ValidateXHRData(o,s?6:1))if(a=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([n],"readwrite");let s;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},s="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(n).put(s);e.onsuccess=()=>{},e.onerror=()=>{we.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&r?r(o):t()}),!1),o.addEventListener("error",(()=>{we.Error("error on XHR request."),r&&r()}),!1),o.send()}else we.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=nx(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}fC._IsUASupportingBlobStorage=!0,fC.IDBStorageEnabled=!1,fC._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},fC._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?fC._ParseURL(window.location.href)+e:e;class mC{constructor(){this.direction1=new de(0,1,0),this.direction2=new de(0,1,0),this.minEmitBox=new de(-.5,-.5,-.5),this.maxEmitBox=new de(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=ne(this.direction1.x,this.direction2.x),n=ne(this.direction1.y,this.direction2.y),o=ne(this.direction1.z,this.direction2.z);if(s)return t.x=r,t.y=n,void(t.z=o);de.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=ne(this.minEmitBox.x,this.maxEmitBox.x),n=ne(this.minEmitBox.y,this.maxEmitBox.y),o=ne(this.minEmitBox.z,this.maxEmitBox.z);if(s)return t.x=r,t.y=n,void(t.z=o);de.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new mC;return Xe.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){de.FromArrayToRef(e.direction1,0,this.direction1),de.FromArrayToRef(e.direction2,0,this.direction2),de.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),de.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class gC{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,s){s?ge.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),ge.Vector3[0]).normalize();const r=xe.RandomRange(0,this.directionRandomizer),n=xe.RandomRange(0,this.directionRandomizer),o=xe.RandomRange(0,this.directionRandomizer);t.x=ge.Vector3[0].x+r,t.y=ge.Vector3[0].y+n,t.z=ge.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=xe.RandomRange(0,2*Math.PI);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=xe.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-xe.RandomRange(0,this._radius*this.radiusRange);o*=n;const a=o*Math.sin(r),l=o*Math.cos(r),h=n*this._height;if(s)return t.x=a,t.y=h,void(t.z=l);de.TransformCoordinatesFromFloatsToRef(a,h,l,e,t)}clone(){const e=new gC(this._radius,this._angle,this.directionRandomizer);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class vC{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=de.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),de.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=xe.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);o+=xe.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s?t.copyFrom(this._tempVector):de.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=xe.RandomRange(-this.height/2,this.height/2),n=xe.RandomRange(0,2*Math.PI),o=xe.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(o)*this.radius,l=a*Math.cos(n),h=a*Math.sin(n);s?t.copyFromFloats(l,r,h):de.TransformCoordinatesFromFloatsToRef(l,r,h,e,t)}clone(){const e=new vC(this.radius,this.directionRandomizer);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class xC extends vC{constructor(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t,i,s){const r=xe.RandomRange(this.direction1.x,this.direction2.x),n=xe.RandomRange(this.direction1.y,this.direction2.y),o=xe.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):de.TransformNormalFromFloatsToRef(r,n,o,e,t)}clone(){const e=new xC(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class bC{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=xe.RandomRange(0,this.directionRandomizer),o=xe.RandomRange(0,this.directionRandomizer),a=xe.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):de.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-xe.RandomRange(0,this.radius*this.radiusRange),n=xe.RandomRange(0,1),o=xe.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,Math.abs(h),c):de.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new bC(this.radius,this.directionRandomizer);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class TC{constructor(){this.direction1=new de(0,1,0),this.direction2=new de(0,1,0)}startDirectionFunction(e,t,i,s){const r=xe.RandomRange(this.direction1.x,this.direction2.x),n=xe.RandomRange(this.direction1.y,this.direction2.y),o=xe.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):de.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){s?t.copyFromFloats(0,0,0):de.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new TC;return Xe.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){de.FromArrayToRef(e.direction1,0,this.direction1),de.FromArrayToRef(e.direction2,0,this.direction2)}}class yC{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=xe.RandomRange(0,this.directionRandomizer),o=xe.RandomRange(0,this.directionRandomizer),a=xe.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):de.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-xe.RandomRange(0,this.radius*this.radiusRange),n=xe.RandomRange(0,1),o=xe.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,h,c):de.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new yC(this.radius,this.directionRandomizer);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class SC extends yC{constructor(e=1,t=new de(0,1,0),i=new de(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=xe.RandomRange(this.direction1.x,this.direction2.x),s=xe.RandomRange(this.direction1.y,this.direction2.y),r=xe.RandomRange(this.direction1.z,this.direction2.z);de.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new SC(this.radius,this.direction1,this.direction2);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class CC{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=ge.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const e=ge.Vector3[1];r.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);s?t.copyFrom(r):de.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=ge.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s?t.copyFrom(r):de.TransformCoordinatesToRef(r,e,t)}clone(){const e=new CC;return Xe.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class EC{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(ys.PositionKind),this._normals=e.getVerticesData(ys.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=de.Zero(),this._mesh=null,this.direction1=new de(0,1,0),this.direction2=new de(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals)return void de.TransformNormalToRef(this._storedNormal,e,t);const r=xe.RandomRange(this.direction1.x,this.direction2.x),n=xe.RandomRange(this.direction1.y,this.direction2.y),o=xe.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):de.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),a=1-n-o,l=this._indices[r],h=this._indices[r+1],c=this._indices[r+2],u=ge.Vector3[0],d=ge.Vector3[1],_=ge.Vector3[2],p=ge.Vector3[3];de.FromArrayToRef(this._positions,3*l,u),de.FromArrayToRef(this._positions,3*h,d),de.FromArrayToRef(this._positions,3*c,_),p.x=n*u.x+o*d.x+a*_.x,p.y=n*u.y+o*d.y+a*_.y,p.z=n*u.z+o*d.z+a*_.z,s?t.copyFromFloats(p.x,p.y,p.z):de.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(de.FromArrayToRef(this._normals,3*l,u),de.FromArrayToRef(this._normals,3*h,d),de.FromArrayToRef(this._normals,3*c,_),this._storedNormal.x=n*u.x+o*d.x+a*_.x,this._storedNormal.y=n*u.y+o*d.y+a*_.y,this._storedNormal.z=n*u.z+o*d.z+a*_.z)}clone(){const e=new EC(this.mesh);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=this.mesh?.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){de.FromArrayToRef(e.direction1,0,this.direction1),de.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class AC{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}bi.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";bi.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}";class PC{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){return this._updateEffect?.isReady()??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof CC&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new Ti("gpuUpdateParticles",this._updateEffectOptions,this._engine),new AC(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;ee)return void i(t[0],t[0],1);for(let s=0;s=r.gradient&&e<=n.gradient)return void i(r,n,(e-r.gradient)/(n.gradient-r.gradient))}const s=t.length-1;i(t[s],t[s],1)}}class wC{constructor(e){this.particleSystem=e,this.position=de.Zero(),this.direction=de.Zero(),this.color=new Ee(0,0,0,0),this.colorStep=new Ee(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new ue(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Ee(0,0,0,0),this._currentColor2=new Ee(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=wC._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID;let s;s=this._initialSpriteCellLoop?ae(e*t%this.lifeTime/this.lifeTime):ae(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=ge.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,ge.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(ge.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=wC._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new _e(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}wC._Count=0;bi.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.particlesVertexShader="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class NC extends rl{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Fi(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new X),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=fe.Identity(),this._inheritedVelocityOffset=new de,this.onDisposeObservable=new X,this.onStoppedObservable=new X,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Ee(0,0,0,0),this._colorDiff=new Ee(0,0,0,0),this._scaledDirection=de.Zero(),this._scaledGravity=de.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=e=>{},this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;return 0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new wC(this),this._prepareParticle(e),e},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=fe.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||se.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Fi(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new mC;let o=null;this.updateFunction=e=>{let t=null;this.noiseTexture&&(t=this.noiseTexture.getSize(),this.noiseTexture.getContent()?.then((e=>{o=e})));const i=e===this._particles;for(let s=0;sr.lifeTime){const e=r.age-a;n=(r.lifeTime-a)*n/e,r.age=r.lifeTime}const l=r.age/r.lifeTime;this._colorGradients&&this._colorGradients.length>0?DC.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==r._currentColorGradient&&(r._currentColor1.copyFrom(r._currentColor2),t.getColorToRef(r._currentColor2),r._currentColorGradient=e),Ee.LerpToRef(r._currentColor1,r._currentColor2,i,r.color)})):(r.colorStep.scaleToRef(n,this._scaledColorStep),r.color.addInPlace(this._scaledColorStep),r.color.a<0&&(r.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&DC.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==r._currentAngularSpeedGradient&&(r._currentAngularSpeed1=r._currentAngularSpeed2,r._currentAngularSpeed2=t.getFactor(),r._currentAngularSpeedGradient=e),r.angularSpeed=oe(r._currentAngularSpeed1,r._currentAngularSpeed2,i)})),r.angle+=r.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&DC.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==r._currentVelocityGradient&&(r._currentVelocity1=r._currentVelocity2,r._currentVelocity2=t.getFactor(),r._currentVelocityGradient=e),h*=oe(r._currentVelocity1,r._currentVelocity2,i)})),r.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&DC.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==r._currentLimitVelocityGradient&&(r._currentLimitVelocity1=r._currentLimitVelocity2,r._currentLimitVelocity2=t.getFactor(),r._currentLimitVelocityGradient=e);const s=oe(r._currentLimitVelocity1,r._currentLimitVelocity2,i);r.direction.length()>s&&r.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&DC.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==r._currentDragGradient&&(r._currentDrag1=r._currentDrag2,r._currentDrag2=t.getFactor(),r._currentDragGradient=e);const s=oe(r._currentDrag1,r._currentDrag2,i);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&r._localPosition?(r._localPosition.addInPlace(this._scaledDirection),de.TransformCoordinatesToRef(r._localPosition,this._emitterWorldMatrix,r.position)):r.position.addInPlace(this._scaledDirection),o&&t&&r._randomNoiseCoordinates1){const e=this._fetchR(r._randomNoiseCoordinates1.x,r._randomNoiseCoordinates1.y,t.width,t.height,o),i=this._fetchR(r._randomNoiseCoordinates1.z,r._randomNoiseCoordinates2.x,t.width,t.height,o),s=this._fetchR(r._randomNoiseCoordinates2.y,r._randomNoiseCoordinates2.z,t.width,t.height,o),a=ge.Vector3[0],l=ge.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*i-1)*this.noiseStrength.y,(2*s-1)*this.noiseStrength.z),a.scaleToRef(n,l),r.direction.addInPlace(l)}this.gravity.scaleToRef(n,this._scaledGravity),r.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&DC.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==r._currentSizeGradient&&(r._currentSize1=r._currentSize2,r._currentSize2=t.getFactor(),r._currentSizeGradient=e),r.size=oe(r._currentSize1,r._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&DC.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const s=oe(e.factor1,t.factor1,i),n=oe(e.factor2,t.factor2,i);r.remapData.x=s,r.remapData.y=n-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&DC.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const s=oe(e.factor1,t.factor1,i),n=oe(e.factor2,t.factor2,i);r.remapData.z=s,r.remapData.w=n-s}))),this._isAnimationSheetEnabled&&r.updateCellIndex(),r._inheritParticleInfoToSubEmitters(),r.age>=r.lifeTime&&(this._emitFromParticle(r),r._attachedSubEmitters&&(r._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),r._attachedSubEmitters=null),this.recycleParticle(r),i&&s--)}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,s){const r=new OC(t,i,s);e.push(r),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=Ae.Color3[0];for(let i=0;i{Ce.LerpToRef(s.color,r.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=Wo.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new MC(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const s=new IC(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,s,r){return r[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*s%s|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Ts(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(ys.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ys.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(ys.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ys.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||8===this.billboardMode||9===this.billboardMode){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Ts(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return void(this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3])));const e=[],t=[];let i=0;for(let s=0;s{this.start(0)}),e);else{if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==this.emitter?.getClassName().indexOf("Mesh")&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)8!==this.billboardMode&&9!==this.billboardMode||(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(de.TransformNormalToRef(e,this._emitterWorldMatrix,ge.Vector3[0]),e=ge.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}else{let e=t.direction;this.isLocal&&(de.TransformNormalToRef(e,this._emitterWorldMatrix,ge.Vector3[0]),e=ge.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===s?s=this._epsilon:1===s&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=fe.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=ae(this._actualFrame/this.targetStopDuration);DC.GetCurrentGradient(e,this._lifeTimeGradients,((i,s)=>{const r=i,n=s,o=r.getFactor(),a=n.getFactor(),l=(e-r.gradient)/(n.gradient-r.gradient);t.lifeTime=oe(o,a,l)}))}else t.lifeTime=ne(this.minLifeTime,this.maxLifeTime);const e=ne(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),de.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=ne(this.minSize,this.maxSize),t.scale.copyFromFloats(ne(this.minScaleX,this.maxScaleX),ne(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;DC.GetCurrentGradient(e,this._startSizeGradients,((e,i,s)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const r=oe(this._currentStartSize1,this._currentStartSize2,s);t.scale.scaleInPlace(r)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=ne(this.minAngularSpeed,this.maxAngularSpeed),t.angle=ne(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=ne(0,1);Ee.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new _e(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new de(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new de(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[ys.PositionKind,ys.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["invView","view","projection","textureMask","translationPivot","eyePosition"];return An(s),e&&s.push("particlesInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t){if(this._scene&&(Pn(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&0!==this._scene.fogMode&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===rl.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),9===this.billboardMode&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...NC._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode,this._useRampGradients)),e.push(...NC._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(gs(e,this._imageProcessingConfigurationDefines),vs(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new Fi(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join("\n");if(n.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return n}animate(e=!1){if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let t;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;DC.GetCurrentGradient(t,this._emitRateGradients,((t,i,s)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=oe(this._currentEmitRate1,this._currentEmitRate2,s)}))}t=e*this._scaledUpdateSpeed|0,this._newPartsExcess+=e*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(r.invertToRef(ge.Matrix[0]),i.setMatrix("invView",ge.Matrix[0])),void 0!==this._vertexArrayObject?this._scene?.forceWireframe?s.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&wn(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case rl.BLENDMODE_ADD:s.setAlphaMode(1);break;case rl.BLENDMODE_ONEONE:s.setAlphaMode(6);break;case rl.BLENDMODE_STANDARD:s.setAlphaMode(2);break;case rl.BLENDMODE_MULTIPLY:s.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?this._scene?.forceWireframe?s.drawElementsType(6,0,10,this._particles.length):s.drawArraysType(7,0,4,this._particles.length):this._scene?.forceWireframe?s.drawElementsType(1,0,10*this._particles.length):s.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===rl.BLENDMODE_MULTIPLYADD?this._render(rl.BLENDMODE_MULTIPLY)+this._render(rl.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var FC;!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(FC||(FC={}));class BC{constructor(e){if(this.particleSystem=e,this.type=FC.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=te("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof de?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new(te("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new de;const t=new BC(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,s=!1){throw vt("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new BC(BC._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}function LC(e,t){const i=new TC;return i.direction1=e,i.direction2=t,i}function kC(e=1,t=1){return new bC(e,t)}function VC(e=1,t=1){return new yC(e,t)}function UC(e=1,t=new de(0,1,0),i=new de(0,1,0)){return new SC(e,t,i)}function GC(e=1,t=1,i=1,s=0){return new vC(e,t,i,s)}function zC(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){return new xC(e,t,i,s,r)}function WC(e=1,t=Math.PI/4){return new gC(e,t)}class HC extends NC{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===FC.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))}}createPointEmitter(e,t){const i=LC(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=kC(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=VC(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new de(0,1,0),i=new de(0,1,0)){const s=UC(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=GC(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){const n=zC(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=WC(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new mC;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof HC?this._subEmitters.push([new BC(e)]):e instanceof BC?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===FC.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}}_onDispose(e=!1,t=!1){if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&this.particles?.forEach((e=>{if(e._attachedSubEmitters)for(let t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()})),t&&this.activeSubSystems)for(let e=this.activeSubSystems.length-1;e>=0;e-=1)this.activeSubSystems[e].dispose();if(this._subEmitters&&this._subEmitters.length){for(let e=0;e0?h.shaderOptions.defines.join("\n"):"";l=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new HC(n,r||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const s of e.subEmitters){const e=[];for(const r of s)e.push(BC.Parse(r,t,i));c.subEmitters.push(e)}}return HC._Parse(e,c,t,i),e.textureMask&&(c.textureMask=Ee.FromArray(e.textureMask)),e.worldOffset&&(c.worldOffset=de.FromArray(e.worldOffset)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),s||c.preventAutoStart||c.start(),c}serialize(e=!1){const t={};if(HC._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const s=[];for(const t of i)s.push(t.serialize(e));t.subEmitters.push(s)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,yt.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const s=t.getColorGradients();if(s){e.colorGradients=[];for(const t of s){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const t of r){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const t of n){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const _=t.getLifeTimeGradients();if(_){e.lifeTimeGradients=[];for(const t of _){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const p=t.getLimitVelocityGradients();if(p){e.limitVelocityGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){r=this.customShader;const e=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e);s[0]?s[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=HC.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}}HC.BILLBOARDMODE_Y=2,HC.BILLBOARDMODE_ALL=7,HC.BILLBOARDMODE_STRETCHED=8,HC.BILLBOARDMODE_STRETCHED_LOCAL=9,BC._ParseParticleSystem=HC.Parse;bi.IncludesShadersStore.clipPlaneFragmentDeclaration2="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";bi.ShadersStore.gpuRenderParticlesPixelShader="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;\n#include \n#include\n#include\n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include\n#include(color,gl_FragColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";bi.IncludesShadersStore.clipPlaneVertexDeclaration2="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;out float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;out float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;out float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;out float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;out float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;out float fClipDistance6;\n#endif\n";bi.ShadersStore.gpuRenderParticlesVertexShader="precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;attribute float age;attribute float life;attribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;attribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x;\n#ifdef BILLBOARD\nvec4 rotatedCorner;rotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n}";class XC extends rl{static get IsSupported(){if(!se.LastCreatedEngine)return!1;const e=se.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=LC(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=kC(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=VC(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new de(0,1,0),i=new de(0,1,0)){const s=UC(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=GC(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){const n=zC(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=WC(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new mC;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==HC.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(HC.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(HC.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((()=>{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Fi(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new X),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new IC(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){for(const e in this._drawWrappers){const t=this._drawWrappers[e];t.drawContext?.reset()}}_addFactorGradient(e,t,i){const s=new OC(t,i);e.push(s),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const s=this;s[t]&&(s[t].dispose(),s[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,s=null,r=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new X,this.onStoppedObservable=new X,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=fe.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||se.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!te("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(te("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!te("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(te("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Fi(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new Fi(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=t??{}).randomTextureSize||delete t.randomTextureSize;const n={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new mC;const a=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let l=[];for(let e=0;e0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),a=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new Ts(t,a,!1,this._attributesStrideSize),this._buffer1=new Ts(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new Ts(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let s=this._drawWrappers[e];s||(s=new Fi(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join("\n");if(s.defines!==r){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),s.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[ys.PositionKind,"age","life","size","angle"];return e||r.push(ys.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",ys.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return An(s),e&&s.push("sheetInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t=0){if(this._scene&&(Pn(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==dr.FOGMODE_NONE&&e.push("#define FOG")),t===HC.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case HC.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case HC.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case HC.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...XC._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===HC.BILLBOARDMODE_STRETCHED)),e.push(...XC._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(xs.PrepareUniforms(e,this._imageProcessingConfigurationDefines),xs.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const s=new Float32Array(this._rawTextureWidth);for(let t=0;t{s[t]=xe.Lerp(e.factor1,i.factor1,r)}))}this[t]=Wo.CreateRTexture(s,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=Ae.Color4[0];for(let i=0;i{Ee.LerpToRef(s.color1,r.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=Wo.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){const i=this._getWrapper(e),s=i.effect;this._engine.enableEffect(i);const r=this._scene?.getViewMatrix()||fe.IdentityReadOnly;if(s.setMatrix("view",r),s.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),s.setTexture("diffuseSampler",this.particleTexture),s.setVector2("translationPivot",this.translationPivot),s.setVector3("worldOffset",this.worldOffset),this.isLocal&&s.setMatrix("emitterWM",t),this._colorGradientsTexture?s.setTexture("colorGradientSampler",this._colorGradientsTexture):s.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();s.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;s.setVector3("eyePosition",e.globalPosition)}const n=s.defines;if(this._scene&&(In(s,this,this._scene),this.applyFog&&Nn(this._scene,void 0,s)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=r.clone();e.invert(),s.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&wn(n,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case HC.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case HC.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case HC.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case HC.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,s,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._scene?.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._scene?.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=ge.Matrix[0],fe.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const e=this.emitter;i=ge.Matrix[0],fe.TranslationToRef(e.x,e.y,e.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return e||t||(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),r=this.blendMode===HC.BLENDMODE_MULTIPLYADD?this._render(HC.BLENDMODE_MULTIPLY,i)+this._render(HC.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}rebuild(){const e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?(this._initialize(!0),this._rebuildingAfterContextLost=!1):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?r.shaderOptions.defines.join("\n"):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=XC.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return HC._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,a;t instanceof ki?o=t:(a=t,o=a.getEngine());const l=new XC(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",s=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(s,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),HC._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),s||l.preventAutoStart||l.start(),l}}class YC{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const s=Eu("emitterSphere",{diameter:e.diameter,segments:e.segments},i);s.renderingGroupId=t;const r=new yc("emitterSphereMaterial",i);r.emissiveColor=e.color,s.material=r;for(const e of this.systems)e.emitter=s;this._emitterNode=s}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,s){const r=new YC,n=this.BaseAssetsUrl+"/textures/";t=t||se.LastCreatedScene;for(const o of e.systems)r.systems.push(i?XC.Parse(o,t,n,!0,s):HC.Parse(o,t,n,!0,s));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&r.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:Ce.FromArray(i.color)},e.emitter.renderingGroupId,t)}return r}}YC.BaseAssetsUrl="https://assets.babylonjs.com/particles";class QC{static CreateDefault(e,t=500,i,s=!1){let r;return r=s?new XC("default system",{capacity:t},i):new HC("default system",t,i),r.emitter=e,r.particleTexture=new Vo("https://assets.babylonjs.com/textures/flare.png",r.getScene()),r.createConeEmitter(.1,Math.PI/4),r.color1=new Ee(1,1,1,1),r.color2=new Ee(1,1,1,1),r.colorDead=new Ee(1,1,1,0),r.minSize=.1,r.maxSize=.1,r.minEmitPower=2,r.maxEmitPower=2,r.updateSpeed=1/60,r.emitRate=30,r}static CreateAsync(e,t,i=!1,s){t||(t=se.LastCreatedScene);const r={};return t.addPendingData(r),new Promise(((n,o)=>{if(i&&!XC.IsSupported)return t.removePendingData(r),o("Particle system with GPU is not supported.");hs.LoadFile(`${QC.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(r);const o=JSON.parse(e.toString());return n(YC.Parse(o,t,i,s))}),void 0,void 0,void 0,(()=>(t.removePendingData(r),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new YC;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,s=!1,r="",n){return new Promise(((o,a)=>{const l=new At;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=s?XC.Parse(t,i,r,!1,n):HC.Parse(t,i,r,!1,n),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,s="",r){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((n,o)=>{const a=new At;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?XC.Parse(l,t,s,!1,r):HC.Parse(l,t,s,!1,r),h.snippetId=e,n(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}QC.BaseAssetsUrl=YC.BaseAssetsUrl,QC.SnippetUrl="https://snippet.babylonjs.com",QC.CreateFromSnippetAsync=QC.ParseFromSnippetAsync,G.AddParser(Rs.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=G.GetIndividualParser(Rs.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;ne.activeParticleCount?XC.Parse(e,t,i):HC.Parse(e,t,i))),gn.prototype.createEffectForParticles=function(e,t=[],i=[],s="",r,n,o,a){let l=[],h=[];const c=[];return a?a.fillUniformsAttributesAndSamplerNames(h,l,c):(l=HC._GetAttributeNamesOrOptions(),h=HC._GetEffectCreationOptions()),-1===s.indexOf(" BILLBOARD")&&(s+="\n#define BILLBOARD\n"),a?.isAnimationSheetEnabled&&-1===s.indexOf(" ANIMATESHEET")&&(s+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:a?.vertexShaderName??"particles",fragmentElement:e},l,h.concat(t),c.concat(i),s,r,n,o)},bo.prototype.getEmittedParticleSystems=function(){const e=[];for(let t=0;tt.sqDistance-e.sqDistance,this._materialSortFunction=(e,t)=>e.materialIndex-t.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||se.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=!!i?.computeBoundingBox&&i.computeBoundingBox,this._autoFixFaceOrientation=!!i?.autoFixFaceOrientation&&i.autoFixFaceOrientation,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new _o(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new qC}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){const e=Nu("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const e=new bo(this.name,this._scene);this.mesh=e}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&cn.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new cn;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,ys.PositionKind),e.set(this._normals32,ys.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,ys.UVKind),this._colors32.length>0&&e.set(this._colors32,ys.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let e=0;for(let t=0;td?d:s,i=Math.round(d/s),r=0):i=i>d?d:i;const _=[],p=[],f=[],m=[],g=[],v=de.Zero(),x=i;for(;ud-i&&(i=d-u),_.length=0,p.length=0,f.length=0,m.length=0,g.length=0;let t=0;for(let e=3*u;e<3*(u+i);e++){f.push(t);const i=o[e],s=3*i;if(_.push(n[s],n[s+1],n[s+2]),p.push(h[s],h[s+1],h[s+2]),a){const e=2*i;m.push(a[e],a[e+1])}if(l){const e=4*i;g.push(l[e],l[e+1],l[e+2],l[e+3])}t++}let s=this.nbParticles;const b=this._posToShape(_),T=this._uvsToShapeUV(m),y=f.slice(),S=g.slice(),C=p.slice();let E;for(v.copyFromFloats(0,0,0),E=0;E65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const e=null!==b.materialIndex?b.materialIndex:0;this.depthSortedParticles.push(new $C(d,t,r.length,e))}return b}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const s=this.particles,r=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh.getBoundingInfo();e&&(v.copyFrom(e.minimum),x.copyFrom(e.maximum))}A=this.particles[e]._pos;const D=A/3|0;R=4*D,M=2*D;for(let i=e;i<=t;i++){const e=this.particles[i];this.updateParticle(e);const t=e._model._shape,r=e._model._shapeUV,c=e._rotationMatrix,u=e.position,D=e.rotation,w=e.scaling,N=e._globalPosition;if(_){const t=this.depthSortedParticles[i];t.idx=e.idx,t.ind=e._ind,t.indicesLength=e._model._indicesLength,t.sqDistance=de.DistanceSquared(e.position,b)}if(e.alive&&(!e._stillInvisible||e.isVisible||this._recomputeInvisibles)){if(e.isVisible){e._stillInvisible=!1;const i=p[12];if(e.pivot.multiplyToRef(w,i),this.billboard&&(D.x=0,D.y=0),(this._computeParticleRotation||this.billboard)&&e.getRotationMatrix(s),null!==e.parentId){const t=this.getParticleById(e.parentId);if(t){const e=t._rotationMatrix,i=t._globalPosition,r=u.x*e[1]+u.y*e[4]+u.z*e[7],n=u.x*e[0]+u.y*e[3]+u.z*e[6],o=u.x*e[2]+u.y*e[5]+u.z*e[8];if(N.x=i.x+n,N.y=i.y+r,N.z=i.z+o,this._computeParticleRotation||this.billboard){const t=s.m;c[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],c[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],c[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],c[3]=t[4]*e[0]+t[5]*e[3]+t[6]*e[6],c[4]=t[4]*e[1]+t[5]*e[4]+t[6]*e[7],c[5]=t[4]*e[2]+t[5]*e[5]+t[6]*e[8],c[6]=t[8]*e[0]+t[9]*e[3]+t[10]*e[6],c[7]=t[8]*e[1]+t[9]*e[4]+t[10]*e[7],c[8]=t[8]*e[2]+t[9]*e[5]+t[10]*e[8]}}else e.parentId=null}else if(N.x=u.x,N.y=u.y,N.z=u.z,this._computeParticleRotation||this.billboard){const e=s.m;c[0]=e[0],c[1]=e[1],c[2]=e[2],c[3]=e[4],c[4]=e[5],c[5]=e[6],c[6]=e[8],c[7]=e[9],c[8]=e[10]}const n=p[11];for(e.translateFromPivot?n.setAll(0):n.copyFrom(i),O=0;O0)for(let t=0;t(this._isReady=!0,this._buildMesh(e))))}_buildMesh(e){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new cn;t.set(this._positions32,ys.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,ys.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,ys.ColorKind));const s=new bo(this.name,this._scene);t.applyToMesh(s,this._updatable),this.mesh=s,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let r=e;return r||(r=new yc("point cloud material",this._scene),r.emissiveColor=new Ce(i,i,i),r.disableLighting=!0,r.pointsCloud=!0,r.pointSize=this._size),s.material=r,new Promise((e=>e(s)))}_addParticle(e,t,i,s){const r=new JC(e,t,i,s,this);return this.particles.push(r),r}_randomUnitVector(e){e.position=new de(Math.random(),Math.random(),Math.random()),e.color=new Ee(1,1,1,1)}_getColorIndicesForCoord(e,t,i,s){const r=e._groupImageData,n=i*(4*s)+4*t,o=[n,n+1,n+2,n+3],a=o[1],l=o[2],h=o[3],c=r[o[0]],u=r[a],d=r[l],_=r[h];return new Ee(c/255,u/255,d/255,_)}_setPointsColorOrUV(e,t,i,s,r,n,o,a){a=a??0,i&&e.updateFacetData();const l=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(ys.PositionKind);const c=e.getIndices(),u=e.getVerticesData(ys.UVKind+(a?a+1:"")),d=e.getVerticesData(ys.ColorKind),_=de.Zero();e.computeWorldMatrix();const p=e.getWorldMatrix();if(!p.isIdentity()){h=h.slice(0);for(let e=0;e1&&(Ie=1),Me<0&&(Me=0),Me>1&&(Me=1),Ce.HSVtoRGBToRef(Re,Ie,Me,we),pe.set(we.r,we.g,we.b,1)):pe=ie.set(Math.random(),Math.random(),Math.random(),1),Fe.color=new Ee(pe.x,pe.y,pe.z,pe.w),this._colors.push(pe.x,pe.y,pe.z,pe.w))}}_colorFromTexture(e,t,i){if(null===e.material)return we.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const s=e.material.getActiveTextures();if(0===s.length)return we.Warn(e.name+"has no usable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const r=e.clone();r.setEnabled(!1),this._promises.push(new Promise((e=>{No.WhenAllReady(s,(()=>{let n=t._textureNb;n<0&&(n=0),n>s.length-1&&(n=s.length-1);const o=()=>{t._groupImgWidth=s[n].getSize().width,t._groupImgHeight=s[n].getSize().height,this._setPointsColorOrUV(r,t,i,!0,!0,void 0,void 0,s[n].coordinatesIndex),r.dispose(),e()};t._groupImageData=null;const a=s[n].readPixels();a?a.then((e=>{t._groupImageData=e,o()})):o()}))})))}_calculateDensity(e,t,i){let s,r,n,o,a,l,h,c,u,d,_,p;const f=de.Zero(),m=de.Zero(),g=de.Zero(),v=de.Zero(),x=de.Zero(),b=de.Zero();let T;const y=[];let S=0;const C=i.length/3;for(let e=0;e0;e--){const t=y[e];if(0===t)E[e]=0;else{const i=(t-y[e-1])/t*A,s=Math.floor(i),r=i-s,n=s+Number(Math.random()3)&&(n=tE.Random);const o=e.getVerticesData(ys.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new eE(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),n===tE.Color?l._textureNb=s||0:s=s||new Ee(1,1,1,1),n){case tE.Color:this._colorFromTexture(e,l,!1);break;case tE.UV:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case tE.Random:this._setPointsColorOrUV(e,l,!1);break;case tE.Stated:this._setPointsColorOrUV(e,l,!1,void 0,void 0,s,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,s,r){let n=i||tE.Random;(isNaN(n)||n<0||n>3)&&(n=tE.Random);const o=e.getVerticesData(ys.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new eE(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),n===tE.Color?l._textureNb=s||0:s=s||new Ee(1,1,1,1),n){case tE.Color:this._colorFromTexture(e,l,!0);break;case tE.UV:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case tE.Random:this._setPointsColorOrUV(e,l,!0);break;case tE.Stated:this._setPointsColorOrUV(e,l,!0,void 0,void 0,s,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const s=ge.Matrix[0],r=this.mesh,n=this._colors32,o=this._positions32,a=this._uvs32,l=ge.Vector3,h=l[5].copyFromFloats(1,0,0),c=l[6].copyFromFloats(0,1,0),u=l[7].copyFromFloats(0,0,1),d=l[8].setAll(Number.MAX_VALUE),_=l[9].setAll(-Number.MAX_VALUE);fe.IdentityToRef(s);let p=0;if(this.mesh?.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh?.getBoundingInfo();e&&(d.copyFrom(e.minimum),_.copyFrom(e.maximum))}p=0;let f=0,m=0,g=0;for(let i=e;i<=t;i++){const e=this.particles[i];p=e.idx,f=3*p,m=4*p,g=2*p,this.updateParticle(e);const t=e._rotationMatrix,r=e.position,n=e._globalPosition;if(this._computeParticleRotation&&e.getRotationMatrix(s),null!==e.parentId){const i=this.particles[e.parentId],o=i._rotationMatrix,a=i._globalPosition,l=r.x*o[1]+r.y*o[4]+r.z*o[7],h=r.x*o[0]+r.y*o[3]+r.z*o[6],c=r.x*o[2]+r.y*o[5]+r.z*o[8];if(n.x=a.x+h,n.y=a.y+l,n.z=a.z+c,this._computeParticleRotation){const e=s.m;t[0]=e[0]*o[0]+e[1]*o[3]+e[2]*o[6],t[1]=e[0]*o[1]+e[1]*o[4]+e[2]*o[7],t[2]=e[0]*o[2]+e[1]*o[5]+e[2]*o[8],t[3]=e[4]*o[0]+e[5]*o[3]+e[6]*o[6],t[4]=e[4]*o[1]+e[5]*o[4]+e[6]*o[7],t[5]=e[4]*o[2]+e[5]*o[5]+e[6]*o[8],t[6]=e[8]*o[0]+e[9]*o[3]+e[10]*o[6],t[7]=e[8]*o[1]+e[9]*o[4]+e[10]*o[7],t[8]=e[8]*o[2]+e[9]*o[5]+e[10]*o[8]}}else if(n.x=0,n.y=0,n.z=0,this._computeParticleRotation){const e=s.m;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10]}const a=l[11];e.translateFromPivot?a.setAll(0):a.copyFrom(e.pivot);const v=l[0];v.copyFrom(e.position);const x=v.x-e.pivot.x,b=v.y-e.pivot.y,T=v.z-e.pivot.z;let y=x*t[0]+b*t[3]+T*t[6],S=x*t[1]+b*t[4]+T*t[7],C=x*t[2]+b*t[5]+T*t[8];y+=a.x,S+=a.y,C+=a.z;const E=o[f]=n.x+h.x*y+c.x*S+u.x*C,A=o[f+1]=n.y+h.y*y+c.y*S+u.y*C,P=o[f+2]=n.z+h.z*y+c.z*S+u.z*C;if(this._computeBoundingBox&&(d.minimizeInPlaceFromFloats(E,A,P),_.maximizeInPlaceFromFloats(E,A,P)),this._computeParticleColor&&e.color){const t=e.color,i=this._colors32;i[m]=t.r,i[m+1]=t.g,i[m+2]=t.b,i[m+3]=t.a}if(this._computeParticleTexture&&e.uv){const t=e.uv,i=this._uvs32;i[g]=t.x,i[g+1]=t.y}}return r&&(i&&(this._computeParticleColor&&r.updateVerticesData(ys.ColorKind,n,!1,!1),this._computeParticleTexture&&r.updateVerticesData(ys.UVKind,a,!1,!1),r.updateVerticesData(ys.PositionKind,o,!1,!1)),this._computeBoundingBox&&(r.hasBoundingInfo?r.getBoundingInfo().reConstruct(d,_,r._worldMatrix):r.buildBoundingInfo(d,_,r._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){this.mesh?.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){return this._isVisibilityBoxLocked||this.mesh?.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new de(-t,-t,-t),new de(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}Object.defineProperty(Sn.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),Sn.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Sn.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Sn.prototype.setPhysicsLinkWith=function(e,t,i,s){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,da.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:s}),this):this};class pE{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw vt("")}constructor(e,t=pE.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new de(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new mv;return this._physicsPlugin.raycast(e,t,s,i),s}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(iE||(iE={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(sE||(sE={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(rE||(rE={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(nE||(nE={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(oE||(oE={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(aE||(aE={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(lE||(lE={})),function(e){e[e.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",e[e.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",e[e.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"}(hE||(hE={}));class fE{constructor(e,t,i,s){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disablePreStep=!0,this.disableSync=!1,this._isDisposed=!1,this._shape=null,!s)return;const r=s.getPhysicsEngine();if(!r)throw new Error("No Physics Engine available.");if(this._physicsEngine=r,2!=r.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const n=r.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");this._physicsPlugin=n,e.rotationQuaternion||(e.rotationQuaternion=pe.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=t!=lE.DYNAMIC;const o=e;o.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,o):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,r.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}getClassName(){return"PhysicsBody"}clone(e){const t=new fE(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t.setMassProperties(this.getMassProperties()),t.setLinearDamping(this.getLinearDamping()),t.setAngularDamping(this.getAngularDamping()),t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}get motionType(){return this._motionType}set shape(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)}get shape(){return this._shape}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this.disableSync=e!=lE.DYNAMIC,this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new de;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new de;return this.getAngularVelocityToRef(t,e),t}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyAngularImpulse(e,t){this._physicsPlugin.applyAngularImpulse(this,e,t)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}getCollisionEndedObservable(){return this._physicsPlugin.getCollisionEndedObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}setCollisionEndedCallbackEnabled(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new de;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){if(this._pluginDataInstances?.length>0){const i=t||0,s=this.transformNode._thinInstanceDataStorage.matrixData;s&&e.set(s[16*i+12],s[16*i+13],s[16*i+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,s){this._physicsPlugin.addConstraint(this,e,t,i,s)}syncWithBone(e,t,i,s,r,n){const o=this.transformNode;if(o.rotationQuaternion)if(r){const i=ge.Quaternion[0];e.getRotationQuaternionToRef(lr.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(lr.WORLD,t,o.rotationQuaternion);const a=ge.Vector3[0],l=ge.Vector3[1];n||((n=ge.Vector3[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}iterateOverAllInstances(e){if(this._pluginDataInstances?.length>0)for(let t=0;t{this.dispose()}))}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new qr(new de(-.5,-.5,-.5),new de(.5,.5,.5))}_hasVertices(e){return e?.getTotalVertices()>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=ge.Vector3[0];t.copyFrom(e.extendSize),t.scaleInPlace(2),t.multiplyInPlace(this.transformNode.scaling),t.x=Math.abs(t.x),t.y=Math.abs(t.y),t.z=Math.abs(t.z);const i=ge.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.scaling),!this._options.center){const t=new de;t.copyFrom(e.center),t.multiplyInPlace(this.transformNode.scaling),this._options.center=t}switch(this.type){case nE.SPHERE:!this._options.radius&&xe.WithinEpsilon(t.x,t.y,1e-4)&&xe.WithinEpsilon(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(we.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(t.x,t.y,t.z)/2);break;case nE.CAPSULE:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new de(0,i.y+e,0),this._options.pointB=this._options.pointB??new de(0,i.y+t.y-e,0)}break;case nE.CYLINDER:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new de(0,i.y,0),this._options.pointB=this._options.pointB??new de(0,i.y+t.y,0)}break;case nE.MESH:case nE.CONVEX_HULL:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case nE.BOX:this._options.extents=this._options.extents??new de(t.x,t.y,t.z),this._options.rotation=this._options.rotation??pe.Identity()}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class FE{}class BE{constructor(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=rE.HINGE,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=rE.HINGE,this._init()}getAggregate(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]}_createColliders(){this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);const e=this._config;for(let t=0;t{this._syncBonesAndBoxes()})),this._syncBonesToPhysics())}ragdoll(){this._ragdollMode=!0,this._skeleton.bones.forEach((e=>{e.linkTransformNode(null)}));for(let e=0;e{e.dispose()}))}}class LE{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=ge.Matrix[0];if(fe.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof bo?this._addMesh(e,i):e instanceof To&&this._addMesh(e.sourceMesh,i),t){const t=ge.Matrix[1];e.computeWorldMatrix().invertToRef(t);const s=ge.Matrix[2];t.multiplyToRef(i,s),e.getChildMeshes(!1).filter((e=>!e.physicsBody)).forEach((e=>{const t=e.computeWorldMatrix(),i=ge.Matrix[3];t.multiplyToRef(s,i),e instanceof bo?this._addMesh(e,i):e instanceof To&&this._addMesh(e.sourceMesh,i)}))}}_addMesh(e,t){const i=e.getVerticesData(ys.PositionKind)||[],s=i.length/3,r=this._vertices.length;for(let e=0;e0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._bodies.delete(t.hpBodyId[0]);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))}initBodyInstances(e,t,i){const s=i._thinInstanceDataStorage?.instancesCount??0,r=i._thinInstanceDataStorage.matrixData;r&&(this._createOrUpdateBodyInstances(e,t,r,0,s,!1),e._pluginDataInstances.forEach(((t,i)=>{this._bodies.set(t.hpBodyId[0],{body:e,index:i})})))}_createOrUpdateBodyInstances(e,t,i,s,r,n){const o=ge.Quaternion[0],a=fe.Identity();for(let l=s;lr){this._createOrUpdateBodyInstances(e,n,s,r,i,!1);const t=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];t[0]||(t[0]=e.shape?._pluginData[0]);for(let s=r;s{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t)}),i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:de.FromArray(e[0]),mass:e[1],inertia:de.FromArray(e[2]),inertiaOrientation:pe.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),null!=i.mass&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case lE.STATIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case lE.ANIMATED:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case lE.DYNAMIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC)}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._internalSetMotionType(e,t)}),i)}getMotionType(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(s){case this._hknp.MotionType.STATIC:return lE.STATIC;case this._hknp.MotionType.KINEMATIC:return lE.ANIMATED;case this._hknp.MotionType.DYNAMIC:return lE.DYNAMIC}throw new Error("Unknown motion type: "+s)}setActivationControl(e,t){switch(t){case hE.ALWAYS_ACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case hE.ALWAYS_INACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case hE.SIMULATION_CONTROLLED:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED)}}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const e=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(e[0]==this._hknp.Result.RESULT_OK)return e[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(s)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,(e=>{e.userMassProps=t,this._internalUpdateMassProperties(e)}),i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(s)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearDamping(e.hpBodyId,t)}),i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularDamping(e.hpBodyId,t)}),i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getLinearVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetLinearVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}_applyToBodyOrInstances(e,t,i){if(e._pluginDataInstances?.length>0&&void 0===i)for(let i=0;i{this._hknp.HP_Body_ApplyImpulse(e.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))}),s)}applyAngularImpulse(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_ApplyAngularImpulse(e.hpBodyId,this._bVecToV3(t))}),i)}applyForce(e,t,i,s){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,s)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getAngularVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetAngularVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}setPhysicsBodyTransformation(e,t){const i=e.transformNode;if(e.numInstances>0){const t=i._thinInstanceDataStorage.matrixData;if(!t)return;const s=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),t,0,s,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}setTargetTransform(e,t,i,s){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetTargetQTransform(e.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])}),s)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetGravityFactor(e.hpBodyId,t)}),i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}initShape(e,t,i){switch(t){case nE.SPHERE:{const t=i.radius||1,s=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateSphere(s,t)[1]}break;case nE.BOX:{const t=i.rotation?this._bQuatToV4(i.rotation):[0,0,0,1],s=i.extents?this._bVecToV3(i.extents):[1,1,1],r=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateBox(r,t,s)[1]}break;case nE.CAPSULE:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCapsule(t,s,r)[1]}break;case nE.CONTAINER:e._pluginData=this._hknp.HP_Shape_CreateContainer()[1];break;case nE.CYLINDER:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCylinder(t,s,r)[1]}break;case nE.CONVEX_HULL:case nE.MESH:{const s=i.mesh;if(!s)throw new Error("No mesh provided to create physics shape.");{const r=!!i.includeChildMeshes,n=t!=nE.CONVEX_HULL,o=new LE(s,n,s?.getScene());o.addNodeMeshes(s,r);const a=o.getVertices(this._hknp),l=a.numObjects/3;if(t==nE.CONVEX_HULL)e._pluginData=this._hknp.HP_Shape_CreateConvexHull(a.offset,l)[1];else{const t=o.getTriangles(this._hknp),i=t.numObjects/3;e._pluginData=this._hknp.HP_Shape_CreateMesh(a.offset,l,t.offset,i)[1],o.freeBuffer(this._hknp,t)}o.freeBuffer(this._hknp,a)}}break;case nE.HEIGHTFIELD:if(!(i.numHeightFieldSamplesX&&i.numHeightFieldSamplesZ&&i.heightFieldSizeX&&i.heightFieldSizeZ&&i.heightFieldData))throw new Error("Missing required heightfield parameters");{const t=i.numHeightFieldSamplesX*i.numHeightFieldSamplesZ,s=4*t,r=this._hknp._malloc(s),n=new Float32Array(this._hknp.HEAPU8.buffer,r,t);for(let e=0;e0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],s=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(s[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const r=this._hknp.HP_DebugGeometry_GetInfo(s[1])[1],n=new Float32Array(this._hknp.HEAPU8.buffer,r[0],3*r[1]),o=new Uint32Array(this._hknp.HEAPU8.buffer,r[2],3*r[3]),a=n.slice(0),l=o.slice(0);return this._hknp.HP_DebugGeometry_Release(s[1]),{positions:a,indices:l}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,s,r){const n=e.type,o=e.options;if(!n||!o)return void we.Warn("No constraint type or options. Constraint is invalid.");if(t._pluginDataInstances.length>0&&void 0===s||i._pluginDataInstances.length>0&&void 0===r)return void we.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");e._pluginData=e._pluginData??[];const a=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(a);const l=this._getPluginReference(t,s).hpBodyId,h=this._getPluginReference(i,r).hpBodyId;this._hknp.HP_Constraint_SetParentBody(a,l),this._hknp.HP_Constraint_SetChildBody(a,h),this._constraintToBodyIdPair.set(a[0],[l[0],h[0]]);const c=o.pivotA?this._bVecToV3(o.pivotA):this._bVecToV3(de.Zero()),u=o.axisA??new de(1,0,0),d=this._tmpVec3[0];o.perpAxisA?d.copyFrom(o.perpAxisA):u.getNormalToRef(d),this._hknp.HP_Constraint_SetAnchorInParent(a,c,this._bVecToV3(u),this._bVecToV3(d));const _=o.pivotB?this._bVecToV3(o.pivotB):this._bVecToV3(de.Zero()),p=o.axisB??new de(1,0,0),f=this._tmpVec3[0];if(o.perpAxisB?f.copyFrom(o.perpAxisB):p.getNormalToRef(f),this._hknp.HP_Constraint_SetAnchorInChild(a,_,this._bVecToV3(p),this._bVecToV3(f)),e._initOptions||(e._initOptions={axisA:u.clone(),axisB:p.clone(),perpAxisA:d.clone(),perpAxisB:f.clone(),pivotA:new de(c[0],c[1],c[2]),pivotB:new de(_[0],_[1],_[2])}),n==rE.LOCK)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==rE.DISTANCE){const e=o.maxDistance||0,t=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e)}else if(n==rE.HINGE)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==rE.PRISMATIC)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==rE.SLIDER)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==rE.BALL_AND_SOCKET)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else{if(n!=rE.SIX_DOF)throw new Error("Unsupported Constraint Type.");{const t=e;for(const e of t.limits){const t=this._constraintAxisToNative(e.axis);0==(e.minLimit??-1)&&0==(e.maxLimit??-1)?this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LOCKED):(null!=e.minLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e.minLimit)),null!=e.maxLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e.maxLimit))),e.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(a,t,e.stiffness),e.damping&&this._hknp.HP_Constraint_SetAxisDamping(a,t,e.damping)}}}const m=!!o.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(a,m),this._hknp.HP_Constraint_SetEnabled(a,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const e=this._constraintToBodyIdPair.get(i[0]);if(e){const i=this._bodies.get(e[0]),s=this._bodies.get(e[1]);i&&s&&t.push({parentBody:i.body,parentBodyIndex:i.index,childBody:s.body,childBodyIndex:s.index})}}return t}addConstraint(e,t,i,s,r){this.initConstraint(i,e,t,s,r)}setEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetEnabled(i,t)}getEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetEnabled(t)[1]}setCollisionsEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetCollisionsEnabled(i,t)}getCollisionsEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]}setAxisFriction(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(s,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null}setAxisMode(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(s,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const e=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(e)}return null}setAxisMinLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(s,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMaxLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(s,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMotorType(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(s,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null}setAxisMotorTarget(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(s,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null}setAxisMotorMaxForce(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(s,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null}disposeConstraint(e){for(const t of e._pluginData)this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t);e._pluginData.length=0}_populateHitData(e,t){const i=this._bodies.get(e[0][0]);t.body=i?.body,t.bodyIndex=i?.index;const s=this._shapes.get(e[1][0]);t.shape=s;const r=e[3],n=e[4],o=e[5];t.setHitData({x:n[0],y:n[1],z:n[2]},{x:r[0],y:r[1],z:r[2]},o)}raycast(e,t,i,s){const r=s?.membership??-1,n=s?.collideWith??-1;i.reset(e,t);const o=[BigInt(0)],a=[this._bVecToV3(e),this._bVecToV3(t),[r,n],!1,o];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[,e]=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1];this._populateHitData(e,i),i.calculateHitDistance()}}pointProximity(e,t){const i=e?.collisionFilter?.membership??-1,s=e?.collisionFilter?.collideWith??-1;t.reset();const r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[this._bVecToV3(e.position),e.maxDistance,[i,s],e.shouldHitTriggers,r];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,i]=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1];this._populateHitData(i,t),t.setHitDistance(e)}}shapeProximity(e,t,i){t.reset(),i.reset();const s=e.shape._pluginData,r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[s,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,r];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,s,r]=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1];this._populateHitData(s,t),this._populateHitData(r,i),t.setHitDistance(e),i.setHitDistance(e)}}shapeCast(e,t,i){t.reset(),i.reset();const s=e.shape._pluginData,r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[s,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,r];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,s,r]=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1];this._populateHitData(s,t),this._populateHitData(r,i),t.setHitFraction(e),i.setHitFraction(e)}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new X,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new X,this._bodyCollisionEndedObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t?i:0)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}setCollisionEndedCallbackEnabled(e,t){const i=this._getPluginReference(e);let s=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];s=t?s|this._hknp.EventType.COLLISION_FINISHED.value:s&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,s)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,s)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new GE;for(;e;){GE.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),s=this._bodies.get(t.bodyIdB);if(i&&s){const e={collider:i.body,colliderIndex:i.index,collidedAgainst:s.body,collidedAgainstIndex:s.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(e)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new UE,i=Number(this.world);for(;e;){UE.readToRef(this._hknp.HEAPU8.buffer,e,t);const s=this._bodies.get(t.contactOnA.bodyId),r=this._bodies.get(t.contactOnB.bodyId);if(s&&r){const e={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeCollisionValueToCollisionType(t.type)};if(e.type===aE.COLLISION_FINISHED)this.onCollisionEndedObservable.notifyObservers(e);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const i=de.Dot(this._tmpVec3[0],t.contactOnA.normal);e.point=t.contactOnA.position,e.distance=i,e.impulse=t.impulseApplied,e.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(e)}if(this._bodyCollisionObservable.size&&e.type!==aE.COLLISION_FINISHED){const i=this._bodyCollisionObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionObservable.get(t.contactOnB.bodyId);i?i.notifyObservers(e):n&&(e.collider=r.body,e.colliderIndex=r.index,e.collidedAgainst=s.body,e.collidedAgainstIndex=s.index,e.normal=t.contactOnB.normal,n.notifyObservers(e))}else if(this._bodyCollisionEndedObservable.size){const i=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);i?i.notifyObservers(e):n&&(e.collider=r.body,e.colliderIndex=r.index,e.collidedAgainst=s.body,e.collidedAgainstIndex=s.index,e.normal=t.contactOnB.normal,n.notifyObservers(e))}}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=BigInt(0),this._hknp.HP_World_Release(this.world),this.world=void 0}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case oE.POSITION:return this._hknp.ConstraintMotorType.POSITION;case oE.VELOCITY:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return oE.POSITION;case this._hknp.ConstraintMotorType.VELOCITY:return oE.VELOCITY}return oE.NONE}_materialCombineToNative(e){switch(e){case cE.GEOMETRIC_MEAN:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case cE.MINIMUM:return this._hknp.MaterialCombine.MINIMUM;case cE.MAXIMUM:return this._hknp.MaterialCombine.MAXIMUM;case cE.ARITHMETIC_MEAN:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case cE.MULTIPLY:return this._hknp.MaterialCombine.MULTIPLY}}_nativeToMaterialCombine(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return cE.GEOMETRIC_MEAN;case this._hknp.MaterialCombine.MINIMUM:return cE.MINIMUM;case this._hknp.MaterialCombine.MAXIMUM:return cE.MAXIMUM;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return cE.ARITHMETIC_MEAN;case this._hknp.MaterialCombine.MULTIPLY:return cE.MULTIPLY;default:return}}_constraintAxisToNative(e){switch(e){case sE.LINEAR_X:return this._hknp.ConstraintAxis.LINEAR_X;case sE.LINEAR_Y:return this._hknp.ConstraintAxis.LINEAR_Y;case sE.LINEAR_Z:return this._hknp.ConstraintAxis.LINEAR_Z;case sE.ANGULAR_X:return this._hknp.ConstraintAxis.ANGULAR_X;case sE.ANGULAR_Y:return this._hknp.ConstraintAxis.ANGULAR_Y;case sE.ANGULAR_Z:return this._hknp.ConstraintAxis.ANGULAR_Z;case sE.LINEAR_DISTANCE:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return iE.FREE;case this._hknp.ConstraintAxisLimitMode.LIMITED:return iE.LIMITED;case this._hknp.ConstraintAxisLimitMode.LOCKED:return iE.LOCKED}return iE.FREE}_limitModeToNative(e){switch(e){case iE.FREE:return this._hknp.ConstraintAxisLimitMode.FREE;case iE.LIMITED:return this._hknp.ConstraintAxisLimitMode.LIMITED;case iE.LOCKED:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return aE.COLLISION_STARTED;case this._hknp.EventType.COLLISION_FINISHED.value:return aE.COLLISION_FINISHED;case this._hknp.EventType.COLLISION_CONTINUED.value:return aE.COLLISION_CONTINUED}return aE.COLLISION_STARTED}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return aE.TRIGGER_ENTERED;case 16:return aE.TRIGGER_EXITED}return aE.TRIGGER_ENTERED}}dr.prototype.getPhysicsEngine=function(){return this._physicsEngine},dr.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(Rs.NAME_PHYSICSENGINE);i||(i=new WE(this),this._addComponent(i));try{if(t&&1!==t?.getPluginVersion()){if(2!==t?.getPluginVersion())throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new pE(e,t)}else this._physicsEngine=new gv(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return we.Error(e.message),!1}},dr.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},dr.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},dr.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},dr.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class WE{constructor(e){this.name=Rs.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new X,this.scene.onAfterPhysicsObservable=new X,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(xn.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),xn.prototype.getPhysicsBody=function(){return this.physicsBody},xn.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},xn.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};class HE{static GetContactPointToRef(e,t,i,s,r){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(1===o){const r=new Zo(t,i).intersectsMesh(e);if(r.hit&&r.pickedPoint)return s.copyFrom(r.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(s,r),!0;return!1}static HasAppliedForces(e,t){return e.getMotionType(t)===lE.STATIC||0===(e.getMassProperties(t)?.mass??0)||0===e.transformNode?.getTotalVertices()}static IsInsideCylinder(e,t,i,s){const r=ge.Vector3[0];return e.subtractToRef(t,r),Math.abs(r.x)<=i&&Math.abs(r.z)<=i&&r.y>=0&&r.y<=s}}class XE{constructor(e){this._hitData={force:new de,contactPoint:new de,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||we.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}applyRadialExplosionImpulse(e,t,i,s){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let r=!1;if("number"==typeof t){const e=t;(t=new $E).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new YE(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyImpulse(o.force,o.contactPoint),r&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,r,((e,t)=>{e.applyImpulse(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}applyRadialExplosionForce(e,t,i,s){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let r=!1;if("number"==typeof t){const e=t;(t=new $E).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new YE(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyForce(o.force,o.contactPoint),r&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,r,((e,t)=>{e.applyForce(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}_applicationForBodies(e,t,i,s,r){const n=Array(),o=this._physicsEngine.getBodies();for(const a of o)a.iterateOverAllInstances(((o,a)=>{e.getBodyHitData(o,t,i,a)&&(r(o,i),s&&n.push({body:o,hitData:this._copyPhysicsHitData(i)}))}));e.triggerAffectedBodiesCallback(n)}gravitationalField(e,t,i,s){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new $E).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}const r=new QE(this,this._scene,e,t);return r.dispose(!1),r}updraft(e,t,i,s,r){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new qE).radius=e,t.strength=i??t.strength,t.height=s??t.height,t.updraftMode=r??t.updraftMode}const n=new jE(this._scene,e,t);return n.dispose(!1),n}vortex(e,t,i,s){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new ZE).radius=e,t.strength=i??t.strength,t.height=s??t.height}const r=new KE(this._scene,e,t);return r.dispose(!1),r}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class YE{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new $E,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,s){const r=ge.Vector3[0];r.copyFrom(t).subtractInPlace(i);const n=ge.Vector3[1];if(!HE.GetContactPointToRef(e,i,r,n,s.instanceIndex))return!1;const o=de.Distance(i,n);if(o>this._options.radius)return!1;const a=this._options.falloff===uE.Constant?this._options.strength:this._options.strength*(1-o/this._options.radius);return r.scaleInPlace(a),s.force.copyFrom(r),s.contactPoint.copyFrom(n),s.distanceFromOrigin=o,!0}getBodyHitData(e,t,i,s){if(HE.HasAppliedForces(e,s))return!1;const r=e.transformNode,n=e.getObjectCenterWorld(s);return i.instanceIndex=s,this._getHitData(r,n,t,i)}getImpostorHitData(e,t,i){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const s=e.object;if(!this._intersectsWithSphere(s,t,this._options.radius))return!1;const r=e.getObjectCenter();return this._getHitData(s,r,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_prepareSphere(){this._sphere||(this._sphere=Eu("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class QE{constructor(e,t,i,s){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=s,this._dataFetched=!1,this._options={...new $E,...this._options},this._tickCallback=()=>this._tick(),this._options.strength=-1*this._options.strength}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_tick(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);e&&(this._sphere=e.getData().sphere?.clone("radialExplosionEventSphereClone"))}}}class jE{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=de.Zero(),this._originDirection=de.Zero(),this._cylinderPosition=de.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new qE,...this._options},this._origin.addToRef(new de(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new de(0,this._options.height,0),this._originTop),this._options.updraftMode===dE.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===dE.Perpendicular?this._originDirection:e.subtract(this._originTop);const s=de.Distance(this._origin,e),r=-1*this._options.strength,n=i.multiplyByFloats(r,r,r);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=s}_getBodyHitData(e,t,i){if(HE.HasAppliedForces(e))return!1;const s=e.getObjectCenterWorld(i);return!!HE.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(s,t),!0}_tick(){const e=jE._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=lu("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}jE._HitData={force:new de,contactPoint:new de,distanceFromOrigin:0};class KE{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=de.Zero(),this._cylinderPosition=de.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new ZE,...this._options},this._origin.addToRef(new de(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new de(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const s=KE._OriginOnPlane;s.set(this._origin.x,t.y,this._origin.z);const r=ge.Vector3[0];t.subtractToRef(s,r);const n=ge.Vector3[1];if(!HE.GetContactPointToRef(e,s,r,n,i.instanceIndex))return!1;const o=de.Distance(n,s)/this._options.radius,a=ge.Vector3[2];let l,h,c;if(n.normalizeToRef(a),o>this._options.centripetalForceThreshold&&a.negateInPlace(),o>this._options.centripetalForceThreshold)l=a.x*this._options.centripetalForceMultiplier,h=a.y*this._options.updraftForceMultiplier,c=a.z*this._options.centripetalForceMultiplier;else{const e=de.Cross(s,t).normalize();l=(e.x+a.x)*this._options.centrifugalForceMultiplier,h=this._originTop.y*this._options.updraftForceMultiplier,c=(e.z+a.z)*this._options.centrifugalForceMultiplier}const u=ge.Vector3[3];return u.set(l,h,c),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=o,!0}_getBodyHitData(e,t,i){if(HE.HasAppliedForces(e,i))return!1;const s=e.transformNode,r=e.getObjectCenterWorld(i);return!!HE.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,r,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(i,s,t),!0}_tick(){const e=KE._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=lu("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}KE._OriginOnPlane=de.Zero(),KE._HitData={force:new de,contactPoint:new de,distanceFromOrigin:0};class $E{constructor(){this.radius=5,this.strength=10,this.falloff=uE.Constant,this.sphere={segments:32,diameter:1}}}class qE{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=dE.Center}}class ZE{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(uE||(uE={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(dE||(dE={}));class JE extends fv{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class eA extends fv{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}bi.ShadersStore.blackAndWhitePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";class tA extends qa{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,s){return yt.Parse((()=>new tA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([st()],tA.prototype,"degree",void 0),ee("BABYLON.BlackAndWhitePostProcess",tA);class iA{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=s.attachPostProcess(e);this._indicesForCamera[r].push(t)})),this._cameras[r]||(this._cameras[r]=s)}}_detachCameras(e){const t=hs.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=hs.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}bi.ShadersStore.extractHighlightsPixelShader="#include\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";class sA extends qa{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,Y)),e.setFloat("exposure",this._exposure)}))}}qe([st()],sA.prototype,"threshold",void 0),ee("BABYLON.ExtractHighlightsPostProcess",sA);bi.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";class rA extends qa{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}qe([st()],rA.prototype,"weight",void 0),ee("BABYLON.BloomMergePostProcess",rA);class nA extends iA{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new sA("highlights",1,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new pm("horizontal blur",new ue(1,0),10,t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new pm("vertical blur",new ue(0,1),10,t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new rA("bloomMerge",this._downscale,this._blurY,i,t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,s){return yt.Parse((()=>new oA(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}qe([st()],oA.prototype,"aberrationAmount",void 0),qe([st()],oA.prototype,"radialIntensity",void 0),qe([st()],oA.prototype,"direction",void 0),qe([st()],oA.prototype,"centerPosition",void 0),qe([st()],oA.prototype,"screenWidth",void 0),qe([st()],oA.prototype,"screenHeight",void 0),ee("BABYLON.ChromaticAberrationPostProcess",oA);bi.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";class aA extends qa{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void we.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}qe([st()],aA.prototype,"lensSize",void 0),qe([st()],aA.prototype,"fStop",void 0),qe([st()],aA.prototype,"focusDistance",void 0),qe([st()],aA.prototype,"focalLength",void 0),ee("BABYLON.CircleOfConfusionPostProcess",aA);bi.ShadersStore.colorCorrectionPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";class lA extends qa{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const a=s?.getScene()||null;this._colorTableTexture=new Vo(t,a,!0,!1,Vo.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Vo.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Vo.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return yt.Parse((()=>new lA(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([st()],lA.prototype,"colorTableUrl",void 0),ee("BABYLON.ColorCorrectionPostProcess",lA);bi.ShadersStore.convolutionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";class hA extends qa{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return yt.Parse((()=>new hA(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,s)}}hA.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],hA.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],hA.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],hA.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],hA.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],hA.GaussianKernel=[0,1,0,1,1,1,0,1,0],qe([st()],hA.prototype,"kernel",void 0),ee("BABYLON.ConvolutionPostProcess",hA);class cA extends pm{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=null,l=Vo.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,_=5){super(e,i,s,r,n,2,h,c,u,"#define DOF 1\n",d,_),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}qe([st()],cA.prototype,"direction",void 0),ee("BABYLON.DepthOfFieldBlurPostProcess",cA);bi.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";class uA extends qa{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,a,l,null,h,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(s.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,s,r,n)}}var dA;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(dA||(dA={}));class _A extends iA{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=dA.Low,s=0,r=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new aA("circleOfConfusion",t,1,null,Vo.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let a=1,l=15;switch(i){case dA.High:a=3,l=51;break;case dA.Medium:a=2,l=31;break;default:l=15,a=1}const h=l/Math.pow(2,a-1);let c=1;for(let t=0;tnew pA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ee("BABYLON.DisplayPassPostProcess",pA);bi.ShadersStore.filterPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";class fA extends qa{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return yt.Parse((()=>new fA(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([pt()],fA.prototype,"kernelMatrix",void 0),ee("BABYLON.FilterPostProcess",fA);bi.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();if(!e)return null;const t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,s){return yt.Parse((()=>new mA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ee("BABYLON.FxaaPostProcess",mA);bi.ShadersStore.grainPixelShader="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";class gA extends qa{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,s){return yt.Parse((()=>new gA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([st()],gA.prototype,"intensity",void 0),qe([st()],gA.prototype,"animated",void 0),ee("BABYLON.GrainPostProcess",gA);bi.ShadersStore.highlightsPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }";class vA extends qa{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0){super(e,"highlights",null,null,t,i,s,r,n,null,o)}}bi.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";class xA extends qa{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=se.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new xs}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,o=0,a){super(e,"imageProcessing",[],[],t,i,s,r,n,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines)this._defines[t]&&(e+=`#define ${t};\n`);const t=["textureSampler"],i=["scale"];xs&&(xs.PrepareSamplers(t,this._defines),xs.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}qe([st()],xA.prototype,"_fromLinearSpace",void 0);bi.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";bi.ShadersStore.geometryPixelShader="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[RENDER_TARGET_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";bi.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";bi.IncludesShadersStore.geometryUboDeclaration="#include\n";bi.ShadersStore.geometryVertexShader="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;vNormalW=normalUpdated;\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";const bA=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];An(bA);class TA{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((()=>{})))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===TA.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===TA.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===TA.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===TA.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===TA.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case TA.POSITION_TEXTURE_TYPE:return this._positionIndex;case TA.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case TA.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case TA.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case TA.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}constructor(e,t=1,i=15,s){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Ee(0,0,0,0),this._clearDepthColor=new Ee(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=s||{},TA._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[ys.PositionKind,ys.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&lc.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&s.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&s.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&s.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&s.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&s.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&s.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&s.push("#define REFLECTIVITYCOLOR"))}e&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(ys.UVKind)&&(r.push(ys.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(ys.UV2Kind)&&(r.push(ys.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),-1!==this._depthIndex&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&s.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&s.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(ys.MatricesIndicesKind),r.push(ys.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(ys.MatricesIndicesExtraKind),r.push(ys.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),s.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(s.push("#define NUM_BONE_INFLUENCERS 0"),s.push("#define BONETEXTURE false"),s.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let a=0;o&&(a=o.numMaxInfluencers||o.numInfluencers,a>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Fn(r,n,a))),t&&(s.push("#define INSTANCES"),Ln(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),Pn(i,this._scene,s);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=s.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:r,uniformsNames:bA,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),u),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[TA.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[TA.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[TA.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[TA.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[TA.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,s]=this._assignRenderTargetIndices();let r=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2);const n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],a=[];for(const e of s)e?(o.push(e.textureType),a.push(e.textureFormat)):(o.push(r),a.push(5));if(this._normalsAreUnsigned=11===o[TA.NORMAL_TEXTURE_TYPE]||13===o[TA.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new Ex("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:a,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Vo.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Vo.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],c=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:u),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(_),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(u)})),this._resizeObserver=e.onResizeObservable.add((()=>{if(this._multiRenderTarget){const t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}}));const p=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:fe.Identity(),viewProjection:s.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=r.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,a)){const h=e._getDrawWrapper();if(!h)return;const c=h.effect;let u;r.enableEffect(h),a||t._bind(e,c,n.fillMode),this._useUbo?(Vn(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",s.getTransformMatrix()),c.setMatrix("view",s.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!n.backFaceCulling&&null===t.overrideMaterialSideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=t.overrideMaterialSideOrientation,null===u&&(u=n.sideOrientation),e<0&&(u=u===uo.ClockWiseSideOrientation?uo.CounterClockWiseSideOrientation:uo.ClockWiseSideOrientation)}if(n._preBind(h,u),n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.bumpTexture&&s.getEngine().getCaps().standardDerivatives&&lc.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),In(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){const i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}kn(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),a&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,s)=>{if((s||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(r.length){for(e.setColorWrite(!1),n=0;n{throw vt("GeometryBufferRendererSceneComponent")};class yA{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(dr.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),dr.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new TA(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},dr.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class SA{constructor(e){this.name=Rs.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Rs.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}TA._SceneComponentInitialization=e=>{let t=e._getComponent(Rs.NAME_GEOMETRYBUFFERRENDERER);t||(t=new SA(e),e._addComponent(t))};bi.ShadersStore.motionBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";class CA extends qa{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new yA)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return we.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=fe.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new ue(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(TA.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=ge.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new ue(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(TA.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,s){return yt.Parse((()=>new CA(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}qe([st()],CA.prototype,"motionStrength",void 0),qe([st()],CA.prototype,"motionBlurSamples",null),qe([st()],CA.prototype,"isObjectBased",null),ee("BABYLON.MotionBlurPostProcess",CA);bi.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class EA extends qa{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,s,r,n,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Vo(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,s){return yt.Parse((()=>new EA(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([st()],EA.prototype,"color",void 0),qe([st()],EA.prototype,"depth",void 0),qe([st()],EA.prototype,"colorLevel",void 0),qe([st()],EA.prototype,"refractionTextureUrl",void 0),ee("BABYLON.RefractionPostProcess",EA);bi.ShadersStore.sharpenPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";class AA extends qa{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return yt.Parse((()=>new AA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}qe([st()],AA.prototype,"colorAmount",void 0),qe([st()],AA.prototype,"edgeAmount",void 0),ee("BABYLON.SharpenPostProcess",AA);class PA{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(hs.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(hs.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=hs.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}qe([st()],PA.prototype,"_name",void 0);class RA{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(dr.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(Rs.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new IA(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new RA}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class IA{constructor(e){this.name=Rs.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Rs.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class MA extends PA{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new nA(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen),!0),this.depthOfField=new _A(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add((()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new nA(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new oA("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,Vo.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new iA(o,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new gA("Grain",1,null,Vo.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new iA(o,this.GrainPostProcessId,(()=>this.grain),!0);let a=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,a?hs.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),a=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new xA("imageProcessing",1,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new iA(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new mA("fxaa",1,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new iA(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&we.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew MA(e._name,e._name._hdr,t)),e,t,i)}}qe([st()],MA.prototype,"sharpenEnabled",null),qe([st()],MA.prototype,"bloomKernel",null),qe([st()],MA.prototype,"_bloomWeight",void 0),qe([st()],MA.prototype,"_bloomThreshold",void 0),qe([st()],MA.prototype,"_hdr",void 0),qe([st()],MA.prototype,"bloomWeight",null),qe([st()],MA.prototype,"bloomThreshold",null),qe([st()],MA.prototype,"bloomScale",null),qe([st()],MA.prototype,"bloomEnabled",null),qe([st()],MA.prototype,"depthOfFieldEnabled",null),qe([st()],MA.prototype,"depthOfFieldBlurLevel",null),qe([st()],MA.prototype,"fxaaEnabled",null),qe([st()],MA.prototype,"samples",null),qe([st()],MA.prototype,"imageProcessingEnabled",null),qe([st()],MA.prototype,"glowLayerEnabled",null),qe([st()],MA.prototype,"chromaticAberrationEnabled",null),qe([st()],MA.prototype,"grainEnabled",null),ee("BABYLON.DefaultRenderingPipeline",MA);bi.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";bi.ShadersStore.depthOfFieldPixelShader="uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}\nif (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}\nif (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}\n";class OA extends PA{constructor(e,t,i,s=1,r){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=void 0!==t.dof_gain?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=void 0!==t.dof_focus_distance?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=void 0===t.dof_pentagon||t.dof_pentagon,this._blurNoise=void 0===t.blur_noise||t.blur_noise,this._createChromaticAberrationPostProcess(s),this._createHighlightsPostProcess(s),this._createDepthOfFieldPostProcess(s/4),this.addEffect(new iA(i.getEngine(),this.LensChromaticAberrationEffect,(()=>this._chromaticAberrationPostProcess),!0)),this.addEffect(new iA(i.getEngine(),this.HighlightsEnhancingEffect,(()=>this._highlightsPostProcess),!0)),this.addEffect(new iA(i.getEngine(),this.LensDepthOfFieldEffect,(()=>this._depthOfFieldPostProcess),!0)),-1===this._highlightsGain&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),r&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new qa("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,Vo.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=e=>{e.setFloat("chromatic_aberration",this._chromaticAberration),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new qa("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,Vo.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=e=>{e.setFloat("gain",this._highlightsGain),e.setFloat("threshold",this._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new qa("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,Vo.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=e=>{e.setTexture("depthSampler",this._depthTexture),e.setTexture("grainSampler",this._grainTexture),e.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),e.setFloat("grain_amount",this._grainAmount),e.setBool("blur_noise",this._blurNoise),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("distortion",this._distortion),e.setBool("dof_enabled",-1!==this._dofDistance),e.setFloat("screen_distance",1/(.1-1/this._dofDistance)),e.setFloat("aperture",this._dofAperture),e.setFloat("darken",this._dofDarken),e.setFloat("edge_blur",this._edgeBlur),e.setBool("highlights",-1!==this._highlightsGain),this._scene.activeCamera&&(e.setFloat("near",this._scene.activeCamera.minZ),e.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){const e=new Uint8Array(1048576);for(let t=0;t1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;const t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,s=1-.85*e,r=Math.sqrt(1-s*s);return new de(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===Kr.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",wA.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const t=this._scene.getEngine().getRenderWidth()/2,i=this._scene.getEngine().getRenderHeight()/2,s=this._scene.activeCamera.orthoLeft??-t,r=this._scene.activeCamera.orthoRight??t,n=this._scene.activeCamera.orthoBottom??-i,o=this._scene.activeCamera.orthoTop??i;e.setMatrix3x3("depthProjection",wA.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(r-s)),e.setFloat("yViewport",.5*(o-n))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new DA)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new qa("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",ge.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const e=new Uint8Array(65536),t=ue.Zero();for(let i=0;inew wA(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}wA.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],wA.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],qe([st()],wA.prototype,"totalStrength",void 0),qe([st()],wA.prototype,"maxZ",void 0),qe([st()],wA.prototype,"minZAspect",void 0),qe([st("epsilon")],wA.prototype,"_epsilon",void 0),qe([st("samples")],wA.prototype,"_samples",void 0),qe([st("textureSamples")],wA.prototype,"_textureSamples",void 0),qe([st()],wA.prototype,"_forceGeometryBuffer",void 0),qe([st()],wA.prototype,"_ratio",void 0),qe([st()],wA.prototype,"_textureType",void 0),qe([st()],wA.prototype,"radius",void 0),qe([st()],wA.prototype,"base",void 0),qe([st("bypassBlur")],wA.prototype,"_bypassBlur",void 0),qe([st("expensiveBlur")],wA.prototype,"_expensiveBlur",void 0),qe([st()],wA.prototype,"bilateralSamples",void 0),qe([st()],wA.prototype,"bilateralSoften",void 0),qe([st()],wA.prototype,"bilateralTolerance",void 0),ee("BABYLON.SSAO2RenderingPipeline",wA);bi.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)\n{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}\nvoid main()\n{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new qa("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new qa("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",ge.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const e=new Uint8Array(1048576);for(let t=0;t0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const i=this._geometryBufferRenderer,s=this._prePassRenderer;if(!s&&!i)return;if(i){const t=i.getTextureIndex(TA.POSITION_TEXTURE_TYPE),s=i.getTextureIndex(TA.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[s])}else if(s){const t=s.getIndex(1),i=s.getIndex(3),r=s.getIndex(6);e.setTexture("normalSampler",s.getRenderTarget().textures[r]),e.setTexture("positionSampler",s.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",s.getRenderTarget().textures[i])}const r=t.activeCamera;if(!r)return;const n=r.getViewMatrix(!0),o=r.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,s){return yt.Parse((()=>new BA(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}qe([st()],BA.prototype,"threshold",void 0),qe([st()],BA.prototype,"strength",void 0),qe([st()],BA.prototype,"reflectionSpecularFalloffExponent",void 0),qe([st()],BA.prototype,"step",void 0),qe([st()],BA.prototype,"roughnessFactor",void 0),qe([st()],BA.prototype,"enableSmoothReflections",null),qe([st()],BA.prototype,"reflectionSamples",null),qe([st()],BA.prototype,"smoothSteps",null),ee("BABYLON.ScreenSpaceReflectionPostProcess",BA);bi.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}\nvec3 pattern(vec2 uv)\n{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";class LA extends PA{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer())return void we.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,s=null,r){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new BA("HDRPass",t,e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new iA(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new qa("HDRPass","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.originalPostProcess})),this.addEffect(new iA(t.getEngine(),"HDRPassPostProcess",(()=>this.originalPostProcess),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new qa("HDRDepthOfFieldSource","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new iA(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new qa("HDRVLSFinal","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new iA(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new qa("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new iA(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new qa("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new iA(t.getEngine(),"HDRPostHDReDepthOfFieldSource",(()=>this.hdrFinalPostProcess),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new mA("fxaa",1,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new iA(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&we.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new qa("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const s=this.downSampleX4PostProcess.width,r=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/s),i[t+1]=(n+.5)*(1/r),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new iA(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new qa("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,s=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*s,i[2]=.5*t,i[3]=.5*s,i[4]=-.5*t,i[5]=-.5*s,i[6]=.5*t,i[7]=-.5*s,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new iA(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new pm("HDRBlurH_"+i,new ue(1,0),this[s],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new pm("HDRBlurV_"+i,new ue(0,1),this[s],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add((()=>{const e=n.width/r.getRenderWidth();n.kernel=this[s]*e})),o.onActivateObservable.add((()=>{const e=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*e:this[s]*e})),this.addEffect(new iA(e.getEngine(),"HDRBlurH"+i,(()=>n),!0)),this.addEffect(new iA(e.getEngine(),"HDRBlurV"+i,(()=>o),!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new qa("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new iA(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new qa("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const r=ue.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",s.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",r)}},this.addEffect(new iA(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new qa("HDRVLSMerge","standard",[],["originalSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new iA(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,LA.LuminanceSteps);this.luminancePostProcess=new qa("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;s[0]=-.5*t,s[1]=.5*i,s[2]=.5*t,s[3]=.5*i,s[4]=-.5*t,s[5]=-.5*i,s[6]=.5*t,s[7]=-.5*i,e.setArray2("lumOffsets",s)},this.addEffect(new iA(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let s=LA.LuminanceSteps-1;s>=0;s--){i=Math.pow(3,s);let r="#define LUMINANCE_DOWN_SAMPLE\n";0===s&&(r+="#define FINAL_DOWN_SAMPLER");const n=new qa("HDRLuminanceDownSample"+s,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,t);this.luminanceDownSamplePostProcesses.push(n)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const s=new Array(18);t.onApply=e=>{if(!r)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)s[n]=e/r.width,s[n+1]=t/r.height,n+=2;e.setArray2("dsOffsets",s),e.setFloat("halfDestPixelSize",.5/r.width),r=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new _e(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new iA(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new qa("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const e=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*e?s-=this.hdrIncreaseRate*e:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=xe.Clamp(s,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new iA(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new qa("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new iA(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new qa("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new iA(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new ue(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=fe.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=fe.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let n=de.Dot(t.toVector3(),new de(1,0,0))+de.Dot(i.toVector3(),new de(0,0,1));n*=4;const o=fe.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),a=r.multiply(o).multiply(s);e.setMatrix("lensStarMatrix",a),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new qa("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new iA(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new CA("HDRMotionBlur",e,t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new qa("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,s=fe.Identity();const r=fe.Identity();let n=fe.Identity();const o=ue.Zero();this.motionBlurPostProcess.onApply=t=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),t.setMatrix("inverseViewProjection",r),t.setMatrix("prevViewProjection",s),s=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",o),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new iA(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew LA(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&yt.Parse((()=>s.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),s}}LA.LuminanceSteps=6,qe([st()],LA.prototype,"brightThreshold",void 0),qe([st()],LA.prototype,"blurWidth",void 0),qe([st()],LA.prototype,"horizontalBlur",void 0),qe([st()],LA.prototype,"exposure",null),qe([rt("lensTexture")],LA.prototype,"lensTexture",void 0),qe([st()],LA.prototype,"volumetricLightCoefficient",void 0),qe([st()],LA.prototype,"volumetricLightPower",void 0),qe([st()],LA.prototype,"volumetricLightBlurScale",void 0),qe([st()],LA.prototype,"hdrMinimumLuminance",void 0),qe([st()],LA.prototype,"hdrDecreaseRate",void 0),qe([st()],LA.prototype,"hdrIncreaseRate",void 0),qe([st()],LA.prototype,"hdrAutoExposure",null),qe([rt("lensColorTexture")],LA.prototype,"lensColorTexture",void 0),qe([st()],LA.prototype,"lensFlareStrength",void 0),qe([st()],LA.prototype,"lensFlareGhostDispersal",void 0),qe([st()],LA.prototype,"lensFlareHaloWidth",void 0),qe([st()],LA.prototype,"lensFlareDistortionStrength",void 0),qe([st()],LA.prototype,"lensFlareBlurWidth",void 0),qe([rt("lensStarTexture")],LA.prototype,"lensStarTexture",void 0),qe([rt("lensFlareDirtTexture")],LA.prototype,"lensFlareDirtTexture",void 0),qe([st()],LA.prototype,"depthOfFieldDistance",void 0),qe([st()],LA.prototype,"depthOfFieldBlurWidth",void 0),qe([st()],LA.prototype,"motionStrength",null),qe([st()],LA.prototype,"objectBasedMotionBlur",null),qe([st()],LA.prototype,"_ratio",void 0),qe([st()],LA.prototype,"BloomEnabled",null),qe([st()],LA.prototype,"DepthOfFieldEnabled",null),qe([st()],LA.prototype,"LensFlareEnabled",null),qe([st()],LA.prototype,"HDREnabled",null),qe([st()],LA.prototype,"VLSEnabled",null),qe([st()],LA.prototype,"MotionBlurEnabled",null),qe([st()],LA.prototype,"fxaaEnabled",null),qe([st()],LA.prototype,"screenSpaceReflectionsEnabled",null),qe([st()],LA.prototype,"volumetricLightStepsCount",null),qe([st()],LA.prototype,"motionBlurSamples",null),qe([st()],LA.prototype,"samples",null),ee("BABYLON.StandardRenderingPipeline",LA);class kA{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}bi.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nndc.z=-projection[2].z-projection[3].z/depth;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n";bi.ShadersStore.screenSpaceReflection2PixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";bi.ShadersStore.screenSpaceReflection2BlurPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}\n";bi.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";const VA=fe.Compose(new de(.5,.5,.5),pe.Identity(),new de(.5,.5,.5)),UA=fe.Compose(new de(.5,.5,1),pe.Identity(),new de(.5,.5,0));class GA extends PA{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,s=!1,r=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const e=t.getRenderTarget();e&&e.textures&&(i=e.textures[t.getIndex(4)].getSize())}else this._ssrPostProcess?.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(this._geometryBufferRenderer?.generateNormalsInWorldSpace??this._prePassRenderer?.generateNormalsInWorldSpace)&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),this._geometryBufferRenderer?.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL"),this._ssrPostProcess?.updateEffect(e.join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const e=this._cameras?.[0];e&&(this._depthRendererCamera=e,this._depthRenderer=new $g(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),e.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new iA(e,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new iA(e,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new iA(e,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===s||this._depthRenderer.getDepthMap().resize({width:i,height:s})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;-1!==e&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){for(let e=0;e{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(TA.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),s=i.getIndex(3),r=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[r]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[s])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(),n=s.getProjectionMatrix();n.invertToRef(ge.Matrix[0]),r.invertToRef(ge.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",ge.Matrix[1]),e.setMatrix("invProjectionMatrix",ge.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();fe.ScalingToRef(o.width,o.height,1,ge.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?UA:VA,ge.Matrix[3]),ge.Matrix[3].multiplyToRef(ge.Matrix[2],ge.Matrix[4]),e.setMatrix("projectionPixel",ge.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new kA)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new qa("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{const t=this._blurPostProcessX?.inputTexture.width??this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/t,0)})),this._blurPostProcessY=new qa("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{const t=this._blurPostProcessY?.inputTexture.height??this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/t)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(s+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(s+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(s+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new qa("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(i||t){if(i&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const t=i.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[i.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(t){const i=t.getTextureIndex(TA.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this.useFresnel&&(e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("depthSampler",t.getGBuffer().textures[0]))}else if(i){const t=i.getIndex(3);if(e.setTexture("reflectivitySampler",i.getRenderTarget().textures[t]),this.useFresnel){const t=i.getIndex(5),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(ge.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",ge.Matrix[0])}}}}))}serialize(){const e=yt.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return yt.Parse((()=>new GA(e._name,t,e._ratio)),e,t,i)}}qe([st()],GA.prototype,"samples",null),qe([st()],GA.prototype,"maxDistance",void 0),qe([st()],GA.prototype,"step",void 0),qe([st()],GA.prototype,"thickness",void 0),qe([st()],GA.prototype,"strength",void 0),qe([st()],GA.prototype,"reflectionSpecularFalloffExponent",void 0),qe([st()],GA.prototype,"maxSteps",void 0),qe([st()],GA.prototype,"roughnessFactor",void 0),qe([st()],GA.prototype,"selfCollisionNumSkip",void 0),qe([st()],GA.prototype,"_reflectivityThreshold",void 0),qe([st("_ssrDownsample")],GA.prototype,"_ssrDownsample",void 0),qe([st()],GA.prototype,"ssrDownsample",null),qe([st("blurDispersionStrength")],GA.prototype,"_blurDispersionStrength",void 0),qe([st("blurDownsample")],GA.prototype,"_blurDownsample",void 0),qe([st("enableSmoothReflections")],GA.prototype,"_enableSmoothReflections",void 0),qe([st("environmentTexture")],GA.prototype,"_environmentTexture",void 0),qe([st("environmentTextureIsProbe")],GA.prototype,"_environmentTextureIsProbe",void 0),qe([st("attenuateScreenBorders")],GA.prototype,"_attenuateScreenBorders",void 0),qe([st("attenuateIntersectionDistance")],GA.prototype,"_attenuateIntersectionDistance",void 0),qe([st("attenuateIntersectionIterations")],GA.prototype,"_attenuateIntersectionIterations",void 0),qe([st("attenuateFacingCamera")],GA.prototype,"_attenuateFacingCamera",void 0),qe([st("attenuateBackfaceReflection")],GA.prototype,"_attenuateBackfaceReflection",void 0),qe([st("clipToFrustum")],GA.prototype,"_clipToFrustum",void 0),qe([st("useFresnel")],GA.prototype,"_useFresnel",void 0),qe([st("enableAutomaticThicknessComputation")],GA.prototype,"_enableAutomaticThicknessComputation",void 0),qe([st("backfaceDepthTextureDownsample")],GA.prototype,"_backfaceDepthTextureDownsample",void 0),qe([st("backfaceForceDepthWriteTransparentMeshes")],GA.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),qe([st("isEnabled")],GA.prototype,"_isEnabled",void 0),qe([st("inputTextureColorIsInGammaSpace")],GA.prototype,"_inputTextureColorIsInGammaSpace",void 0),qe([st("generateOutputInGammaSpace")],GA.prototype,"_generateOutputInGammaSpace",void 0),qe([st("debug")],GA.prototype,"_debug",void 0),ee("BABYLON.SSRRenderingPipeline",GA);bi.ShadersStore.taaPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}\n";class zA extends PA{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,s=0){const r=t.getEngine();super(r,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._hs=new jT(this.samples),this.isSupported&&(this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){const i=this._scene.getEngine();this._ping?.dispose(),this._pong?.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){this._taaPostProcess?.updateEffect([].join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new iA(e,this.TAARenderEffect,(()=>this._taaPostProcess),!0)),this._createPassPostProcess(),this.addEffect(new iA(e,this.TAAPassEffect,(()=>this._passPostProcess),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){for(let e=0;e{const e=this._scene.activeCamera;if(this._taaPostProcess?.width!==this._ping.width||this._taaPostProcess?.height!==this._ping.height){const e=this._scene.getEngine();this._createPingPongTextures(e.getRenderWidth(),e.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===Kr.PERSPECTIVE_CAMERA){const t=e.getProjectionMatrix();t.setRowFromFloats(2,this._hs.x,this._hs.y,t.m[10],t.m[11])}else{const t=e.getProjectionMatrix(!0);t.setRowFromFloats(3,this._hs.x+t.m[12],this._hs.y+t.m[13],t.m[14],t.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=1^this._pingpong,this._hs.next()})),this._taaPostProcess.onApplyObservable.add((e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t?.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1}))}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new Nh("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=yt.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return yt.Parse((()=>new zA(e._name,t,e._ratio)),e,t,i)}}qe([st("samples")],zA.prototype,"_samples",void 0),qe([st("msaaSamples")],zA.prototype,"_msaaSamples",void 0),qe([st()],zA.prototype,"factor",void 0),qe([st()],zA.prototype,"disableOnCameraMove",void 0),qe([st("isEnabled")],zA.prototype,"_isEnabled",void 0),ee("BABYLON.TAARenderingPipeline",zA);var WA;bi.ShadersStore.tonemapPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}",function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(WA||(WA={}));class HA extends qa{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,s,r=2,n,o=0,a){super(e,"tonemap",["_ExposureAdjustment"],null,1,s,r,n,a,null,o),this._operator=t,this.exposureAdjustment=i;let l="#define ";this._operator===WA.Hable?l+="HABLE_TONEMAPPING":this._operator===WA.Reinhard?l+="REINHARD_TONEMAPPING":this._operator===WA.HejiDawson?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===WA.Photographic&&(l+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(l),this.onApply=e=>{e.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}}bi.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const s=i._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(i,e,t);const r=[],n=[ys.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&r.push("#define ALPHATEST"),i.isVerticesDataPresent(ys.UVKind)&&(n.push(ys.UVKind),r.push("#define UV1")),i.isVerticesDataPresent(ys.UV2Kind)&&(n.push(ys.UV2Kind),r.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(n.push(ys.MatricesIndicesKind),n.push(ys.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),r.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),Ln(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const a=e._getDrawWrapper(void 0,!0),l=a.defines,h=r.join("\n");return l!==h&&a.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),h),a.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new pl("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Vo.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Vo.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh();if(this._meshExcluded(t))return;i._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=t.getScene(),n=r.getEngine();n.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances);if(this._isReady(e,a)){const l=i._internalAbstractMeshDataInfo._materialForRenderPass?.[n.currentRenderPassId];let h=e._getDrawWrapper();if(t!==this.mesh||h||(h=s._getDrawWrapper()),!h)return;const c=h.effect;if(n.enableEffect(h),a||t._bind(e,c,s.fillMode),t===this.mesh)s.bind(i.getWorldMatrix(),t);else if(l)l.bindForSubMesh(i.getWorldMatrix(),i,e);else{if(c.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&c.setMatrices("mBones",t.skeleton.getTransformMatrices(t))}a&&t.hasThinInstances&&c.setMatrix("world",i.getWorldMatrix()),t._processRendering(i,e,c,uo.TriangleFillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}};let n;const o=new Ee(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{n=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=n})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,s)=>{if((s||0===t)&&e.subMeshes)for(let t=0;t{const o=e.getEngine();let a;if(n.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):we.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=se.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,s){return yt.Parse((()=>new YA(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}qe([st()],YA.prototype,"ridge",void 0),qe([st()],YA.prototype,"valley",void 0),ee("BABYLON.ScreenSpaceCurvaturePostProcess",YA);bi.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n";bi.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n";bi.ShadersStore.boundingBoxRendererPixelShader="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";bi.ShadersStore.boundingBoxRendererVertexShader="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n",Object.defineProperty(dr.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),dr.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new QA(this)),this._boundingBoxRenderer},Object.defineProperty(Sn.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class QA{constructor(e){this.name=Rs.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Ce(1,1,1),this.backColor=new Ce(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new X,this.onAfterBoxRenderingObservable=new X,this.onResourcesReadyObservable=new X,this.enabled=!0,this.renderList=new ds(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new bs(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new bs(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(Rs.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Rs.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Rs.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Rs.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new Yu("colorShader",this.scene,"boundingBoxRenderer",{attributes:[ys.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new Yu("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[ys.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=bu({size:1});this._vertexBuffers[ys.PositionKind]=new ys(e,t.positions,ys.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let s=0;s{let t=e._getComponent(Rs.NAME_DEPTHRENDERER);t||(t=new jA(e),e._addComponent(t))};bi.ShadersStore.oitFinalPixelShader="precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";bi.ShadersStore.oitBackBlendPixelShader="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";class KA{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class $A{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new ds(10),this._excludedSubMeshes=new ds(10),this._excludedMeshes=[],this._colorCache=[new Ee($A._DEPTH_CLEAR_VALUE,$A._DEPTH_CLEAR_VALUE,0,0),new Ee(-$A._MIN_DEPTH,$A._MAX_DEPTH,0,0),new Ee(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.lineVertexShader="#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",Sn.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Sn.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new JA(this,e,t,!0,i),this},Object.defineProperty(Sn.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),Qu.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new eP(this,e,t),this},ju.prototype.enableEdgesRendering=function(e=.95,t=!1){return Qu.prototype.enableEdgesRendering.apply(this,arguments),this};class ZA{constructor(){this.edges=[],this.edgesConnectedCount=0}}class JA{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new Yu("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,r){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new ds(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Fi(e.getEngine())),this._prepareRessources(),s&&(r?.useAlternateEdgeFinder??1?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add((()=>{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=JA._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[ys.PositionKind];e&&e._rebuild(),e=this._buffers[ys.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[ys.PositionKind];e&&(e.dispose(),this._buffers[ys.PositionKind]=null),e=this._buffers[ys.NormalKind],e&&(e.dispose(),this._buffers[ys.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),this._drawWrapper?.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){const n=1e-10;return e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(s,n)||e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(i,n)?0:e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(r,n)||e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(s,n)?1:e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(i,n)||e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(r,n)?2:-1}_checkEdge(e,t,i,s,r){let n;n=void 0===t||de.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort(((e,t)=>e[1]t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--o)r(e[o%3],a,o!==n+2?s[i[t+(o+1)%3]]:-1);const h=a.length;i.push(s[i[t+n]],o[0],a[0]),i.push(s[i[t+(n+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,_=c?l-1:h-1,p=c?0:1;let f=l+h-2,m=0,g=0;const v=c?o:a,x=c?a:o;let b=0;for(;f-- >0;){let e;p?i.push(v[m],x[g]):i.push(x[g],v[m]),b+=u,b>=d&&m<_?(e=v[++m],b-=d):e=x[++g],i.push(e)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){const e=this._source.getVerticesData(ys.PositionKind);let t=this._source.getIndices();if(!t||!e)return;Array.isArray(t)||(t=Array.from(t));const i=this._options?.useFastVertexMerger??!0,s=i?Math.round(-Math.log(this._options?.epsilonVertexMerge??1e-6)/Math.log(10)):this._options?.epsilonVertexMerge??1e-6,r=[],n=[];if(i){const t={};for(let i=0;il){const e=a;a=l,l=e}const c=a+"_"+l,u=o[c];u?u.done||(de.Dot(s,u.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let r=0;if(s)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(r=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[r]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(s)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw vt("PrePassRendererSceneComponent")},iP.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(dr.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),dr.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new iP(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,we.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},dr.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class sP{constructor(e){this.name=Rs.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(Rs.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Rs.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Rs.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Rs.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Rs.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Rs.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Rs.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Rs.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}iP._SceneComponentInitialization=e=>{let t=e._getComponent(Rs.NAME_PREPASSRENDERER);t||(t=new sP(e),e._addComponent(t))};bi.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}";bi.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";bi.ShadersStore.subSurfaceScatteringPixelShader="#include\n#include\n#include\n#include\nvarying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void we.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class nP{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=Rs.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Ce(1,1,1)),this._scene=e,nP._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return we.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw vt("SubSurfaceSceneComponent")},G.AddParser(Rs.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,s=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(Rs.NAME_SUBSURFACE);t||(t=new oP(e),e._addComponent(t))};bi.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n",dr.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new aP(this)),this._outlineRenderer},Object.defineProperty(bo.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(bo.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class aP{constructor(e){this.name=Rs.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(Rs.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Rs.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{_.setMatrix("world",t)})),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[ys.PositionKind,ys.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(ys.UVKind)&&(r.push(ys.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(ys.UV2Kind)&&(r.push(ys.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),Pn(o,a,s),n.useBones&&n.computeBonesUsingShaders?(r.push(ys.MatricesIndicesKind),r.push(ys.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(ys.MatricesIndicesExtraKind),r.push(ys.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const l=n.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Fn(r,n,h))),t&&(s.push("#define INSTANCES"),Ln(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),u=c.defines,d=s.join("\n");if(u!==d){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];An(e),c.setEffect(this.scene.getEngine().createEffect("outline",r,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(aP._StencilReference),this._engine.setStencilFunctionReference(aP._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),s=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=s}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}aP._StencilReference=4;class lP{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){return!!this.vertexBuffers?.velocity}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new X,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new ll({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new ll({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){this._depthEffectWrapper?.dispose(),this._thicknessEffectWrapper?.dispose()}}class hP extends lP{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((()=>{this._engine.setAlphaMode(2)}))))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class cP{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,s,r,n,o=1,a=6,l=1,h=6,c=!1,u=null,d=!0,_=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new X,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=s,this._blurTextureSizeX=r,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=a,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=_,this._postProcessRunningIndex=0,this.enableBlur=0!==r&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Vo(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Vo.CLAMP_ADDRESSMODE,this._texture.wrapV=Vo.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,s,r,n=!1){const o=this._scene.getEngine(),a=new ue(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),l=1===t&&o.getCaps().textureFloatLinearFiltering||2===t&&o.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:a.x,height:a.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${r}`}),c=h.texture;c.incrementReferences();const u=new Vo(null,this._scene);if(u.name="rttBlurred"+r,u._texture=c,u.wrapU=Vo.CLAMP_ADDRESSMODE,u.wrapV=Vo.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,n){const s=new qa("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Vo.CLAMP_ADDRESSMODE,e.texture.wrapV=Vo.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new qa("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Vo.CLAMP_ADDRESSMODE,e.texture.wrapV=Vo.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?r:s;return[h,u,n]}{const s=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],r=new qa("BilateralBlurX","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Vo.CLAMP_ADDRESSMODE,e.texture.wrapV=Vo.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r);const n=new qa("BilateralBlurY","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Vo.CLAMP_ADDRESSMODE,e.texture.wrapV=Vo.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n),r.autoClear=!1,n.autoClear=!1;const a=[];for(let e=0;e<2*this._blurNumIterations;++e)a[e]=1&e?n:r;return[h,u,a]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((this._camera?.fov??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),this._rt?.dispose(),this._rt=null,this._texture?.dispose(),this._texture=null,this._rtBlur?.dispose(),this._rtBlur=null,this._textureBlurred?.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var uP;!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(uP||(uP={}));class dP{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Ce(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new de(-2,-1,1).normalize(),this._debugFeature=uP.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new X,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new fe,this._depthClearColor=new Ee(1e6,1e6,1e6,1),this._thicknessClearColor=new Ee(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new cP("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=this._diffuseMapSize??this._engine.getRenderWidth(),t=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new cP("Diffuse",this._scene,e,t,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),s=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new cP("Thickness",this._scene,i,s,i,s,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new ue(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===uP.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===uP.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),this._debugFeature!==uP.DepthTexture&&this._debugFeature!==uP.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new qa("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add((t=>{if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),e.isWebGPU&&t.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(t.setTexture("depthSampler",this._depthRenderTarget.textureBlur),e.isWebGPU&&t.setTextureSampler("depthSamplerSampler",this._depthRenderTarget.textureBlur?.getInternalTexture()??null)):(t.setTexture("depthSampler",this._depthRenderTarget.texture),e.isWebGPU&&t.setTextureSampler("depthSamplerSampler",this._depthRenderTarget.texture?.getInternalTexture()??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(t.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),e.isWebGPU&&t.setTextureSampler("diffuseSamplerSampler",this._diffuseRenderTarget.textureBlur?.getInternalTexture()??null)):(t.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),e.isWebGPU&&t.setTextureSampler("diffuseSamplerSampler",this._diffuseRenderTarget.texture?.getInternalTexture()??null)):t.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(t.setFloat("thickness",this.minimumThickness),t._bindTexture("bgDepthSampler",this._bgDepthTexture),e.isWebGPU&&t.setTextureSampler("bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(t.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),e.isWebGPU&&t.setTextureSampler("thicknessSamplerSampler",this._thicknessRenderTarget.textureBlur?.getInternalTexture()??null)):(t.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),e.isWebGPU&&t.setTextureSampler("thicknessSamplerSampler",this._thicknessRenderTarget.texture?.getInternalTexture()??null)),t.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const i=this._environmentMap??this._scene.environmentTexture;i&&(t.setTexture("reflectionSampler",i),e.isWebGPU&&t.setTextureSampler("reflectionSamplerSampler",i?.getInternalTexture()??null))}if(t.setMatrix("viewMatrix",this._scene.getViewMatrix()),t.setMatrix("invProjectionMatrix",this._invProjectionMatrix),t.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),t.setVector2("texelSize",n),t.setFloat("density",this.density),t.setFloat("refractionStrength",this.refractionStrength),t.setFloat("fresnelClamp",this.fresnelClamp),t.setFloat("specularPower",this.specularPower),t.setVector3("dirLight",this.dirLight),t.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case uP.DepthTexture:i=this._depthRenderTarget.texture;break;case uP.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case uP.ThicknessTexture:i=this._thicknessRenderTarget?.texture??null;break;case uP.ThicknessBlurredTexture:i=this._thicknessRenderTarget?.enableBlur?this._thicknessRenderTarget?.textureBlur??null:this._thicknessRenderTarget?.texture??null;break;case uP.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==uP.Normals&&(t.setTexture("debugSampler",i),e.isWebGPU&&t.setTextureSampler("debugSamplerSampler",i?.getInternalTexture()??null))}}))}_clearTargets(){this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),this._depthRenderTarget?.applyBlurPostProcesses(),this._diffuseRenderTarget?.applyBlurPostProcesses(),this._thicknessRenderTarget?.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){e||(this._depthRenderTarget?.dispose(),this._depthRenderTarget=null,this._diffuseRenderTarget?.dispose(),this._diffuseRenderTarget=null,this._thicknessRenderTarget?.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),this._renderPostProcess?.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class _P extends lP{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1}this._vertexBuffers[t]=new ys(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new ll({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){return this._vertexBuffers.offset||(this._vertexBuffers.offset=new ys(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(this._diffuseEffectWrapper?.effect.isReady()??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){super.dispose(),this._diffuseEffectWrapper?.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}var pP;bi.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(pP||(pP={}));class fP{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new al(e),this._effectWrapper=new ll({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=pP.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class mP{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new fP(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${s}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}bi.ShadersStore.fluidRenderingParticleDepthVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";bi.ShadersStore.fluidRenderingParticleDepthPixelShader="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";bi.ShadersStore.fluidRenderingParticleThicknessVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}\n";bi.ShadersStore.fluidRenderingParticleThicknessPixelShader="uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}\n";bi.ShadersStore.fluidRenderingParticleDiffuseVertexShader="attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}\n";bi.ShadersStore.fluidRenderingParticleDiffusePixelShader="uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}\n";bi.ShadersStore.fluidRenderingBilateralBlurPixelShader="uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";bi.ShadersStore.fluidRenderingStandardBlurPixelShader="uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}\nfloat sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";function gP(e){return!!e.particleSystem}function vP(e){return!!e.addBuffers}bi.ShadersStore.fluidRenderingRenderPixelShader="/* disable_uniformity_analysis */\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\nglFragColor=backColor;return;}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n",Object.defineProperty(dr.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),dr.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new bP(this)),this._fluidRenderer},dr.prototype.disableFluidRenderer=function(){this._fluidRenderer?.dispose(),this._fluidRenderer=null};class xP{constructor(e){this.name=Rs.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Rs.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(Rs.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){this.scene.fluidRenderer?._prepareRendering()}_afterCameraDraw(e){this.scene.fluidRenderer?._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{e._rebuild()}))}dispose(){this.scene.disableFluidRenderer()}}class bP{static _SceneComponentInitialization(e){let t=e._getComponent(Rs.NAME_FLUIDRENDERER);t||(t=new xP(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,bP._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,s){const r=new hP(this._scene,e);r.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),i||(i=new dP(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==t&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new _P(this._scene,e,t);n.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),s||(s=new dP(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==i&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priorityt.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let t=0;t{r.inputTexture.depthStencilTexture||r.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${r.name}`);for(const e of n){const t=e._thicknessRenderTarget?.renderTarget,i=t?.texture;if(t&&i){const e=i.width+"_"+i.height;let s=o[e];s||(s=o[e]=new mP(this._engine,i.width,i.height)),s.depthRTWrapper.shareDepth(t)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,s=this._cameras.get(t)[1],r=e.get(t);if(r)for(const e in s)r[1][e]||s[e].dispose();else for(const e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){for(let t=0;t{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class TP{get enable(){return this._enable}set enable(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))}get positionWorldTexture(){return this._mrt.textures[0]}get normalWorldTexture(){return this._mrt.textures[1]}get fluxTexture(){return this._mrt.textures[2]}get renderList(){return this._mrt.renderList}get light(){return this._light}constructor(e,t,i={width:512,height:512}){this._lightTransformMatrix=fe.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}setTextureDimensions(e){const t=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),t?.forEach((e=>{this._addMeshToMRT(e)}))}addMesh(e){e?this._addMeshToMRT(e):this._scene.meshes.forEach((e=>{this._addMeshToMRT(e)})),this._recomputeLightTransformationMatrix()}updateLightParameters(){this._recomputeLightTransformationMatrix()}get lightTransformationMatrix(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix}get countersGPU(){return this._counters}dispose(){this._disposeMultiRenderTarget()}_createMultiRenderTarget(){const e=this._light.name,t=this._scene.getEngine().getCaps(),i=t.rg11b10ufColorRenderable?13:2,s=t.rg11b10ufColorRenderable?4:5;let r,n;this._mrt=new Ex("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,s]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new Ee(0,0,0,1),this._mrt.noPrePassRenderer=!0;const o=this._scene.getEngine().supportsUniformBuffers;let a;o&&(r=this._scene.createSceneUniformBuffer(`Scene for RSM (light "${e}")`)),this._mrt.onBeforeBindObservable.add((()=>{n=this._scene.getSceneUniformBuffer(),a=this._light.shadowEnabled,this._light.shadowEnabled=!1})),this._mrt.onBeforeRenderObservable.add((e=>{r&&this._scene.setSceneUniformBuffer(r);const t=this._light.getViewMatrix(e),i=this._light.getProjectionMatrix(t||void 0,this._mrt.renderList||void 0);t&&i&&this._scene.setTransformMatrix(t,i),o&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._mrt.onAfterUnbindObservable.add((()=>{r&&this._scene.setSceneUniformBuffer(n),this._scene.updateTransformMatrix(),this._light.shadowEnabled=a,this._counters[0].value=this._mrt.renderTarget.gpuTimeInFrame?.counter.lastSecAverage??0})),this._customRenderTarget(!0)}_customRenderTarget(e){const t=this._scene.customRenderTargets.indexOf(this._mrt);e?-1===t&&this._scene.customRenderTargets.push(this._mrt):-1!==t&&this._scene.customRenderTargets.splice(t,1)}_recomputeLightTransformationMatrix(){const e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)}_addMeshToMRT(e){this._mrt.renderList?.push(e);const t=e.material;if(0===e.getTotalVertices()||!t)return;let i=this._regularMatToMatWithPlugin.get(t);if(!i&&(i=t.clone("RSMCreate_"+t.name)||void 0,i)){Object.defineProperty(i,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),i.disableLighting=!0;const e=new SP(i);e.isEnabled=!0,e.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class yP extends Oa{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class SP extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,SP.Name,300,new yP),this._lightColor=new Ce,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Vm?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===yo.LIGHTTYPEID_SPOTLIGHT;if(t){const e=this.light;this._hasProjectionTexture=!!e.projectionTexture&&e.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #endif"}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===yo.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=ge.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(.5*t.angle))}}getCustomCode(e){return"vertex"===e?null:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n `}}}SP.Name="RSMCreate",qe([st()],SP.prototype,"light",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],SP.prototype,"isEnabled",void 0),ee("BABYLON.RSMCreatePluginMaterial",SP);class CP{constructor(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}dispose(){this.rsm.dispose()}}bi.ShadersStore.bilateralBlurPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nglFragColor=vec4(sum/wsum,1.);}\n";bi.ShadersStore.bilateralBlurQualityPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nglFragColor=vec4(sum/wsum,1.);}\n";bi.ShadersStore.rsmGlobalIlluminationPixelShader="/**\n* The implementation is an application of the formula found in http:\n* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";bi.ShadersStore.rsmFullGlobalIlluminationPixelShader="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{t.pluginManager&&(t.pluginManager.getPlugin(PP.Name).isEnabled=e)})),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{e.getTotalVertices()>0&&e.isEnabled()&&e.material&&this._addGISupportToMaterial(e.material)}))}get countersGPU(){return this._counters}recreateResources(e=!1){this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()}generateSampleTexture(e){this._sampleTexture?.dispose(),this._maxSamples=e;const t=new Float32Array(4*this._maxSamples);for(let e=0;e{const e=this._engine._currentRenderTarget;let t=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),t=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let e=0;e{if(e.pluginManager){const t=e.pluginManager.getPlugin(PP.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}}))}_createPostProcesses(){if(!this._enable)return;const e=13===this._giTextureType?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=this._scene.geometryBufferRenderer?.enablePosition??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,15,EP.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,s=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let r="";i&&(r+="#define DECODE_NORMAL\n"),s||(r+="#define TRANSFORM_NORMAL\n");for(let i=0;i{e.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(TA.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",o.positionWorldTexture),e.setTexture("rsmNormalW",o.normalWorldTexture),e.setTexture("rsmFlux",o.fluxTexture),e.setMatrix("rsmLightMatrix",o.lightTransformationMatrix),n.useFullTexture?e.setFloat4("rsmInfo",o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height,n.intensity,n.edgeArtifactCorrection):(e.setTexture("rsmSamples",this._sampleTexture),e.setFloat4("rsmInfo",n.numSamples,n.radius,n.intensity,n.edgeArtifactCorrection),e.setFloat4("rsmInfo2",n.noiseFactor,n.rotateSample?1:0,o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height)),s||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),e.setMatrix("invView",this._tempMatrix))}))}for(const e of this._ppGlobalIllumination)e.inputTexture||e.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const s=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new pl("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const r=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(r),this._blurXPostprocess=new qa(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurXPostprocess.onApplyObservable.add((e=>{e._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(TA.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new qa("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(TA.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",0,1/this._giTextureDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurYPostprocess.resize(s.width,s.height),r.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)r.push(this._blurRTT.renderTarget);else{const n=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(n),this._upsamplingXPostprocess=new qa(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(TA.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(s.width,s.height),r.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new qa("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(TA.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",0,1/this._outputDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),n.push(this._upsamplingYPostprocess.inputTexture)),n.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}this._debugLayer.texture?.dispose(),this._debugLayer.texture=new No(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){if(e.pluginManager?.getPlugin(PP.Name))return;const t=new PP(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}EP.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class AP extends Oa{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class PP extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,PP.Name,310,new AP),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Vm}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e){const t={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n "),"vertex"===e?null:t}}PP.Name="GIRSMRender",qe([st()],PP.prototype,"textureGIContrib",void 0),qe([st()],PP.prototype,"outputTextureWidth",void 0),qe([st()],PP.prototype,"outputTextureHeight",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],PP.prototype,"isEnabled",void 0),ee("BABYLON.GIRSMRenderPluginMaterial",PP);bi.ShadersStore.spriteMapPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);}\nvoid main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}}\nmat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}\ncolor.xyz*=colorMul;gl_FragColor=color;}";bi.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \ngl_Position=worldViewProjection*p;}";class RP{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}constructor(e,t,i,s,r){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=s,s.stageSize=s.stageSize||new ue(1,1),s.outputSize=s.outputSize||s.stageSize,s.outputPosition=s.outputPosition||de.Zero(),s.outputRotation=s.outputRotation||de.Zero(),s.layerCount=s.layerCount||1,s.maxAnimationFrames=s.maxAnimationFrames||0,s.baseTile=s.baseTile||0,s.flipU=s.flipU||!1,s.colorMultiply=s.colorMultiply||new de(1,1,1),this._scene=r,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let e=0;e{this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture?this._material.setVector2("spriteMapSize",new ue(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1)):l<100&&setTimeout((()=>{l++,h()}),100)};h(),this._material.setVector3("colorMul",s.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=ta(e+":output",{size:1,updatable:!0},r),this._output.scaling.x=s.outputSize.x,this._output.scaling.y=s.outputSize.y,this.position=s.outputPosition,this.rotation=s.outputRotation,this._scene.onBeforeRenderObservable.add((()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)})),this._output.material=this._material}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||ue.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,(t=>t===e));if(!t||!t.hit||!t.getTextureCoordinates)return new ue(-1,-1);return t.getTextureCoordinates()||new ue(-1,-1)}_createFrameBuffer(){const e=[];for(let t=0;t0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const e=t.response.split("\n\r");for(let t=0;t{e.dispose()})),this._frameMap.dispose()}}class IP extends Av{constructor(e,t,i,s,r=null,n=.01,o=Vo.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,s,n,o,!0,r),this.name=e}}var MP;!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(MP||(MP={}));class OP{constructor(e){this.name=e,this._isCompleted=!1,this._taskState=MP.INIT}get isCompleted(){return this._isCompleted}get taskState(){return this._taskState}get errorObject(){return this._errorObject}_setErrorObject(e,t){this._errorObject||(this._errorObject={message:e,exception:t})}run(e,t,i){this._taskState=MP.RUNNING,this.runTask(e,(()=>{this._onDoneCallback(t,i)}),((e,t)=>{this._onErrorCallback(i,e,t)}))}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=MP.INIT}_onErrorCallback(e,t,i){this._taskState=MP.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=MP.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}}}class DP{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class wP extends OP{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){Pa.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(e=>{this.loadedContainer=e,this.loadedMeshes=e.meshes,this.loadedTransformNodes=e.transformNodes,this.loadedParticleSystems=e.particleSystems,this.loadedSkeletons=e.skeletons,this.loadedAnimationGroups=e.animationGroups,t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class NP extends OP{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){Pa.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,((e,i,s,r,n)=>{this.loadedMeshes=e,this.loadedTransformNodes=n,this.loadedParticleSystems=i,this.loadedSkeletons=s,this.loadedAnimationGroups=r,t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class FP extends OP{constructor(e,t,i,s,r){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=s,this.extension=r}runTask(e,t,i){const s=e.animatables.length,r=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],Pa.ImportAnimations(this.rootUrl,this.filename,e,!1,va.NoSync,this.targetConverter,(()=>{this.loadedAnimatables=e.animatables.slice(s),this.loadedAnimationGroups=e.animationGroups.slice(r),t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class BP extends OP{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.text=e,t()}),void 0,!1,!1,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class LP extends OP{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.data=e,t()}),void 0,!0,!0,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class kP extends OP{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const s=new Image;hs.SetCorsBehavior(this.url,s),s.onload=()=>{this.image=s,t()},s.onerror=e=>{i("Error loading image",e)},s.src=this.url}}class VP extends OP{constructor(e,t,i,s=!0,r=Vo.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=s,this.samplingMode=r}runTask(e,t,i){this.texture=new Vo(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(()=>{t()}),((e,t)=>{i(e,t)}))}}class UP extends OP{constructor(e,t,i,s,r,n){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=s,this.files=r,this.prefiltered=n}runTask(e,t,i){this.texture=new mm(this.url,e,this.extensions,this.noMipmap,this.files,(()=>{t()}),((e,t)=>{i(e,t)}),void 0,this.prefiltered)}}class GP extends OP{constructor(e,t,i,s=!1,r=!0,n=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.generateHarmonics=r,this.gammaSpace=n,this.reserved=o}runTask(e,t,i){this.texture=new uv(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(()=>{t()}),((e,t)=>{i(e,t)}))}}class zP extends OP{constructor(e,t,i,s=!1,r=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.gammaSpace=r}runTask(e,t,i){this.texture=new Xv(this.url,e,this.size,this.noMipmap,this.gammaSpace,(()=>{t()}),((e,t)=>{i(e,t)}))}}class WP{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new X,this.onTaskErrorObservable=new X,this.onTasksDoneObservable=new X,this.onProgressObservable=new X,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||se.LastCreatedScene}addContainerTask(e,t,i,s,r){const n=new wP(e,t,i,s,r);return this._tasks.push(n),n}addMeshTask(e,t,i,s,r){const n=new NP(e,t,i,s,r);return this._tasks.push(n),n}addTextFileTask(e,t){const i=new BP(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new LP(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new kP(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,s,r=Vo.TRILINEAR_SAMPLINGMODE){const n=new VP(e,t,i,s,r);return this._tasks.push(n),n}addCubeTextureTask(e,t,i,s,r,n){const o=new UP(e,t,i,s,r,n);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,s=!1,r=!0,n=!1,o=!1){const a=new GP(e,t,i,s,r,n,o);return this._tasks.push(a),a}addEquiRectangularCubeTextureAssetTask(e,t,i,s=!1,r=!0){const n=new zP(e,t,i,s,r);return this._tasks.push(n),n}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new DP(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){we.Error("Error running progress callbacks."),we.Log(e)}if(0===this._waitingTasksCount){try{const e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(const t of e)if(t.taskState===MP.DONE){const e=this._tasks.indexOf(t);e>-1&&this._tasks.splice(e,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){we.Error("Error running tasks-done callbacks."),we.Log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=(t,i)=>{e._setErrorObject(t,i),this.onTaskError?this.onTaskError(e):e.onError||we.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,(()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(e){t("Error executing task success callbacks",e)}}),t)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{this._isLoading?e():(this.onTasksDoneObservable.addOnce((i=>{i&&i.length?t(i):e()})),this.load())}))}}class HP{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class XP{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new de(1,1,1),this._newPosition=de.Zero(),this._centerPosition=de.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let e=0;e!0,this.displayLoadingUI=!0,this.loadAsync=(e,t)=>this.useAppend?Pa.AppendAsync("file:",e,this._currentScene,t):Pa.LoadAsync("file:",e,this._engine,t),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=s,this._additionalRenderLoopLogicCallback=r,this._textureLoadingCallback=n,this._startingProcessingFilesCallback=o,this._onReloadCallback=a,this._errorCallback=l}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=e=>{this._drag(e)},this._dragOverHandler=e=>{this._drag(e)},this._dropHandler=e=>{this._drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,s){const r=e.createReader(),n=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");r.readEntries((e=>{i.count+=e.length;for(const r of e)r.isFile?r.file((e=>{e.correctName=n+e.name,t.push(e),0==--i.count&&s()})):r.isDirectory&&this._traverseFolder(r,t,i,s);0==--i.count&&s()}))}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=e))&&(Pa.IsPluginForExtensionAvailable("."+s)&&(this._sceneFileToLoad=e[t]),YP.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=[],i=[],s=e.dataTransfer?e.dataTransfer.items:null;for(let e=0;e{this._processFiles(t),0===e.count&&this._processReload()}))}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){this._sceneFileToLoad?(this.useAppend||this._currentScene&&(we.errorsCount>0&&we.ClearLogCache(),this._engine.stopRenderLoop()),Pa.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then((e=>{this.useAppend?this.displayLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady((()=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop((()=>{this._renderFunction()}))}))),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)})).catch((e=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)}))):we.Error("Please provide a valid .babylon file.")}}class QP{dispose(){if(this._observers&&this._observables)for(let e=0;e{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(n=i.scope?n.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):n.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await n,e};class jP{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class KP extends jP{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let t=0;tthis.maximumSize&&(s.scale(this.step),i=!1)}return i}}class $P extends jP{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class qP extends jP{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class ZP extends jP{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class JP extends jP{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class eR extends jP{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return!this.onApply||this.onApply(e,t)}}class tR extends jP{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class iR extends jP{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class sR extends jP{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof bo))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return sR._UpdateSelectionTree}static set UpdateSelectionTree(e){sR._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const s=e.meshes.slice(0);let r=s.length;for(let e=0;e{this._sceneDisposeObserver=null,this.dispose()}))}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady((()=>{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)})))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);let i=!0,s=!0;for(let r=0;r{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)}))}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,s){const r=new nR(e,t||rR.ModerateDegradationAllowed(),!1);return i&&r.onSuccessObservable.add((()=>{i()})),s&&r.onFailureObservable.add((()=>{s()})),r.start(),r}}let oR=[];const aR=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),oR[e.id]=!0)},lR=(e,t)=>{const i={},s=e._geometry;return s&&(e.getScene().getGeometryById(s.id)||aR(s,t.geometries)),e.serialize&&e.serialize(i),i};class hR{static ClearCache(){oR=[]}static Serialize(e){return hR._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Vo.ForceSerializeBuffers&&we.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),hR.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(i.fogMode=e.fogMode,i.fogColor=e.fogColor.asArray(),i.fogStart=e.fogStart,i.fogEnd=e.fogEnd,i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let s,r,n;for(i.lights=[],s=0;s0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],s=0;st))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const s=e[i];s instanceof Promise?t.push(s.then((t=>e[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}}static SerializeMesh(e,t=!1,i=!1){const s={meshes:[],transformNodes:[],cameras:[],lights:[]};if(hR.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach((e=>{((e,t)=>{if(e._isMesh){const i=e;if(1===i.delayLoadState||0===i.delayLoadState){const e=e=>{t.materials=t.materials||[],i.material&&!t.materials.some((e=>e.id===i.material.id))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof _o){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((e=>e.id===i.material.id))){t.multiMaterials.push(i.material.serialize());for(const t of i.material.subMaterials)t&&e(t)}}else e(i.material);else i.material||e(i.getScene().defaultMaterial);const s=i._geometry;s&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),aR(s,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(lR(i,t))}}else if("TransformNode"===e.getClassName()){const i=e;t.transformNodes.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){const i=e;t.cameras.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Light")){const i=e;t.lights.push(i.serialize())}})(e,s)})),s}}class cR{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!cR.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...cR._DefaultOptions,...t};const s=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)s.addTrack(e);this._mediaRecorder=new MediaRecorder(s,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&hs.Download(e,this._fileName)}}cR._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let uR=null;function dR(e,t,i,s,r="image/png",n=!1,o){const{height:a,width:l}=gR(e,t,i);if(!a||!l)return void we.Error("Invalid 'size' parameter !");uR||(uR=document.createElement("canvas")),uR.width=l,uR.height=a;const h=uR.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const _=Math.max(0,l-u)/2,p=Math.max(0,a-d)/2;t.getScene().activeCamera!==t?fR(e,t,i,(e=>{if(n){const t=new Blob([e]);hs.DownloadBlob(t),s&&s("")}else s&&s(e)}),r,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,_,p,u,d),uR&&(n?(hs.EncodeScreenshotCanvasData(uR,void 0,r,void 0,o),s&&s("")):hs.EncodeScreenshotCanvasData(uR,s,r,void 0,o))}))}function _R(e,t,i,s="image/png",r){return new Promise(((n,o)=>{dR(e,t,i,(e=>{void 0!==e?n(e):o(new Error("Data is undefined"))}),s,void 0,r)}))}function pR(e,t,i,s,r="image/png",n){return new Promise((o=>{dR(e,t,{width:i,height:s},(()=>{o()}),r,!0,n)}))}function fR(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u,d){const{height:_,width:p,finalWidth:f,finalHeight:m}=gR(e,t,i),g={width:p,height:_};if(!_||!p)return void we.Error("Invalid 'size' parameter !");const v={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(p,_);const x=t.getScene(),b=new pl("screenShot",g,x,!1,!1,0,!1,Vo.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);b.renderList=x.meshes.slice(),b.samples=n,b.renderSprites=l,b.activeCamera=t,b.forceLayerMaskCheck=c,d?.(b);const T=()=>{b.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((()=>{f===p&&m===_?b.readPixels(void 0,void 0,void 0,!1).then((e=>{_l.DumpData(p,_,e,s,r,a,!0,void 0,u),b.dispose()})):c_("pass",b.getInternalTexture(),x,void 0,void 0,void 0,f,m).then((t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then((e=>{_l.DumpData(f,m,e,s,r,a,!0,void 0,u),t.dispose()}))}))})),b.render(!0),x.incrementRenderId(),x.resetCachedMaterial(),e.setSize(v.width,v.height),t.getProjectionMatrix(!0),x.render()):setTimeout(T,16)},y=()=>{x.incrementRenderId(),x.resetCachedMaterial(),T()};if(o){const e=new mA("antialiasing",1,x.activeCamera);b.addPostProcess(e),e.getEffect().isReady()?y():e.getEffect().onCompiled=()=>{y()}}else y()}function mR(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){return new Promise(((u,d)=>{fR(e,t,i,(e=>{void 0!==e?u(e):d(new Error("Data is undefined"))}),s,r,n,o,a,l,h,c)}))}function gR(e,t,i){let s=0,r=0,n=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(s=i.height*a,r=i.width*a):i.width&&!i.height?(r=i.width*a,s=Math.round(r/e.getAspectRatio(t))):i.height&&!i.width?(s=i.height*a,r=Math.round(s*e.getAspectRatio(t))):(r=Math.round(e.getRenderWidth()*a),s=Math.round(r/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?(n=i.finalWidth,o=Math.round(n/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,n=Math.round(o*e.getAspectRatio(t))):(n=r,o=s)}else isNaN(i)||(s=i,r=i,n=i,o=i);return r&&(r=Math.floor(r)),s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),o&&(o=Math.floor(o)),{height:0|s,width:0|r,finalWidth:0|n,finalHeight:0|o}}const vR={CreateScreenshot:dR,CreateScreenshotAsync:_R,CreateScreenshotWithResizeAsync:pR,CreateScreenshotUsingRenderTarget:fR,CreateScreenshotUsingRenderTargetAsync:mR};var xR,bR;hs.CreateScreenshot=dR,hs.CreateScreenshotAsync=_R,hs.CreateScreenshotUsingRenderTarget=fR,hs.CreateScreenshotUsingRenderTargetAsync=mR,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(xR||(xR={}));class TR{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return $t(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class yR{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}yR._Storage=yR._GetStorage();class SR{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,yt.AllowLoadingUniqueId=!0,this._savedJSON=hR.Serialize(e),yt.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=Vo.ForceSerializeBuffers;Vo.ForceSerializeBuffers=!1,yt.AllowLoadingUniqueId=!0;const t=hR.Serialize(this._trackedScene);yt.AllowLoadingUniqueId=!1;const i={};for(const e in t)this._compareCollections(e,this._savedJSON[e],t[e],i);return Vo.ForceSerializeBuffers=e,i}_compareArray(e,t,i,s){if(0===t.length&&0===i.length)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(0===t.length)return!0;for(let r=0;re.uniqueId===a));if(l.length){const t=l[0],i={};this._compareObjects(o,t,i)||(s[e]||(s[e]=[]),i.__state={id:t.id||t.name},s[e].push(i))}else{const t={__state:{deleteId:o.id||o.name}};s[e]||(s[e]=[]),s[e].push(t)}}for(let t=0;te.getShadowGenerators()));for(const e of i)if(e){const i=e.values();for(let e=i.next();!0!==e.done;e=i.next()){const i=e.value;if(i&&i.id===t)return i}}return null}static ApplyDelta(e,t){"string"==typeof e&&(e=JSON.parse(e));const i=t;for(const s in e){const r=e[s],n=i[s];if(Array.isArray(n)||"shadowGenerators"===s)switch(s){case"cameras":this._ApplyDeltaForEntity(r,t,t.getCameraById.bind(t),(e=>Kr.Parse(e,t)));break;case"lights":this._ApplyDeltaForEntity(r,t,t.getLightById.bind(t),(e=>yo.Parse(e,t)));break;case"shadowGenerators":this._ApplyDeltaForEntity(r,t,(e=>this.GetShadowGeneratorById(t,e)),(e=>Kg.Parse(e,t)));break;case"meshes":this._ApplyDeltaForEntity(r,t,t.getMeshById.bind(t),(e=>bo.Parse(e,t,"")));break;case"skeletons":this._ApplyDeltaForEntity(r,t,t.getSkeletonById.bind(t),(e=>Ho.Parse(e,t)));break;case"materials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),(e=>uo.Parse(e,t,"")));break;case"multiMaterials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),(e=>_o.Parse(e,t,"")));break;case"transformNodes":this._ApplyDeltaForEntity(r,t,t.getTransformNodeById.bind(t),(e=>xn.Parse(e,t,"")));break;case"particleSystems":this._ApplyDeltaForEntity(r,t,t.getParticleSystemById.bind(t),(e=>HC.Parse(e,t,"")));break;case"morphTargetManagers":this._ApplyDeltaForEntity(r,t,t.getMorphTargetById.bind(t),(e=>pv.Parse(e,t)));break;case"postProcesses":this._ApplyDeltaForEntity(r,t,t.getPostProcessByName.bind(t),(e=>qa.Parse(e,t,"")))}else isNaN(n)?n.fromArray&&n.fromArray(r):i[s]=r}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const s=e[i],r=t[i];void 0!==r&&(!isNaN(r)||Array.isArray(r)?t[i]=s:r.fromArray?r.fromArray(s):"object"==typeof r&&null!==r&&this._ApplyPropertiesToEntity(s,r))}}static _ApplyDeltaForEntity(e,t,i,s){for(const r of e)if(r.__state&&void 0!==r.__state.id){const e=i(r.__state.id);e&&(this._ApplyPropertiesToEntity(r,e),yt.ParseProperties(r,e,t,null))}else if(r.__state&&void 0!==r.__state.deleteId){const e=i(r.__state.deleteId);e?.dispose()}else s(r)}}!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),s=new t(i.characters);return s._insertionCosts=i.insertionCosts,s._deletionCosts=i.deletionCosts,s._substitutionCosts=i.substitutionCosts,s}constructor(e,t=null,i=null,s=null){let r;t=t??(()=>1),i=i??(()=>1),s=s??((e,t)=>e===t?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const s=e._alphabet;if(s!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const r=e._characters,n=t._characters,o=r.length,a=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(bR||(bR={}));class CR{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new CR(t._segmentLength);return i._points=t._points.map((e=>new de(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/de.Distance(this._points[t-1],e);for(let s=i();s<=1;s=i()){const i=this._points[t-1].scale(1-s);e.scaleAndAddToRef(s,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new CR(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new de;for(let s=2;s.98||(de.CrossToRef(CR._ForwardDir,CR._InverseFromVec,CR._UpDir),CR._UpDir.normalize(),fe.LookAtLHToRef(e,t,CR._UpDir,CR._LookMatrix),i.subtractToRef(t,CR._FromToVec),CR._FromToVec.normalize(),de.TransformNormalToRef(CR._FromToVec,CR._LookMatrix,s),0))}static _TokenizeSegment(e,t){CR._BestMatch=0,CR._Score=de.Dot(e,t[0]),CR._BestScore=CR._Score;for(let i=1;iCR._BestScore&&(CR._BestMatch=i,CR._BestScore=CR._Score);return CR._BestMatch}}CR._ForwardDir=new de,CR._InverseFromVec=new de,CR._UpDir=new de,CR._FromToVec=new de,CR._LookMatrix=new fe;class ER{static Generate(e=64,t=256,i=.1,s=.001,r=[]){const n=new ER(e);for(let t=0;t{n.chars[e].subtractToRef(t,h),a=h.lengthSquared(),a>1e-6&&h.scaleAndAddToRef(1/(h.lengthSquared()*a),l)})),l.scaleInPlace(o),n.chars[e].addInPlace(l),n.chars[e].normalize()}var c;return n}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new ER(t.length);for(let e=0;ee.serialize())))}static Deserialize(e,t){const i=new AR;return i._sequences=JSON.parse(e).map((e=>bR.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return AR.CreateFromTokenizationPyramid(AR._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new AR;return i._sequences=e.map((e=>new bR.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=AR._FINEST_DESCRIPTOR_RESOLUTION){const s=[];for(let r=i;r>4;r=Math.floor(r/2))s.push(e.resampleAtTargetResolution(r).tokenize(t.chars));return s}distance(e){let t,i=0;for(let s=0;se.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),s=new PR;return s._descriptors=i.descriptors.map((e=>AR.Deserialize(e,t))),s._centroidIdx=i.centroidIdx,s._averageDistance=i.averageDistance,s}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,PR._MIN_AVERAGE_DISTANCE))}}PR._MIN_AVERAGE_DISTANCE=1;class RR{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach(((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())})),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new RR;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=ER.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=bR.Alphabet.Deserialize(t.levenshteinAlphabet);for(let e=0;e0===e?0:1),(e=>0===e?0:1),((t,i)=>Math.min(1-de.Dot(e.chars[t],e.chars[i]),1))),s=new RR;return s._vector3Alphabet=e,s._levenshteinAlphabet=i,s}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new PR),this._nameToDescribedTrajectory.get(t).add(AR.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=AR.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach(((e,s)=>{e.getMatchCost(t){const t=e.data;if(t.startsWith(IR._SERVER_PREFIX)){const e=t.substr(IR._SERVER_PREFIX.length);return we.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}we.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{we.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&hR.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}IR._SERVER_PREFIX="$$";class MR{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new X,MR.IsAvailable&&(this._observer=new PressureObserver((e=>{this._currentState=e,this.onPressureChanged.notifyObservers(e)}),e))}static get IsAvailable(){return"undefined"!=typeof PressureObserver&&PressureObserver.supportedSources.includes("cpu")}observe(e){try{this._observer?.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){try{this._observer?.unobserve(e)}catch{}}dispose(){this._observer?.disconnect(),this._observer=null,this.onPressureChanged.clear()}}class OR{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const DR=1800,wR="timestamp",NR="numPoints",FR=/\r/g;class BR{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=zt.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let s=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);s=e+this.datasets.data.at(e+BR.NumberOfPointsOffset)+BR.SliceDataOffset}if(this.datasets.startingIndices.push(s),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new W(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(this._strategies.get(e)?.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,s=0;const r=t.onAfterRenderObservable.add((()=>{s=i,i=0})),n=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>s,dispose:()=>{t.onAfterRenderObservable.remove(r),this._customEventObservable.remove(n)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:s}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:s}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){const e=[zt.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);s&&(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new OR(DR),this.datasets.ids.length=0,this.datasets.startingIndices=new OR(DR),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(FR,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),s=BR.NumberOfPointsOffset;if(i.length<2)return!1;const r={ids:[],data:new OR(DR),startingIndices:new OR(DR)},[n,...o]=i;if(n.length<2||n[0]!==wR||n[s]!==NR)return!1;const a=new Map;for(let e=BR.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${wR},${NR}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const LR=()=>{};class kR{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:LR}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const s=new MR;return s.observe("cpu"),s.onPressureChanged.add((e=>{for(const s of e)if(t&&s.factors.includes(t)||!t&&0===(s.factors?.length??0))switch(s.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1}})),{id:e,getData:()=>i,dispose:()=>s.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:LR})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:LR})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:LR})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:LR})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:LR})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:LR})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add((()=>{e.getEngine()._drawCalls.fetchNewFrame()})),s=e.onAfterRenderObservable.add((()=>{t=e.getEngine()._drawCalls.current}));return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(s)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:LR})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:LR})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:LR})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:LR})}static AbsoluteFpsStrategy(){return e=>{const t=new kg(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:LR}}}static MeshesSelectionStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeActiveMeshesEvaluationObservable.add((()=>{t=zt.Now})),r=e.onAfterActiveMeshesEvaluationObservable.add((()=>{i=zt.Now-t}));return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(s),e.onAfterActiveMeshesEvaluationObservable.remove(r)}}}}static RenderTargetsStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeRenderTargetsRenderObservable.add((()=>{t=zt.Now})),r=e.onAfterRenderTargetsRenderObservable.add((()=>{i=zt.Now-t}));return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(s),e.onAfterRenderTargetsRenderObservable.remove(r)}}}}static ParticlesStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeParticlesRenderingObservable.add((()=>{t=zt.Now})),r=e.onAfterParticlesRenderingObservable.add((()=>{i=zt.Now-t}));return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(s),e.onAfterParticlesRenderingObservable.remove(r)}}}}static SpritesStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeSpritesRenderingObservable?.add((()=>{t=zt.Now})),r=e.onAfterSpritesRenderingObservable?.add((()=>{i=zt.Now-t}));return{id:"Sprites",getData:()=>i,dispose:()=>{e.onBeforeSpritesRenderingObservable?.remove(s),e.onAfterSpritesRenderingObservable?.remove(r)}}}}static AnimationsStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{t=zt.Now})),r=e.onAfterAnimationsObservable.add((()=>{i=zt.Now-t}));return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterAnimationsObservable.remove(r)}}}}static PhysicsStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforePhysicsObservable?.add((()=>{t=zt.Now})),r=e.onAfterPhysicsObservable?.add((()=>{i=zt.Now-t}));return{id:"Physics",getData:()=>i,dispose:()=>{e.onBeforePhysicsObservable?.remove(s),e.onAfterPhysicsObservable?.remove(r)}}}}static RenderStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeDrawPhaseObservable.add((()=>{t=zt.Now})),r=e.onAfterDrawPhaseObservable.add((()=>{i=zt.Now-t}));return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(s),e.onAfterDrawPhaseObservable.remove(r)}}}}static FrameTotalStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{t=zt.Now})),r=e.onAfterRenderObservable.add((()=>{i=zt.Now-t}));return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static InterFrameStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{i=zt.Now-t})),r=e.onAfterRenderObservable.add((()=>{t=zt.Now}));return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new Lg(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(1e-6*t.gpuFrameTimeCounter.current,0),dispose:()=>{t.dispose()}}}}}dr.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new BR(this)),this._perfCollector},X.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,s=new Array,r=e.add((()=>{const e=t.length;for(let r=0;r{t.push(e),i.push(r),s.push(n)},dispose:()=>{e.remove(r)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return Xr(e,this._coroutineScheduler)},X.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};async function VR(e,t){const i=t.probe??new Tv("tempProbe",t.size,e),s=!!t.probe;s||(t.position?i.position=t.position.clone():e.activeCamera&&(i.position=e.activeCamera.position.clone()));const r=t.meshesFilter?e.meshes.filter(t.meshesFilter):e.meshes;i.renderList?.push(...r),i.refreshRate=pl.REFRESHRATE_RENDER_ONCE,i.cubeTexture.render();const n=new Rx("tempProceduralTexture","equirectangularPanorama",{width:2*t.size,height:t.size},e);return n.setTexture("cubeMap",i.cubeTexture),new Promise(((e,r)=>{n.onGeneratedObservable.addOnce((()=>{const o=n.readPixels();if(!o)return r(new Error("No Pixel Data found on procedural texture")),n.dispose(),void(s||i.dispose());o.then((r=>{n.dispose(),s||i.dispose(),t.filename?(_l.DumpData(2*t.size,t.size,r,void 0,"image/png",t.filename),e(null)):e(r)}))}))}))}bi.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";class UR extends ua{constructor(e,t={}){super(e),this.options=t,this._direction=new de(0,0,-1),this._mat=new fe,this._onSelectEnabled=!1,this._origin=new de(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new X,this._onHitTestResults=e=>{const t=e.map((e=>{const t=fe.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&UR.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",hs.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then((e=>{const t=s||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;fe.FromArrayToRef(t.transform.matrix,0,this._mat),de.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),de.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});UR.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}UR.Name=ha.HIT_TEST,UR.Version=1,ca.AddWebXRFeature(UR.Name,((e,t)=>()=>new UR(e,t)),UR.Version,!1);let GR=0;class zR extends ua{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new X,this.onAnchorRemovedObservable=new X,this.onAnchorUpdatedObservable=new X,this._tmpVector=new de,this._tmpQuaternion=new pe,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new de,i=new pe){this._populateTmpTransformation(t,i);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(s);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:s,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new pe,i=!1){this._populateTmpTransformation(e,t);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let s=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),s++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),s=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,s,e),s.attachedNode&&(s.attachedNode.rotationQuaternion=s.attachedNode.rotationQuaternion||new pe,s.transformationMatrix.decompose(s.attachedNode.scaling,s.attachedNode.rotationQuaternion,s.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(s)}catch(e){hs.Warn("Anchor could not be updated")}}else{const i={id:GR++,xrAnchor:t,remove:()=>t.delete()},s=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(s),this.onAnchorAddedObservable.notifyObservers(s);const r=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];r&&(r.resolve(s),r.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new zR(e,t)),zR.Version);let WR=0;class HR extends ua{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new X,this.onPlaneRemovedObservable=new X,this.onPlaneUpdatedObservable=new X,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||e.worldInformation?.detectedPlanes;if(t){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),s=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,s,e),this.onPlaneUpdatedObservable.notifyObservers(s)}}else{const i={id:WR++,xrPlane:t,polygonDefinition:[]},s=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(s),this.onPlaneAddedObservable.notifyObservers(s)}})),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new de(e.x,e.y,e.z*t)}));const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const e=t.transformationMatrix||new fe;fe.FromArrayToRef(s.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new HR(e,t)),HR.Version);class XR extends ua{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new X}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}XR.Name=ha.BACKGROUND_REMOVER,XR.Version=1,ca.AddWebXRFeature(XR.Name,((e,t)=>()=>new XR(e,t)),XR.Version,!0);class YR{}class QR extends ua{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||ga.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=Eu("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new pe;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new ga(s,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||we.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new ga(t.rootMesh,ga.MeshImpostor,{mass:0,...this._options.physicsProperties}),s=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:s.position.clone(),oldRotation:s.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new pe,this._tmpVector=new de,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)}))}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:ga.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Eu("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new pe,this._headsetMesh.isVisible=!1,this._headsetImpostor=new ga(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e],i=t.xrController.grip||t.xrController.pointer,s=t.oldPos||t.impostorMesh.position;if(t.xrController._lastXRPose?.linearVelocity){const e=t.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setLinearVelocity(this._tmpVector)}else i.position.subtractToRef(s,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),t.impostor.setLinearVelocity(this._tmpVector);s.copyFrom(i.position),this._debugMode&&we.Log([this._tmpVector,"linear"]);const r=t.oldRotation||t.impostorMesh.rotationQuaternion;if(t.xrController._lastXRPose?.angularVelocity){const e=t.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setAngularVelocity(this._tmpVector)}else if(!r.equalsWithEpsilon(i.rotationQuaternion)){r.conjugateInPlace().multiplyToRef(i.rotationQuaternion,this._tmpQuaternion);const e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}t.impostor.setAngularVelocity(this._tmpVector)}r.copyFrom(i.rotationQuaternion),this._debugMode&&we.Log([this._tmpVector,this._tmpQuaternion,"angular"])}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}QR.Name=ha.PHYSICS_CONTROLLERS,QR.Version=1,ca.AddWebXRFeature(QR.Name,((e,t)=>()=>new QR(e,t)),QR.Version,!0);class jR extends ua{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new fe,this._tmpPos=new de,this._tmpQuat=new pe,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):hs.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new X,this.paused=!1,this.xrNativeFeatureName="hit-test",hs.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then((e=>{this._transientXrHitTestSource=e}))}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const s=e.getPose(this._xrSessionManager.referenceSpace);if(!s)return;const r=s.transform.position,n=s.transform.orientation;this._tmpPos.set(r.x,r.y,r.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(n.x,n.y,n.z,n.w),fe.FromFloat32ArrayToRefScaled(s.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const o={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(o)})),this.onHitTestResultObservable.notifyObservers(i)}}jR.Name=ha.HIT_TEST,jR.Version=2,ca.AddWebXRFeature(jR.Name,((e,t)=>()=>new jR(e,t)),jR.Version,!1);class KR extends ua{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new X,this.onFeaturePointsUpdatedObservable=new X,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=[],s=[];for(let r=0;r0&&this.onFeaturePointsAddedObservable.notifyObservers(s),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}KR.Name=ha.FEATURE_POINTS,KR.Version=1,ca.AddWebXRFeature(KR.Name,(e=>()=>new KR(e)),KR.Version);let $R=0;class qR extends ua{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new X,this.onMeshRemovedObservable=new X,this.onMeshUpdatedObservable=new X,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((e=>{this.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){try{if(!this.attached||!e)return;const t=e.detectedMeshes||e.worldInformation?.detectedMeshes;if(t){const i=new Set;this._detectedMeshes.forEach(((e,s)=>{t.has(s)||i.add(s)})),i.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),t.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:$R++,xrMesh:t},s=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,s),this.onMeshAddedObservable.notifyObservers(s)}}))}}catch(e){we.Log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let e=0;e()=>new qR(e,t)),qR.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(ZR||(ZR={}));class JR extends ua{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new X,this.onTrackableImageFoundObservable=new X,this.onTrackedImageUpdatedObservable=new X,this._trackableScoreStatus=ZR.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach((e=>{e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return hs.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===ZR.Waiting)return;if(this._trackableScoreStatus===ZR.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const s=i.index,r=this._trackedImages[s];if(!r)continue;r.xrTrackingResult=i,r.realWorldWidth!==i.measuredWidthInMeters&&(r.realWorldWidth=i.measuredWidthInMeters,t=!0);const n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){const e=r.transformationMatrix;fe.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const o="emulated"===i.trackingState;r.emulated!==o&&(r.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(r)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==ZR.NotReceived)return;this._trackableScoreStatus=ZR.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?ZR.Received:ZR.NotReceived}else this._trackableScoreStatus=ZR.NotReceived}}JR.Name=ha.IMAGE_TRACKING,JR.Version=1,ca.AddWebXRFeature(JR.Name,((e,t)=>()=>new JR(e,t)),JR.Version,!1);class eI extends ua{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",hs.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return hs.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return hs.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}eI.Name=ha.DOM_OVERLAY,eI.Version=1,ca.AddWebXRFeature(eI.Name,((e,t)=>()=>new eI(e,t)),eI.Version,!1);class tI extends ua{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new pe,this._tmpRotationMatrix=fe.Identity(),this._tmpTranslationDirection=new de,this._tmpMovementTranslation=new de,this._tempCacheQuaternion=new pe,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let s=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){s=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;s=t}if("function"==typeof i.componentSelectionPredicate&&(s=i.componentSelectionPredicate(e)),s&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===s)continue;const r={registrationConfiguration:i,component:s};t.registeredComponents.push(r),"axisChangedHandler"in i&&(r.onAxisChangedObserver=s.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(r.onButtonChangedObserver=s.onButtonStateChangedObservable.add((()=>{s.changes.pressed&&i.buttonChangedhandler(s.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=tI.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):hs.Error('WebXRControllerMovement feature requires "xrInput" option.')}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,pe.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(pe.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(fe.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),de.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}tI.Name=ha.MOVEMENT,tI.REGISTRATIONS={default:[{allowedComponentTypes:[cg.THUMBSTICK_TYPE,cg.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[cg.THUMBSTICK_TYPE,cg.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},tI.Version=1,ca.AddWebXRFeature(tI.Name,((e,t)=>()=>new tI(e,t)),tI.Version,!0);class iI extends ua{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=de.Up().negateInPlace(),this._lightColor=Ce.White(),this._intensity=1,this._sphericalHarmonics=new a_,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new X,this._updateReflectionCubeMap=()=>{if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)})))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new lm("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new de(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=nr.FALLOFF_GLTF),this._hdrFilter=new cv(this._xrSessionManager.scene.getEngine()),hs.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new No(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))})),!0}detach(){const e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new iI(e,t)),iI.Version,!1);class sI extends ua{constructor(e){super(e),this.onEyeTrackingStartedObservable=new X,this.onEyeTrackingEndedObservable=new X,this.onEyeTrackingFrameUpdateObservable=new X,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new Zo(de.Zero(),de.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const e=t.transform.orientation;ge.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?de.RightHandedForwardReadOnly.rotateByQuaternionToRef(ge.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,ge.Quaternion[0].z*=-1,ge.Quaternion[0].w*=-1,de.LeftHandedForwardReadOnly.rotateByQuaternionToRef(ge.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}sI.Name=ha.EYE_TRACKING,sI.Version=1,ca.AddWebXRFeature(sI.Name,(e=>()=>new sI(e)),sI.Version,!1);class rI{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class nI{constructor(){this._samples=new rI(20),this._entropy=0,this.onFirstStepDetected=new X}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=ue.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(a=t,o=e);if(on*this._squaredProjectionDistanceThreshold)return;const p=ge.Vector3[0];p.set(i,s,0);const f=ge.Vector3[1];f.set(h.x,h.y,0);const m=de.Cross(p,f).z>0,g=r.clone(),v=r.clone();l.subtractToRef(r,h),m?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,g),h.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,g),h.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:g,rightApex:v,currentPosition:r,currentStepDirection:m?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class aI{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new nI,this._walker=null,this._movement=new ue,this._millisecondsSinceLastUpdate=aI._MillisecondsPerUpdate,this.movementThisFrame=de.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new oI(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{we.Log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=aI._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=aI._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class lI extends ua{static get Name(){return ha.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new de,this._forward=new de,this._position=new de,this._movement=new de,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&we.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new aI(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||de.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}ca.AddWebXRFeature(lI.Name,((e,t)=>()=>new lI(e,t)),lI.Version,!1);class hI extends Cc{constructor(e,t,i,s,r,n,o=null){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n,this._originalInternalTexture=o}}class cI extends Ec{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new X,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),s="right"==t?1:0,r=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[s]||i?.textureWidth!==r||i?.textureHeight!==n){let i;const o=e.depthStencilTextureWidth??r,a=e.depthStencilTextureHeight??n;r!==o&&n!==a||(i=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(r,n,null,e.colorTexture,i,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e?.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,s=t.colorTextureHeight??t.textureHeight,r=t.viewport;e.x=r.x/i,e.y=r.y/s,e.width=r.width/i,e.height=r.height/s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class uI extends hI{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new dI(e,i,this))),this.layer=e}}class dI extends cI{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}const _I={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},pI={};class fI extends ua{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={..._I,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return!!super.detach()&&(this._existingLayers.forEach((e=>{e.dispose()})),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0)}createXRWebGLLayer(e=pI){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Ac(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=_I,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),s=new uI(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(s),s}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,s=this._existingLayers[0].layer.textureHeight,r={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:s,clearOnAccess:!0,...e.params};this._validateLayerInit(r,!1);const n=this._xrWebGLBinding.createQuadLayer(r);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new hI((()=>n.width),(()=>n.height),n,"XRQuadLayer",!1,(e=>new cI(e,this._xrWebGLBinding,o)));t&&this._compositionLayerTextureMapping.set(n,t);const a=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,a),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),s=i.layer,r={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};s.transform=new XRRigidTransform(r,{x:0,y:0,z:0,w:1});const n=this._layerToRTTProviderMapping.get(s);if(!n)throw new Error("Could not find the RTT provider for the layer");const o=this._xrSessionManager.scene.layers.find((t=>t.texture===e));if(!o)throw new Error("Could not find the babylon layer for the texture");return n.onRenderTargetTextureCreatedObservable.add((e=>{e.eye&&"right"===e.eye||(e.texture.clearColor=new Ee(0,0,0,0),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add((()=>{e.texture.render()})),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce((()=>{o.renderTargetTextures.splice(o.renderTargetTextures.indexOf(e.texture),1),o.renderOnlyInRenderTargetTextures=!1})))})),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;i.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});const s=this._layerToRTTProviderMapping.get(i);if(!s)throw new Error("Could not find the RTT provider for the layer");return s.onRenderTargetTextureCreatedObservable.add((t=>{t.texture.clearColor=new Ee(0,0,0,0),t.texture.customRenderFunction=()=>{e.render()}})),this._xrSessionManager.onXRSessionInit.add((()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)})),this._xrSessionManager.onXRSessionEnded.add((()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)})),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new fI(e,t)),fI.Version,!1);class mI extends ua{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new Pi(e,Ai.Unknown);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format="ushort"===this.depthDataFormat?2:5,t.generateMipMaps=!1,t.type="ushort"===this.depthDataFormat?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Ni(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new X,this.xrNativeFeatureName="depth-sensing",hs.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){this._cachedDepthImageTexture?.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:hs.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{data:r,width:n,height:o,rawValueToMeters:a,getDepthInMeters:l}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Wo.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,Vo.NEAREST_SAMPLINGMODE,gn.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Wo.CreateRTexture(null,n,o,a,!1,!0,Vo.NEAREST_SAMPLINGMODE,"ushort"===i?gn.TEXTURETYPE_UNSIGNED_BYTE:gn.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}mI.Name=ha.DEPTH_SENSING,mI.Version=1,ca.AddWebXRFeature(mI.Name,((e,t)=>()=>new mI(e,t)),mI.Version,!1);bi.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class gI extends pl{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[fe.Identity(),fe.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new Yu("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)})),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[1]}))}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class vI{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new gI(s,r,this._scene,n),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=s,a._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return s&&i?.textureWidth===r&&i?.textureHeight==n||(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.clear()}}class xI extends ua{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[ha.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new vI(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add((()=>this._onAfterRender())),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}xI.Name=ha.SPACE_WARP,xI.Version=1,ca.AddWebXRFeature(xI.Name,(e=>()=>new xI(e)),xI.Version,!1);class bI extends ua{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new X,this.xrNativeFeatureName="camera-access"}attach(e){return!!super.attach(e)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)}detach(){return!!super.detach()&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach((e=>e.dispose())),this.texturesData.forEach((e=>e.dispose())),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],a=i.height/2*s[5],l=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:a,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=this._glBinding?.getCameraImage(e.camera);if(this._cachedInternalTextures[t])this._cachedInternalTextures[t]._hardwareTexture?.set(i);else{const s=new Pi(this._xrSessionManager.scene.getEngine(),Ai.Unknown,!0);s.isCube=!0,s.invertY=!1,s.format=5,s.generateMipMaps=!0,s.type=1,s.samplingMode=3,s.width=e.camera.width,s.height=e.camera.height,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new Ni(i,this._glContext),this._cachedInternalTextures[t]=s;const r=new No(this._xrSessionManager.scene);r.name=`WebXR Raw Camera Access (${t})`,r._texture=this._cachedInternalTextures[t],this.texturesData[t]=r,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let s=!0;i.views.forEach(((e,t)=>{s=s&&this._updateInternalTextures(e,t)})),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}bI.Name=ha.RAW_CAMERA_ACCESS,bI.Version=1,ca.AddWebXRFeature(bI.Name,((e,t)=>()=>new bI(e,t)),bI.Version,!1);class TI extends ug{constructor(e,t,i){super(e,yI[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}mg.RegisterController("generic-hand-select-grasp",((e,t)=>new TI(t,e.gamepad,e.handedness)));const yI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class SI extends ug{constructor(e,t,i){super(e,CI["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?SI.MODEL_LEFT_FILENAME:SI.MODEL_RIGHT_FILENAME,{filename:e,path:SI.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=Pa.IsPluginForExtensionAvailable(".glb");return e||we.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],s=i.rootNodeName;if(!s)return void we.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const r=this._getChildByName(this.rootMesh,s);if(!r)return void we.Warn("Missing button mesh with name: "+s);if(i.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else we.Warn("Missing button submesh under mesh with name: "+s)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const s=this._mapping.axes[e][i],r=this._getChildByName(this.rootMesh,s.rootNodeName);r?(s.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.valueNodeName),s.minMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.minNodeName),s.maxMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.maxNodeName),s.valueMesh&&s.minMesh&&s.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(s,t,!0)}),void 0,!0):we.Warn("Missing axis submesh under mesh with name: "+s.rootNodeName)):we.Warn("Missing axis mesh with name: "+s.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew SI(t,e.gamepad,e.handedness)));const CI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class EI extends ug{constructor(e,t,i,s=!1,r=!1){super(e,AI[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?EI.MODEL_LEFT_FILENAME:EI.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?EI.QUEST_MODEL_BASE_URL:EI.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const s=e&&this.getComponent(e);s&&s.onButtonStateChangedObservable.add((s=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-s.value,this._modelRootNode.getChildren()[3].position.y=.005*-s.value,this._modelRootNode.getChildren()[3].position.z=.005*-s.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*s.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=pe.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}EI.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",EI.MODEL_LEFT_FILENAME="left.babylon",EI.MODEL_RIGHT_FILENAME="right.babylon",EI.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",mg.RegisterController("oculus-touch",((e,t)=>new EI(t,e.gamepad,e.handedness))),mg.RegisterController("oculus-touch-legacy",((e,t)=>new EI(t,e.gamepad,e.handedness,!0)));const AI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class PI extends ug{constructor(e,t,i){super(e,RI[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:PI.MODEL_FILENAME,path:PI.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=pe.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}PI.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",PI.MODEL_FILENAME="wand.babylon",mg.RegisterController("htc-vive",((e,t)=>new PI(t,e.gamepad,e.handedness)));const RI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class II{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}var MI;$_("NativeXRFrame",II),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(MI||(MI={}));class OI{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=ns(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=new(hs.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class DI{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new DI(this.value+e.value)}subtract(e){return new DI(this.value-e.value)}multiply(e){return new DI(Math.imul(this.value,e.value))}divide(e){return new DI(this.value/e.value)}getClassName(){return DI.ClassName}equals(e){return this.value===e.value}static Parse(e){return new DI(e.value)}}DI.ClassName="FlowGraphInteger",ee("FlowGraphInteger",DI);class wI{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new wI(e.typeName,e.defaultValue)}}const NI=new wI("any",void 0),FI=new wI("string",""),BI=new wI("number",0),LI=new wI("boolean",!1),kI=new wI("Vector2",ue.Zero()),VI=new wI("Vector3",de.Zero()),UI=new wI("Vector4",_e.Zero()),GI=new wI("Matrix",fe.Identity()),zI=new wI("Color3",Ce.Black()),WI=new wI("Color4",new Ee(0,0,0,0)),HI=new wI("Quaternion",pe.Identity()),XI=new wI("FlowGraphInteger",new DI(0));function YI(e){switch(typeof e){case"string":return FI;case"number":return BI;case"boolean":return LI;case"object":return e instanceof ue?kI:e instanceof de?VI:e instanceof _e?UI:e instanceof Ce?zI:e instanceof Ee?WI:e instanceof pe?HI:e instanceof DI?XI:NI;default:return NI}}class QI extends OI{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===MI.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===MI.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=OI.Parse(e,t);return i.richType=wI.Parse(e.richType),i}}function jI(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function KI(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function $I(e,t,i){const s=t?.getClassName?.()??"";jI(s)?i[e]={name:t.name,className:s}:KI(s)?i[e]={value:t.asArray(),className:s}:i[e]=t}function qI(e,t,i){const s=t[e];let r;const n=s?.className;return r=jI(n)?i.getMeshByName(s.name):KI(n)?function(e,t){if("Vector2"===e)return ue.FromArray(t);if("Vector3"===e)return de.FromArray(t);if("Vector4"===e)return _e.FromArray(t);if("Quaternion"===e)return pe.FromArray(t);if("Color3"===e)return new Ce(t[0],t[1],t[2]);if("Color4"===e)return new Ee(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,s.value):"Matrix"===n?fe.FromArray(s.value):n===DI.ClassName?DI.Parse(s):s&&void 0!==s.value?s.value:s,r}ee("FGDataConnection",QI);class ZI{constructor(e){this.config=e,this.uniqueId=ns(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new QI(e,MI.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new QI(e,MI.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=$I){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=hs.Instantiate(e.className),s={},r=t.valueParseFunction??qI;if(e.config)for(const i in e.config)s[i]=r(i,e.config,t.scene);(function(e){return"FGSetPropertyBlock"===e||"FGGetPropertyBlock"===e||"FGPlayAnimationBlock"===e||"FGMeshPickEventBlock"===e})(e.className)&&(s.pathConverter=t.pathConverter);const n=new i(s);n.uniqueId=e.uniqueId;for(let t=0;tt.name===e))}getSignalOutput(e){return this.signalOutputs.find((t=>t.name===e))}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{t.type===Ms.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||rM(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const s=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return nM.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var oM;nM.ClassName="FGMeshPickEventBlock",ee(nM.ClassName,nM),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(oM||(oM={}));class aM{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=oM.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new sM({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==oM.Started){this.state=oM.Started,0===this._executionContexts.length&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===nM.ClassName){const i=t._getReferencedMesh();let s=0;for(;s0;){const s=t.pop();e(s);for(const e of s.dataInputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId));if(s instanceof eM)for(const e of s.signalOutputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof eM)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??qI;for(const n of e.allBlocks){const e=ZI.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(e),e instanceof iM&&i.addEventBlock(e)}for(const e of s){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=aM.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof eM)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=aM.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(const t of e.executionContexts)sM.Parse(t,{graph:i,valueParseFunction:r});return i}}class lM{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()})),(lM.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new aM({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=lM.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)}))}static Parse(e,t){const i=t.valueParseFunction??qI,s=new lM({scene:t.scene});return e._flowGraphs?.forEach((e=>{aM.Parse(e,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})})),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new X,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}lM.SceneCoordinators=new Map;class hM{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add((e=>{hs.Log(`Node executed: ${e.getClassName()}`)}))}}class cM extends eM{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class uM extends cM{constructor(e){super(e),this.message=this.registerDataInput("message",NI)}_execute(e){const t=this.message.getValue(e);we.Log(t),this.out._activateSignal(e)}getClassName(){return uM.ClassName}}uM.ClassName="FGConsoleLogBlock",ee(uM.ClassName,uM);class dM extends cM{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,NI)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return dM.ClassName}}dM.ClassName="FGSetVariableBlock",ee(dM.ClassName,dM);const _M=new RegExp(/\{(\w+)\}/g);class pM{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=_M.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,XI)),i=_M.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const s=e.getValue(t).value;i=i.replace(`{${e.name}}`,s.toString())}return e.convert(i)}}class fM extends cM{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",NI),this.templateComponent=new pM(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return fM.ClassName}}fM.ClassName="FGSetPropertyBlock",ee("FGSetPropertyBlock",fM);class mM extends cM{constructor(e){super(e),this.config=e;for(let e=0;et.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return mM.ClassName}}mM.ClassName="FGSendCustomEventBlock",ee("FGSendCustomEventBlock",mM);class gM extends eM{constructor(e){super(e),this.condition=this.registerDataInput("condition",LI),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}ee("FGBranchBlock",gM);class vM extends cM{constructor(e={startIndex:new DI(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",XI),this.value=this.registerDataOutput("value",XI)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.values)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const t=s-(r-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}}ee("FGThrottleBlock",bM);class TM extends tM{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",BI)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new Ig({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);-1!==s?i.splice(s,1):hs.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return TM.ClassName}}TM.ClassName="FGTimerBlock",ee("FGTimerBlock",TM);class yM extends eM{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",BI),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter((e=>e!==r)),0===s.length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((e=>e))){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}ee("FGDebounceBlock",PM);class RM extends eM{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",LI)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}ee("FGFlipFlopBlock",RM);class IM extends eM{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e)));this.runningAnimatable.setValue(t,e),n.push(t)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);-1!==s&&i.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const e of t)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return MM.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}MM.ClassName="FGPlayAnimationBlock",ee(MM.ClassName,MM);class OM extends cM{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",NI)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}ee("FGStopAnimationBlock",OM);class DM extends cM{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",NI)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}ee("FGPauseAnimationBlock",DM);class wM extends ZI{constructor(e){super(e),this.condition=this.registerDataInput("condition",LI),this.trueValue=this.registerDataInput("trueValue",NI),this.falseValue=this.registerDataInput("falseValue",NI),this.output=this.registerDataOutput("output",NI)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}ee("FGConditionalDataBlock",wM);class NM extends ZI{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,NI)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return NM.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}NM.ClassName="FGGetVariableBlock",ee(NM.ClassName,NM);class FM extends ZI{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",NI),this.destinationSystem=this.registerDataInput("destinationSystem",NI),this.inputCoordinates=this.registerDataInput("inputCoordinates",VI),this.outputCoordinates=this.registerDataOutput("outputCoordinates",VI)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=ge.Matrix[0].copyFrom(n);o.invert();const a=ge.Matrix[1];o.multiplyToRef(r,a);const l=this.outputCoordinates.getValue(e);de.TransformCoordinatesToRef(s,a,l)}getClassName(){return"FGCoordinateTransformBlock"}}ee("FGCoordinateTransformBlock",FM);class BM extends ZI{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",YI(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=$I){super.serialize(e),t("value",this.config.value,e.config)}}ee("FGConstantBlock",BM);class LM extends ZI{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",NI),this.templateComponent=new pM(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return LM.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}LM.ClassName="FGGetPropertyBlock",ee(LM.ClassName,LM);const kM="cachedOperationValue",VM="cachedExecutionId";class UM extends ZI{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,VM),i=e._getExecutionVariable(this,kM);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,kM,t),e._setExecutionVariable(this,VM,e.executionId),this.value.setValue(t,e)}}}class GM extends UM{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class zM extends UM{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const WM="FGLogic",HM="AndBlock",XM="OrBlock",YM="NotBlock";class QM extends GM{constructor(e){super(LI,LI,LI,((e,t)=>e&&t),`${WM}${HM}`,e)}}ee(`${WM}${HM}`,QM);class jM extends GM{constructor(e){super(LI,LI,LI,((e,t)=>e||t),`${WM}${XM}`,e)}}ee(`${WM}${XM}`,jM);class KM extends zM{constructor(e){super(LI,LI,(e=>!e),`${WM}${YM}`,e)}}ee(`${WM}${YM}`,KM);class $M extends UM{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class qM extends UM{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function ZM(e){return e.getClassName?e.getClassName():""}function JM(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function eO(e,t){return"Matrix"===e&&"Matrix"===t}function tO(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class iO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicAdd(e,t)),iO.ClassName,e)}_polymorphicAdd(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||eO(i,s)||tO(i,s)?e.add(t):e+t}}iO.ClassName="FGAddBlock",ee(iO.ClassName,iO);class sO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicAdd(e,t)),sO.ClassName,e)}_polymorphicAdd(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||tO(i,s)?e.subtract(t):eO(i,s)?e.add(t.scale(-1)):e-t}}sO.ClassName="FGSubBlock",ee(sO.ClassName,sO);class rO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicMultiply(e,t)),rO.ClassName,e)}_polymorphicMultiply(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||tO(i,s)?e.multiply(t):eO(i,s)?fe.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}rO.ClassName="FGMultiplyBlock",ee(rO.ClassName,rO);class nO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicDivide(e,t)),nO.ClassName,e)}_polymorphicDivide(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||tO(i,s)?e.divide(t):eO(i,s)?fe.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}nO.ClassName="FGDivideBlock",ee(nO.ClassName,nO);class oO extends $M{constructor(e){super(BI,(()=>Math.random()),oO.ClassName,e)}}oO.ClassName="FGRandomBlock",ee(oO.ClassName,oO);class aO extends GM{constructor(e){super(NI,NI,BI,((e,t)=>this._polymorphicDot(e,t)),aO.ClassName,e)}_polymorphicDot(e,t){switch(ZM(e)){case"Vector2":return ue.Dot(e,t);case"Vector3":return de.Dot(e,t);case"Vector4":return _e.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}aO.ClassName="FGDotBlock",ee(aO.ClassName,aO);class lO extends $M{constructor(e){super(BI,(()=>Math.E),lO.ClassName,e)}}lO.ClassName="FGEBlock",ee(lO.ClassName,lO);class hO extends $M{constructor(e){super(BI,(()=>Math.PI),hO.ClassName,e)}}hO.ClassName="FGPIBlock",ee(hO.ClassName,hO);class cO extends $M{constructor(e){super(BI,(()=>Number.POSITIVE_INFINITY),cO.ClassName,e)}}cO.ClassName="FGInfBlock",ee(cO.ClassName,cO);class uO extends $M{constructor(e){super(BI,(()=>Number.NaN),uO.ClassName,e)}}function dO(e,t){switch(ZM(e)){case"FlowGraphInteger":return new DI(t(e.value));case"Vector2":return new ue(t(e.x),t(e.y));case"Vector3":return new de(t(e.x),t(e.y),t(e.z));case"Vector4":return new _e(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return fe.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}uO.ClassName="FGNaNBlock",ee(uO.ClassName,uO);class _O extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicAbs(e)),_O.ClassName,e)}_polymorphicAbs(e){return dO(e,Math.abs)}}_O.ClassName="FGAbsBlock",ee(_O.ClassName,_O);class pO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicSign(e)),pO.ClassName,e)}_polymorphicSign(e){return dO(e,Math.sign)}}pO.ClassName="FGSignBlock",ee(pO.ClassName,pO);class fO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicTrunc(e)),fO.ClassName,e)}_polymorphicTrunc(e){return dO(e,Math.trunc)}}fO.ClassName="FGTruncBlock",ee(fO.ClassName,fO);class mO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicFloor(e)),mO.ClassName,e)}_polymorphicFloor(e){return dO(e,Math.floor)}}mO.ClassName="FGFloorBlock",ee(mO.ClassName,mO);class gO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicCeiling(e)),gO.ClassName,e)}_polymorphicCeiling(e){return dO(e,Math.ceil)}}gO.ClassName="FGCeilBlock",ee(gO.ClassName,gO);class vO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicFract(e)),vO.ClassName,e)}_polymorphicFract(e){return dO(e,(e=>e-Math.floor(e)))}}vO.ClassName="FGFractBlock",ee(vO.ClassName,vO);class xO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicNeg(e)),xO.ClassName,e)}_polymorphicNeg(e){return dO(e,(e=>-e))}}function bO(e,t,i){switch(ZM(e)){case"FlowGraphInteger":return new DI(i(e.value,t.value));case"Vector2":return new ue(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new de(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new _e(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return fe.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}xO.ClassName="FGNegBlock",ee(xO.ClassName,xO);class TO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicRemainder(e,t)),TO.ClassName,e)}_polymorphicRemainder(e,t){return bO(e,t,((e,t)=>e%t))}}TO.ClassName="FGRemainderBlock",ee(TO.ClassName,TO);class yO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicMin(e,t)),yO.ClassName,e)}_polymorphicMin(e,t){return bO(e,t,Math.min)}}yO.ClassName="FGMinBlock",ee(yO.ClassName,yO);class SO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicMax(e,t)),SO.ClassName,e)}_polymorphicMax(e,t){return bO(e,t,Math.max)}}function CO(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function EO(e,t,i,s){switch(ZM(e)){case"FlowGraphInteger":return new DI(s(e.value,t.value,i.value));case"Vector2":return new ue(s(e.x,t.x,i.x),s(e.y,t.y,i.y));case"Vector3":return new de(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z));case"Vector4":return new _e(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z),s(e.w,t.w,i.w));case"Matrix":return fe.FromValues(s(e.m[0],t.m[0],i.m[0]),s(e.m[4],t.m[4],i.m[4]),s(e.m[8],t.m[8],i.m[8]),s(e.m[12],t.m[12],i.m[12]),s(e.m[1],t.m[1],i.m[1]),s(e.m[5],t.m[5],i.m[5]),s(e.m[9],t.m[9],i.m[9]),s(e.m[13],t.m[13],i.m[13]),s(e.m[2],t.m[2],i.m[2]),s(e.m[6],t.m[6],i.m[6]),s(e.m[10],t.m[10],i.m[10]),s(e.m[14],t.m[14],i.m[14]),s(e.m[3],t.m[3],i.m[3]),s(e.m[7],t.m[7],i.m[7]),s(e.m[11],t.m[11],i.m[11]),s(e.m[15],t.m[15],i.m[15]));default:return s(e,t,i)}}SO.ClassName="FGMaxBlock",ee(SO.ClassName,SO);class AO extends qM{constructor(e){super(NI,NI,NI,NI,((e,t,i)=>this._polymorphicClamp(e,t,i)),AO.ClassName,e)}_polymorphicClamp(e,t,i){return EO(e,t,i,CO)}}function PO(e){return Math.min(Math.max(e,0),1)}AO.ClassName="FGClampBlock",ee(AO.ClassName,AO);class RO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicSaturate(e)),RO.ClassName,e)}_polymorphicSaturate(e){return dO(e,PO)}}RO.ClassName="FGSaturateBlock",ee(RO.ClassName,RO);class IO extends qM{constructor(e){super(NI,NI,NI,NI,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),IO.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return EO(e,t,i,this._interpolate)}}IO.ClassName="FGInterpolateBlock",ee(IO.ClassName,IO);class MO extends GM{constructor(e){super(NI,NI,LI,((e,t)=>this._polymorphicEq(e,t)),MO.ClassName,e)}_polymorphicEq(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||eO(i,s)||tO(i,s)?e.equals(t):e===t}}function OO(e,t,i){const s=ZM(e);if(s===ZM(t)){if(""===s)return i(e,t);if("FlowGraphInteger"===s)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}MO.ClassName="FGEqBlock",ee(MO.ClassName,MO);class DO extends GM{constructor(e){super(NI,NI,LI,((e,t)=>this._polymorphicLessThan(e,t)),DO.ClassName,e)}_polymorphicLessThan(e,t){return OO(e,t,((e,t)=>ethis._polymorphicLessThanOrEqual(e,t)),wO.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return OO(e,t,((e,t)=>e<=t))}}wO.ClassName="FGLessThanOrEqualBlock";class NO extends GM{constructor(e){super(NI,NI,LI,((e,t)=>this._polymorphicGreaterThan(e,t)),NO.ClassName,e)}_polymorphicGreaterThan(e,t){return OO(e,t,((e,t)=>e>t))}}NO.ClassName="FGGreaterThanBlock",ee(NO.ClassName,NO);class FO extends GM{constructor(e){super(NI,NI,LI,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),FO.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return OO(e,t,((e,t)=>e>=t))}}FO.ClassName="FGGreaterThanOrEqualBlock",ee(FO.ClassName,FO);class BO extends zM{constructor(e){super(NI,LI,(e=>this._polymorphicIsNan(e)),BO.ClassName,e)}_polymorphicIsNan(e){const t=ZM(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}BO.ClassName="FGIsNanBlock",ee(BO.ClassName,BO);class LO extends zM{constructor(e){super(NI,LI,(e=>this._polymorphicIsInf(e)),LO.ClassName,e)}_polymorphicIsInf(e){const t=ZM(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}LO.ClassName="FGIsInfBlock";class kO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicDegToRad(e)),kO.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return dO(e,this._degToRad)}}kO.ClassName="FGDegToRadBlock",ee(kO.ClassName,kO);class VO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicRadToDeg(e)),VO.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return dO(e,this._radToDeg)}}VO.ClassName="FGRadToDegBlock",ee(VO.ClassName,VO);class UO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicSin(e)),UO.ClassName,e)}_polymorphicSin(e){return dO(e,Math.sin)}}UO.ClassName="FGSinBlock",ee(UO.ClassName,UO);class GO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicCos(e)),GO.ClassName,e)}_polymorphicCos(e){return dO(e,Math.cos)}}GO.ClassName="FGCosBlock",ee(GO.ClassName,GO);class zO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicTan(e)),zO.ClassName,e)}_polymorphicTan(e){return dO(e,Math.tan)}}zO.ClassName="FGTanBlock",ee(zO.ClassName,zO);class WO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicAsin(e)),WO.ClassName,e)}_polymorphicAsin(e){return dO(e,Math.asin)}}WO.ClassName="FGAsinBlock",ee(WO.ClassName,WO);class HO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicAcos(e)),HO.ClassName,e)}_polymorphicAcos(e){return dO(e,Math.acos)}}HO.ClassName="FGAcosBlock",ee(HO.ClassName,HO);class XO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicAtan(e)),XO.ClassName,e)}_polymorphicAtan(e){return dO(e,Math.atan)}}XO.ClassName="FGAtanBlock",ee(XO.ClassName,XO);class YO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicAtan2(e,t)),YO.ClassName,e)}_polymorphicAtan2(e,t){return bO(e,t,Math.atan2)}}YO.ClassName="FGAtan2Block",ee(YO.ClassName,YO);class QO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicSinh(e)),QO.ClassName,e)}_polymorphicSinh(e){return dO(e,Math.sinh)}}QO.ClassName="FGSinhBlock",ee(QO.ClassName,QO);class jO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicCosh(e)),jO.ClassName,e)}_polymorphicCosh(e){return dO(e,Math.cosh)}}jO.ClassName="FGCoshBlock",ee(jO.ClassName,jO);class KO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicTanh(e)),KO.ClassName,e)}_polymorphicTanh(e){return dO(e,Math.tanh)}}KO.ClassName="FGTanhBlock",ee(KO.ClassName,KO);class $O extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicAsinh(e)),$O.ClassName,e)}_polymorphicAsinh(e){return dO(e,Math.asinh)}}$O.ClassName="FGAsinhBlock",ee($O.ClassName,$O);class qO extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicAcosh(e)),qO.ClassName,e)}_polymorphicAcosh(e){return dO(e,Math.acosh)}}qO.ClassName="FGAcoshBlock",ee(qO.ClassName,qO);class ZO extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicAtanh(e)),ZO.ClassName,e)}_polymorphicAtanh(e){return dO(e,Math.atanh)}}ZO.ClassName="FGAtanhBlock",ee(ZO.ClassName,ZO);class JO extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicExp(e)),JO.ClassName,e)}_polymorphicExp(e){return dO(e,Math.exp)}}JO.ClassName="FGExpBlock",ee(JO.ClassName,JO);class eD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicLog(e)),eD.ClassName,e)}_polymorphicLog(e){return dO(e,Math.log)}}eD.ClassName="FGLogBlock",ee(eD.ClassName,eD);class tD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicLog2(e)),tD.ClassName,e)}_polymorphicLog2(e){return dO(e,Math.log2)}}tD.ClassName="FGLog2Block",ee(tD.ClassName,tD);class iD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicLog10(e)),iD.ClassName,e)}_polymorphicLog10(e){return dO(e,Math.log10)}}iD.ClassName="FGLog10Block",ee(iD.ClassName,iD);class sD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicSqrt(e)),sD.ClassName,e)}_polymorphicSqrt(e){return dO(e,Math.sqrt)}}sD.ClassName="FGSqrtBlock",ee(sD.ClassName,sD);class rD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicCubeRoot(e)),rD.ClassName,e)}_polymorphicCubeRoot(e){return dO(e,Math.cbrt)}}rD.ClassName="FGCubeRootBlock",ee(rD.ClassName,rD);class nD extends GM{constructor(e){super(NI,BI,BI,((e,t)=>this._polymorphicPow(e,t)),nD.ClassName,e)}_polymorphicPow(e,t){return bO(e,t,Math.pow)}}nD.ClassName="FGPowBlock",ee(nD.ClassName,nD);class oD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicLength(e)),oD.ClassName,e)}_polymorphicLength(e){switch(ZM(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}oD.ClassName="FGLengthBlock",ee(oD.ClassName,oD);class aD extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicNormalize(e)),aD.ClassName,e)}_polymorphicNormalize(e){switch(ZM(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}aD.ClassName="FGNormalizeBlock",ee(aD.ClassName,aD);class lD extends GM{constructor(e){super(VI,VI,VI,((e,t)=>de.Cross(e,t)),lD.ClassName,e)}}lD.ClassName="FGCrossBlock",ee(lD.ClassName,lD);class hD extends GM{constructor(e){super(kI,BI,kI,((e,t)=>ue.Transform(e,fe.RotationZ(t))),hD.ClassName,e)}}hD.ClassName="FGRotate2DBlock",ee(hD.ClassName,hD);class cD extends qM{constructor(e){super(VI,VI,BI,VI,((e,t,i)=>de.TransformCoordinates(e,fe.RotationAxis(t,i))),cD.ClassName,e)}}cD.ClassName="FGRotate3DBlock",ee(cD.ClassName,cD);class uD extends zM{constructor(e){super(GI,GI,(e=>fe.Transpose(e)),uD.ClassName,e)}}uD.ClassName="FGTransposeBlock",ee(uD.ClassName,uD);class dD extends zM{constructor(e){super(GI,BI,(e=>e.determinant()),dD.ClassName,e)}}dD.ClassName="FGDeterminantBlock",ee(dD.ClassName,dD);class _D extends zM{constructor(e){super(GI,GI,(e=>fe.Invert(e)),_D.ClassName,e)}}_D.ClassName="FGInvertMatrixBlock",ee(_D.ClassName,_D);class pD extends GM{constructor(e){super(GI,GI,GI,((e,t)=>t.multiply(e)),pD.ClassName,e)}}pD.ClassName="FGMatMulBlock",ee(pD.ClassName,pD);class fD extends zM{constructor(e){super(XI,XI,(e=>new DI(~e.value)),fD.ClassName,e)}}fD.ClassName="FGBitwiseNotBlock",ee(fD.ClassName,fD);class mD extends GM{constructor(e){super(XI,XI,XI,((e,t)=>new DI(e.value&t.value)),mD.ClassName,e)}}mD.ClassName="FGBitwiseAndBlock",ee(mD.ClassName,mD);class gD extends GM{constructor(e){super(XI,XI,XI,((e,t)=>new DI(e.value|t.value)),gD.ClassName,e)}}gD.ClassName="FGBitwiseOrBlock",ee(gD.ClassName,gD);class vD extends GM{constructor(e){super(XI,XI,XI,((e,t)=>new DI(e.value^t.value)),vD.ClassName,e)}}vD.ClassName="FGBitwiseXorBlock",ee(vD.ClassName,vD);class xD extends GM{constructor(e){super(XI,XI,XI,((e,t)=>new DI(e.value<new DI(e.value>>t.value)),bD.ClassName,e)}}bD.ClassName="FGBitwiseRightShiftBlock",ee(bD.ClassName,bD);class TD extends zM{constructor(e){super(XI,XI,(e=>new DI(Math.clz32(e.value))),TD.ClassName,e)}}TD.ClassName="FGCountLeadingZerosBlock",ee(TD.ClassName,TD);class yD extends zM{constructor(e){super(XI,XI,(e=>new DI(e.value?31-Math.clz32(e.value&-e.value):32)),yD.ClassName,e)}}yD.ClassName="FGCountTrailingZerosBlock",ee(yD.ClassName,yD);class SD extends zM{constructor(e){super(XI,XI,(e=>new DI(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),SD.ClassName,e)}}SD.ClassName="FGCountOneBitsBlock",ee(SD.ClassName,SD);class CD extends iM{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return CD.ClassName}}CD.ClassName="FGSceneReadyEventBlock",ee("FGSceneReadyEventBlock",CD);class ED extends iM{constructor(e){super(e),this.config=e;for(let e=0;e{for(let i=0;i{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return AD.ClassName}}AD.ClassName="FGSceneTickEventBlock",ee(AD.ClassName,AD);class PD{constructor(e,t=PD.UNITMODE_PIXEL,i=!0){this.negativeValueAllowed=i,this._value=1,this._unit=PD.UNITMODE_PIXEL,this.ignoreAdaptiveScaling=!1,this.onChangedObservable=new X,this._value=e,this._unit=t,this._originalUnit=t}get isPercentage(){return this._unit===PD.UNITMODE_PERCENTAGE}get isPixel(){return this._unit===PD.UNITMODE_PIXEL}get internalValue(){return this._value}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this.onChangedObservable.notifyObservers())}get unit(){return this._unit}set unit(e){e!==this._unit&&(this._unit=e,this.onChangedObservable.notifyObservers())}getValueInPixel(e,t){return this.isPixel?this.getValue(e):this.getValue(e)*t}updateInPlace(e,t=PD.UNITMODE_PIXEL){return this.value===e&&this.unit===t||(this._value=e,this._unit=t,this.onChangedObservable.notifyObservers()),this}getValue(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==PD.UNITMODE_PERCENTAGE){let t=0,i=0;if(e.idealWidth&&(t=Math.ceil(this._value*e.getSize().width/e.idealWidth)),e.idealHeight&&(i=Math.ceil(this._value*e.getSize().height/e.idealHeight)),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidth{this._markAsDirty(),this._resetFontCache()}))),this._markAsDirty(),this._resetFontCache()}get _isFontSizeInPercentage(){return this._fontSize.isPercentage}get fontSizeInPixels(){const e=this._style?this._style._fontSize:this._fontSize;return e.isPixel?e.getValue(this._host):e.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)}set fontSizeInPixels(e){isNaN(e)||(this.fontSize=e+"px")}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&(this._markAsDirty(),this._resetFontCache())}get color(){return this._color}set color(e){this._color!==e&&(this._color=e,this._markAsDirty())}get gradient(){return this._gradient}set gradient(e){this._gradient!==e&&(this._gradient=e,this._markAsDirty())}get zIndex(){return this._zIndex}set zIndex(e){this.zIndex!==e&&(this._zIndex=e,this.parent&&this.parent._reOrderControl(this))}get notRenderable(){return this._doNotRender}set notRenderable(e){this._doNotRender!==e&&(this._doNotRender=e,this._markAsDirty())}get isVisible(){return this._isVisible}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this._markAsDirty(!0),this.onIsVisibleChangedObservable.notifyObservers(e))}get isDirty(){return this._isDirty}get linkedMesh(){return this._linkedMesh}get descendantsOnlyPadding(){return this._descendantsOnlyPadding}set descendantsOnlyPadding(e){this._descendantsOnlyPadding!==e&&(this._descendantsOnlyPadding=e,this._markAsDirty())}get paddingLeft(){return this._paddingLeft.toString(this._host)}set paddingLeft(e){this._paddingLeft.fromString(e)&&this._markAsDirty()}get paddingLeftInPixels(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingLeftInPixels(e){isNaN(e)||(this.paddingLeft=e+"px")}get _paddingLeftInPixels(){return this._descendantsOnlyPadding?0:this.paddingLeftInPixels}get paddingRight(){return this._paddingRight.toString(this._host)}set paddingRight(e){this._paddingRight.fromString(e)&&this._markAsDirty()}get paddingRightInPixels(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingRightInPixels(e){isNaN(e)||(this.paddingRight=e+"px")}get _paddingRightInPixels(){return this._descendantsOnlyPadding?0:this.paddingRightInPixels}get paddingTop(){return this._paddingTop.toString(this._host)}set paddingTop(e){this._paddingTop.fromString(e)&&this._markAsDirty()}get paddingTopInPixels(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingTopInPixels(e){isNaN(e)||(this.paddingTop=e+"px")}get _paddingTopInPixels(){return this._descendantsOnlyPadding?0:this.paddingTopInPixels}get paddingBottom(){return this._paddingBottom.toString(this._host)}set paddingBottom(e){this._paddingBottom.fromString(e)&&this._markAsDirty()}get paddingBottomInPixels(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingBottomInPixels(e){isNaN(e)||(this.paddingBottom=e+"px")}get _paddingBottomInPixels(){return this._descendantsOnlyPadding?0:this.paddingBottomInPixels}get left(){return this._left.toString(this._host)}set left(e){this._left.fromString(e)&&this._markAsDirty()}get leftInPixels(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)}set leftInPixels(e){isNaN(e)||(this.left=e+"px")}get top(){return this._top.toString(this._host)}set top(e){this._top.fromString(e)&&this._markAsDirty()}get topInPixels(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)}set topInPixels(e){isNaN(e)||(this.top=e+"px")}get linkOffsetX(){return this._linkOffsetX.toString(this._host)}set linkOffsetX(e){this._linkOffsetX.fromString(e)&&this._markAsDirty()}get linkOffsetXInPixels(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)}set linkOffsetXInPixels(e){isNaN(e)||(this.linkOffsetX=e+"px")}get linkOffsetY(){return this._linkOffsetY.toString(this._host)}set linkOffsetY(e){this._linkOffsetY.fromString(e)&&this._markAsDirty()}get linkOffsetYInPixels(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)}set linkOffsetYInPixels(e){isNaN(e)||(this.linkOffsetY=e+"px")}get centerX(){return this._currentMeasure.left+this._currentMeasure.width/2}get centerY(){return this._currentMeasure.top+this._currentMeasure.height/2}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled===e)return;this._isEnabled=e,this._markAsDirty();const t=e=>{if(e.host){for(const t in e.host._lastControlOver)e===this.host._lastControlOver[t]&&(e._onPointerOut(e,null,!0),delete e.host._lastControlOver[t]);void 0!==e.children&&e.children.forEach(t)}};t(this),this.onEnabledStateChangedObservable.notifyObservers(e)}get disabledColor(){return this._disabledColor}set disabledColor(e){this._disabledColor!==e&&(this._disabledColor=e,this._markAsDirty())}get disabledColorItem(){return this._disabledColorItem}set disabledColorItem(e){this._disabledColorItem!==e&&(this._disabledColorItem=e,this._markAsDirty())}constructor(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=DD.Empty(),this._tempPaddingMeasure=DD.Empty(),this._fontFamily="",this._fontStyle="",this._fontWeight="",this._fontSize=new PD(18,PD.UNITMODE_PIXEL,!1),this._width=new PD(1,PD.UNITMODE_PERCENTAGE,!1),this._height=new PD(1,PD.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._wasDirty=!1,this._tempParentMeasure=DD.Empty(),this._prevCurrentMeasureTransformedIntoGlobalSpace=DD.Empty(),this._cachedParentMeasure=DD.Empty(),this._descendantsOnlyPadding=!1,this._paddingLeft=new PD(0),this._paddingRight=new PD(0),this._paddingTop=new PD(0),this._paddingBottom=new PD(0),this._left=new PD(0),this._top=new PD(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=ND.Identity(),this._invertTransformMatrix=ND.Identity(),this._transformedPosition=ue.Zero(),this._isMatrixDirty=!0,this._isVisible=!0,this._isHighlighted=!1,this._highlightColor="#4affff",this._highlightLineWidth=2,this._fontSet=!1,this._dummyVector2=ue.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this._evaluatedMeasure=new DD(0,0,0,0),this._evaluatedParentMeasure=new DD(0,0,0,0),this._isEnabled=!0,this._disabledColor="#9a9a9a",this._disabledColorItem="#6a6a6a",this._isReadOnly=!1,this._gradient=null,this._rebuildLayout=!1,this.onEnabledStateChangedObservable=new X,this._customData={},this._isClipped=!1,this._automaticSize=!1,this.metadata=null,this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this._clipChildren=!0,this._clipContent=!0,this.useBitmapCache=!1,this._shadowOffsetX=0,this._shadowOffsetY=0,this._shadowBlur=0,this._previousShadowBlur=0,this._shadowColor="black",this.hoverCursor="",this._linkOffsetX=new PD(0),this._linkOffsetY=new PD(0),this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new X,this.onWheelObservable=new X,this.onPointerMoveObservable=new X,this.onPointerOutObservable=new X,this.onPointerDownObservable=new X,this.onPointerUpObservable=new X,this.onPointerClickObservable=new X,this.onPointerEnterObservable=new X,this.onDirtyObservable=new X,this.onBeforeDrawObservable=new X,this.onAfterDrawObservable=new X,this.onDisposeObservable=new X,this.onIsVisibleChangedObservable=new X,this.isSerializable=!0,this._fixedRatio=0,this._fixedRatioMasterIsWidth=!0,this.animations=null,this._tmpMeasureA=new DD(0,0,0,0)}_getTypeName(){return"Control"}getAscendantOfClass(e){return this.parent?this.parent.getClassName()===e?this.parent:this.parent.getAscendantOfClass(e):null}markAsDirty(e=!1){this._markAsDirty(e)}markAllAsDirty(){this._markAllAsDirty()}_resetFontCache(){this._fontSet=!0,this._markAsDirty()}isAscendant(e){return!!this.parent&&(this.parent===e||this.parent.isAscendant(e))}getLocalCoordinates(e){const t=ue.Zero();return this.getLocalCoordinatesToRef(e,t),t}getLocalCoordinatesToRef(e,t){return t.x=e.x-this._currentMeasure.left,t.y=e.y-this._currentMeasure.top,this}getParentLocalCoordinates(e){const t=ue.Zero();return t.x=e.x-this._cachedParentMeasure.left,t.y=e.y-this._cachedParentMeasure.top,t}moveToVector3(e,t){if(!this._host||this.parent!==this._host._rootContainer)return void hs.Error("Cannot move a control to a vector3 if the control is not at root level");this.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP;const i=this._host._getGlobalViewport(),s=de.Project(e,fe.IdentityReadOnly,t.getTransformMatrix(),i);this._moveToProjectedPosition(s),s.z<0||s.z>1?this.notRenderable=!0:this.notRenderable=!1}getDescendantsToRef(e,t=!1,i){}getDescendants(e,t){const i=[];return this.getDescendantsToRef(i,e,t),i}linkWithMesh(e){if(!this._host||this.parent&&this.parent!==this._host._rootContainer)return void(e&&hs.Error("Cannot link a control to a mesh if the control is not at root level"));const t=this._host._linkedControls.indexOf(this);if(-1!==t)return this._linkedMesh=e,void(e||this._host._linkedControls.splice(t,1));e&&(this.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._host._linkedControls.push(this))}setPadding(e,t,i,s){const r=e,n=t??r,o=i??r,a=s??n;this.paddingTop=r,this.paddingRight=n,this.paddingBottom=o,this.paddingLeft=a}setPaddingInPixels(e,t,i,s){const r=e,n=t??r,o=i??r,a=s??n;this.paddingTopInPixels=r,this.paddingRightInPixels=n,this.paddingBottomInPixels=o,this.paddingLeftInPixels=a}_moveToProjectedPosition(e){const t=this._left.getValue(this._host),i=this._top.getValue(this._host),s=this.parent?._currentMeasure;s&&this._processMeasures(s,this._host.getContext());let r=e.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,n=e.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;const o=this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling;o&&(Math.abs(r-t)<.5&&(r=t),Math.abs(n-i)<.5&&(n=i)),(o||t!==r||i!==n)&&(this.left=r+"px",this.top=n+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0,this._markAsDirty())}_offsetLeft(e){this._isDirty=!0,this._currentMeasure.left+=e}_offsetTop(e){this._isDirty=!0,this._currentMeasure.top+=e}_markMatrixAsDirty(){this._isMatrixDirty=!0,this._flagDescendantsAsMatrixDirty()}_flagDescendantsAsMatrixDirty(){}_intersectsRect(e,t){return this._transform(t),!(this._evaluatedMeasure.left>=e.left+e.width||this._evaluatedMeasure.top>=e.top+e.height||this._evaluatedMeasure.left+this._evaluatedMeasure.width<=e.left||this._evaluatedMeasure.top+this._evaluatedMeasure.height<=e.top)}_computeAdditionalOffsetX(){return 0}_computeAdditionalOffsetY(){return 0}invalidateRect(){if(this._transform(),this.host&&this.host.useInvalidateRectOptimization){this._currentMeasure.transformToRef(this._transformMatrix,this._tmpMeasureA),DD.CombineToRef(this._tmpMeasureA,this._prevCurrentMeasureTransformedIntoGlobalSpace,this._tmpMeasureA);const e=this.shadowOffsetX,t=this.shadowOffsetY,i=Math.max(this._previousShadowBlur,this.shadowBlur),s=Math.min(Math.min(e,0)-2*i,0),r=Math.max(Math.max(e,0)+2*i,0),n=Math.min(Math.min(t,0)-2*i,0),o=Math.max(Math.max(t,0)+2*i,0),a=this._computeAdditionalOffsetX(),l=this._computeAdditionalOffsetY();this.host.invalidateRect(Math.floor(this._tmpMeasureA.left+s-a),Math.floor(this._tmpMeasureA.top+n-l),Math.ceil(this._tmpMeasureA.left+this._tmpMeasureA.width+r+a),Math.ceil(this._tmpMeasureA.top+this._tmpMeasureA.height+o+l))}}_markAsDirty(e=!1){(this._isVisible||e)&&(this._isDirty=!0,this._markMatrixAsDirty(),this._host&&this._host.markAsDirty())}_markAllAsDirty(){this._markAsDirty(),this._font&&this._prepareFont()}_link(e){this._host=e,this._host&&(this.uniqueId=this._host.getScene().getUniqueId())}_transform(e){if(!this._isMatrixDirty&&1===this._scaleX&&1===this._scaleY&&0===this._rotation)return;const t=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;e&&(e.translate(t,i),e.rotate(this._rotation),e.scale(this._scaleX,this._scaleY),e.translate(-t,-i)),(this._isMatrixDirty||this._cachedOffsetX!==t||this._cachedOffsetY!==i)&&(this._cachedOffsetX=t,this._cachedOffsetY=i,this._isMatrixDirty=!1,this._flagDescendantsAsMatrixDirty(),ND.ComposeToRef(-t,-i,this._rotation,this._scaleX,this._scaleY,this.parent?this.parent._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure))}_renderHighlight(e){this.isHighlighted&&(e.save(),e.strokeStyle=this._highlightColor,e.lineWidth=this._highlightLineWidth,this._renderHighlightSpecific(e),e.restore())}_renderHighlightSpecific(e){e.strokeRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)}_getColor(e){return this.gradient?this.gradient.getCanvasGradient(e):this.color}_applyStates(e){this._isFontSizeInPercentage&&(this._fontSet=!0),this._host&&this._host.useSmallestIdeal&&!this._font&&(this._fontSet=!0),this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(e.font=this._font),(this._color||this.gradient)&&(e.fillStyle=this._getColor(e)),BD.AllowAlphaInheritance?e.globalAlpha*=this._alpha:this._alphaSet&&(e.globalAlpha=this.parent&&!this.parent.renderToIntermediateTexture?this.parent.alpha*this._alpha:this._alpha)}_layout(e,t){if(!this.isDirty&&(!this.isVisible||this.notRenderable))return!1;if(this._isDirty||!this._cachedParentMeasure.isEqualsTo(e)){this.host._numLayoutCalls++,this._currentMeasure.addAndTransformToRef(this._transformMatrix,0|-this._paddingLeftInPixels,0|-this._paddingTopInPixels,0|this._paddingRightInPixels,0|this._paddingBottomInPixels,this._prevCurrentMeasureTransformedIntoGlobalSpace),t.save(),this._applyStates(t);let i=0;do{this._rebuildLayout=!1,this._processMeasures(e,t),i++}while(this._rebuildLayout&&i<3);i>=3&&we.Error(`Layout cycle detected in GUI (Control name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this.invalidateRect(),this._evaluateClippingState(e)}return this._wasDirty=this._isDirty,this._isDirty=!1,!0}_processMeasures(e,t){this._tempPaddingMeasure.copyFrom(e),this.parent&&this.parent.descendantsOnlyPadding&&(this._tempPaddingMeasure.left+=this.parent.paddingLeftInPixels,this._tempPaddingMeasure.top+=this.parent.paddingTopInPixels,this._tempPaddingMeasure.width-=this.parent.paddingLeftInPixels+this.parent.paddingRightInPixels,this._tempPaddingMeasure.height-=this.parent.paddingTopInPixels+this.parent.paddingBottomInPixels),this._currentMeasure.copyFrom(this._tempPaddingMeasure),this._preMeasure(this._tempPaddingMeasure,t),this._measure(),this._postMeasure(this._tempPaddingMeasure,t),this._computeAlignment(this._tempPaddingMeasure,t),this._currentMeasure.left=0|this._currentMeasure.left,this._currentMeasure.top=0|this._currentMeasure.top,this._currentMeasure.width=0|this._currentMeasure.width,this._currentMeasure.height=0|this._currentMeasure.height,this._additionalProcessing(this._tempPaddingMeasure,t),this._cachedParentMeasure.copyFrom(this._tempPaddingMeasure),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)}_evaluateClippingState(e){if(this._transform(),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.parent&&this.parent.clipChildren){if(e.transformToRef(this.parent._transformMatrix,this._evaluatedParentMeasure),this._evaluatedMeasure.left>this._evaluatedParentMeasure.left+this._evaluatedParentMeasure.width)return void(this._isClipped=!0);if(this._evaluatedMeasure.left+this._evaluatedMeasure.widththis._evaluatedParentMeasure.top+this._evaluatedParentMeasure.height)return void(this._isClipped=!0);if(this._evaluatedMeasure.top+this._evaluatedMeasure.heightthis._currentMeasure.left+this._currentMeasure.width||tthis._currentMeasure.top+this._currentMeasure.height||(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),0))}_processPicking(e,t,i,s,r,n,o,a){return!(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this._doNotRender||!this.contains(e,t)||(this._processObservables(s,e,t,i,r,n,o,a),0))}_onPointerMove(e,t,i,s){this.onPointerMoveObservable.notifyObservers(t,-1,e,this,s)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerMove(e,t,i,s)}_onPointerEnter(e,t){return!!this._isEnabled&&(!(this._enterCount>0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,e,this,t)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerEnter(e,t),!0))}_onPointerOut(e,t,i=!1){if(!(i||this._isEnabled&&e!==this))return;this._enterCount=0;let s=!0;e.isAscendant(this)||(s=this.onPointerOutObservable.notifyObservers(this,-1,e,this,t)),s&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return this._onPointerEnter(this,r),0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new wD(t,s),-1,e,this,r)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerDown(e,t,i,s,r),r&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.add(r.event.pointerId),!0)}_onPointerUp(e,t,i,s,r,n){if(!this._isEnabled)return;this._downCount=0,delete this._downPointerIds[i];let o=r;r&&(this._enterCount>0||-1===this._enterCount)&&(o=this.onPointerClickObservable.notifyObservers(new wD(t,s),-1,e,this,n)),this.onPointerUpObservable.notifyObservers(new wD(t,s),-1,e,this,n)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerUp(e,t,i,s,o,n),n&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.delete(n.event.pointerId)}_forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,ue.Zero(),e,0,!0);else for(const e in this._downPointerIds)this._onPointerUp(this,ue.Zero(),+e,0,!0)}_onWheelScroll(e,t){this._isEnabled&&this.onWheelObservable.notifyObservers(new ue(e,t))&&null!=this.parent&&this.parent._onWheelScroll(e,t)}_onCanvasBlur(){}_processObservables(e,t,i,s,r,n,o,a){if(!this._isEnabled)return!1;if(this._dummyVector2.copyFromFloats(t,i),e===Ms.POINTERMOVE){this._onPointerMove(this,this._dummyVector2,r,s);const e=this._host._lastControlOver[r];return e&&e!==this&&e._onPointerOut(this,s),e!==this&&this._onPointerEnter(this,s),this._host._lastControlOver[r]=this,!0}return e===Ms.POINTERDOWN?(this._onPointerDown(this,this._dummyVector2,r,n,s),this._host._registerLastControlDown(this,r),this._host._lastPickedControl=this,!0):e===Ms.POINTERUP?(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,this._dummyVector2,r,n,!0,s),delete this._host._lastControlDown[r],!0):!(e!==Ms.POINTERWHEEL||!this._host._lastControlOver[r]||(this._host._lastControlOver[r]._onWheelScroll(o,a),0))}_getStyleProperty(e,t){const i=(this._style&&this._style[e])??this[e];return!i&&this.parent?this.parent._getStyleProperty(e,t):this.parent?i:t}_prepareFont(){(this._font||this._fontSet)&&(this._font=this._getStyleProperty("fontStyle","")+" "+this._getStyleProperty("fontWeight","")+" "+this.fontSizeInPixels+"px "+this._getStyleProperty("fontFamily","Arial"),this._fontOffset=BD._GetFontOffset(this._font),this.getDescendants().forEach((e=>e._markAllAsDirty())))}isDimensionFullyDefined(e){return this.getDimension(e).isPixel}getDimension(e){return"width"===e?this._width:this._height}clone(e){const t={};this.serialize(t,!0);const i=new(hs.Instantiate("BABYLON.GUI."+t.className));return i.parse(t,e),i}parse(e,t){return yt.Parse((()=>this),e,null),this.name=e.name,this._parseFromContent(e,t??this._host),this}serialize(e,t=!1){(this.isSerializable||t)&&(yt.Serialize(this,e),e.name=this.name,e.className=this.getClassName(),this._prepareFont(),this._font&&(e.fontFamily=this._fontFamily,e.fontSize=this.fontSize,e.fontWeight=this.fontWeight,e.fontStyle=this.fontStyle),this._gradient&&(e.gradient={},this._gradient.serialize(e.gradient)),yt.AppendSerializedAnimations(this,e))}_parseFromContent(e,t){if(e.fontFamily&&(this.fontFamily=e.fontFamily),e.fontSize&&(this.fontSize=e.fontSize),e.fontWeight&&(this.fontWeight=e.fontWeight),e.fontStyle&&(this.fontStyle=e.fontStyle),e.gradient){const t=hs.Instantiate("BABYLON.GUI."+e.gradient.className);this._gradient=new t,this._gradient?.parse(e.gradient)}if(e.animations){this.animations=[];for(let t=0;t-1&&this.linkWithMesh(null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}static get HORIZONTAL_ALIGNMENT_LEFT(){return BD._HORIZONTAL_ALIGNMENT_LEFT}static get HORIZONTAL_ALIGNMENT_RIGHT(){return BD._HORIZONTAL_ALIGNMENT_RIGHT}static get HORIZONTAL_ALIGNMENT_CENTER(){return BD._HORIZONTAL_ALIGNMENT_CENTER}static get VERTICAL_ALIGNMENT_TOP(){return BD._VERTICAL_ALIGNMENT_TOP}static get VERTICAL_ALIGNMENT_BOTTOM(){return BD._VERTICAL_ALIGNMENT_BOTTOM}static get VERTICAL_ALIGNMENT_CENTER(){return BD._VERTICAL_ALIGNMENT_CENTER}static _GetFontOffset(e){if(BD._FontHeightSizes[e])return BD._FontHeightSizes[e];const t=se.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");const i=t.getFontOffset(e);return BD._FontHeightSizes[e]=i,i}static Parse(e,t){const i=hs.Instantiate("BABYLON.GUI."+e.className),s=yt.Parse((()=>new i),e,null);return s.name=e.name,s._parseFromContent(e,t),s}static drawEllipse(e,t,i,s,r){r.translate(e,t),r.scale(i,s),r.beginPath(),r.arc(0,0,1,0,2*Math.PI),r.closePath(),r.scale(1/i,1/s),r.translate(-e,-t)}isReady(){return!0}}BD.AllowAlphaInheritance=!1,BD._ClipMeasure=new DD(0,0,0,0),BD._HORIZONTAL_ALIGNMENT_LEFT=0,BD._HORIZONTAL_ALIGNMENT_RIGHT=1,BD._HORIZONTAL_ALIGNMENT_CENTER=2,BD._VERTICAL_ALIGNMENT_TOP=0,BD._VERTICAL_ALIGNMENT_BOTTOM=1,BD._VERTICAL_ALIGNMENT_CENTER=2,BD._FontHeightSizes={},BD.AddHeader=()=>{},qe([st()],BD.prototype,"metadata",void 0),qe([st()],BD.prototype,"isHitTestVisible",void 0),qe([st()],BD.prototype,"isPointerBlocker",void 0),qe([st()],BD.prototype,"isFocusInvisible",void 0),qe([st()],BD.prototype,"clipChildren",null),qe([st()],BD.prototype,"clipContent",null),qe([st()],BD.prototype,"useBitmapCache",void 0),qe([st()],BD.prototype,"shadowOffsetX",null),qe([st()],BD.prototype,"shadowOffsetY",null),qe([st()],BD.prototype,"shadowBlur",null),qe([st()],BD.prototype,"shadowColor",null),qe([st()],BD.prototype,"hoverCursor",void 0),qe([st()],BD.prototype,"fontOffset",null),qe([st()],BD.prototype,"alpha",null),qe([st()],BD.prototype,"isSerializable",void 0),qe([st()],BD.prototype,"scaleX",null),qe([st()],BD.prototype,"scaleY",null),qe([st()],BD.prototype,"rotation",null),qe([st()],BD.prototype,"transformCenterY",null),qe([st()],BD.prototype,"transformCenterX",null),qe([st()],BD.prototype,"horizontalAlignment",null),qe([st()],BD.prototype,"verticalAlignment",null),qe([st()],BD.prototype,"fixedRatio",null),qe([st()],BD.prototype,"fixedRatioMasterIsWidth",null),qe([st()],BD.prototype,"width",null),qe([st()],BD.prototype,"height",null),qe([st()],BD.prototype,"style",null),qe([st()],BD.prototype,"color",null),qe([st()],BD.prototype,"gradient",null),qe([st()],BD.prototype,"zIndex",null),qe([st()],BD.prototype,"notRenderable",null),qe([st()],BD.prototype,"isVisible",null),qe([st()],BD.prototype,"descendantsOnlyPadding",null),qe([st()],BD.prototype,"paddingLeft",null),qe([st()],BD.prototype,"paddingRight",null),qe([st()],BD.prototype,"paddingTop",null),qe([st()],BD.prototype,"paddingBottom",null),qe([st()],BD.prototype,"left",null),qe([st()],BD.prototype,"top",null),qe([st()],BD.prototype,"linkOffsetX",null),qe([st()],BD.prototype,"linkOffsetY",null),qe([st()],BD.prototype,"isEnabled",null),qe([st()],BD.prototype,"disabledColor",null),qe([st()],BD.prototype,"disabledColorItem",null),qe([st()],BD.prototype,"overlapGroup",void 0),qe([st()],BD.prototype,"overlapDeltaMultiplier",void 0),ee("BABYLON.GUI.Control",BD);class LD extends BD{get renderToIntermediateTexture(){return this._renderToIntermediateTexture}set renderToIntermediateTexture(e){this._renderToIntermediateTexture!==e&&(this._renderToIntermediateTexture=e,this._markAsDirty())}get adaptHeightToChildren(){return this._adaptHeightToChildren}set adaptHeightToChildren(e){this._adaptHeightToChildren!==e&&(this._adaptHeightToChildren=e,e&&(this.height="100%"),this._markAsDirty())}get adaptWidthToChildren(){return this._adaptWidthToChildren}set adaptWidthToChildren(e){this._adaptWidthToChildren!==e&&(this._adaptWidthToChildren=e,e&&(this.width="100%"),this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get backgroundGradient(){return this._backgroundGradient}set backgroundGradient(e){this._backgroundGradient!==e&&(this._backgroundGradient=e,this._markAsDirty())}get children(){return this._children}get isReadOnly(){return this._isReadOnly}set isReadOnly(e){this._isReadOnly=e;for(const t of this._children)t.isReadOnly=e}constructor(e){super(e),this.name=e,this._children=new Array,this._measureForChildren=DD.Empty(),this._background="",this._backgroundGradient=null,this._adaptWidthToChildren=!1,this._adaptHeightToChildren=!1,this._renderToIntermediateTexture=!1,this._intermediateTexture=null,this.delegatePickingToChildren=!1,this.logLayoutCycleErrors=!1,this.maxLayoutCycle=3,this.onControlAddedObservable=new X,this.onControlRemovedObservable=new X,this._inverseTransformMatrix=ND.Identity(),this._inverseMeasure=new DD(0,0,0,0)}_getTypeName(){return"Container"}_flagDescendantsAsMatrixDirty(){for(const e of this.children)e._isClipped=!1,e._markMatrixAsDirty()}getChildByName(e){for(const t of this.children)if(t.name===e)return t;return null}getChildByType(e,t){for(const e of this.children)if(e.typeName===t)return e;return null}containsControl(e){return-1!==this.children.indexOf(e)}addControl(e){return e?(-1!==this._children.indexOf(e)||(e._link(this._host),e._markAllAsDirty(),this._reOrderControl(e),this._markAsDirty(),this.onControlAddedObservable.notifyObservers(e)),this):this}clearControls(){const e=this.children.slice();for(const t of e)this.removeControl(t);return this}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null),e.linkWithMesh(null),this._host&&this._host._cleanControlAfterRemoval(e),this._markAsDirty(),this.onControlRemovedObservable.notifyObservers(e),this}_reOrderControl(e){const t=e.linkedMesh;this.removeControl(e);let i=!1;for(let t=0;te.zIndex){this._children.splice(t,0,e),i=!0;break}i||this._children.push(e),e.parent=this,t&&e.linkWithMesh(t),this._markAsDirty()}_offsetLeft(e){super._offsetLeft(e);for(const t of this._children)t._offsetLeft(e)}_offsetTop(e){super._offsetTop(e);for(const t of this._children)t._offsetTop(e)}_markAllAsDirty(){super._markAllAsDirty();for(let e=0;e=0&&(s+=this.paddingLeftInPixels+this.paddingRightInPixels,this.width!==s+"px"&&(this.parent?._markAsDirty(),this.width=s+"px",this._width.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this.adaptHeightToChildren&&r>=0&&(r+=this.paddingTopInPixels+this.paddingBottomInPixels,this.height!==r+"px"&&(this.parent?._markAsDirty(),this.height=r+"px",this._height.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this._postMeasure()}i++}while(this._rebuildLayout&&i=3&&this.logLayoutCycleErrors&&we.Error(`Layout cycle detected in GUI (Container name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this._isDirty&&(this.invalidateRect(),this._isDirty=!1),!0}_postMeasure(){}_draw(e,t){const i=this._renderToIntermediateTexture&&this._intermediateTexture,s=i?this._intermediateTexture.getContext():e;i&&(s.save(),s.translate(-this._currentMeasure.left,-this._currentMeasure.top),t?(this._transformMatrix.invertToRef(this._inverseTransformMatrix),t.transformToRef(this._inverseTransformMatrix,this._inverseMeasure),s.clearRect(this._inverseMeasure.left,this._inverseMeasure.top,this._inverseMeasure.width,this._inverseMeasure.height)):s.clearRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._localDraw(s),e.save(),this.clipChildren&&this._clipForChildren(s);for(const e of this._children)t&&!e._intersectsRect(t)||e._render(s,t);i&&(s.restore(),e.save(),e.globalAlpha=this.alpha,e.drawImage(s.canvas,this._currentMeasure.left,this._currentMeasure.top),e.restore()),e.restore()}getDescendantsToRef(e,t=!1,i){if(this.children)for(let s=0;s=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}for(let l=this._children.length-1;l>=0;l--){const h=this._children[l];if(h._processPicking(e,t,i,s,r,n,o,a))return h.hoverCursor&&this._host._changeCursor(h.hoverCursor),!0}return!!l&&!!this.isHitTestVisible&&this._processObservables(s,e,t,i,r,n,o,a)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(this._currentMeasure)}_getAdaptDimTo(e){return"width"===e?this.adaptWidthToChildren:this.adaptHeightToChildren}isDimensionFullyDefined(e){if(this._getAdaptDimTo(e)){for(const t of this.children)if(!t.isDimensionFullyDefined(e))return!1;return!0}return super.isDimensionFullyDefined(e)}serialize(e,t=!1){if(super.serialize(e,t),(this.isSerializable||t)&&(this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient)),this.children.length)){e.children=[];for(const i of this.children)if(i.isSerializable||t){const t={};i.serialize(t),e.children.push(t)}}}dispose(){super.dispose();for(let e=this.children.length-1;e>=0;e--)this.children[e].dispose();this._intermediateTexture?.dispose()}_parseFromContent(e,t){if(super._parseFromContent(e,t),this._link(t),e.backgroundGradient){const t=hs.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this._backgroundGradient=new t,this._backgroundGradient?.parse(e.backgroundGradient)}if(e.children)for(const i of e.children)this.addControl(BD.Parse(i,t))}isReady(){for(const e of this.children)if(!e.isReady())return!1;return!0}}qe([st()],LD.prototype,"delegatePickingToChildren",void 0),qe([st()],LD.prototype,"renderToIntermediateTexture",null),qe([st()],LD.prototype,"maxLayoutCycle",void 0),qe([st()],LD.prototype,"adaptHeightToChildren",null),qe([st()],LD.prototype,"adaptWidthToChildren",null),qe([st()],LD.prototype,"background",null),qe([st()],LD.prototype,"backgroundGradient",null),ee("BABYLON.GUI.Container",LD);class kD extends LD{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get cornerRadius(){return this._cornerRadius[0]}set cornerRadius(e){e<0&&(e=0),this._cornerRadius[0]===e&&this._cornerRadius[1]===e&&this._cornerRadius[2]===e&&this._cornerRadius[3]===e||(this._cornerRadius[0]=this._cornerRadius[1]=this._cornerRadius[2]=this._cornerRadius[3]=e,this._markAsDirty())}get cornerRadiusX(){return this._cornerRadius[0]}set cornerRadiusX(e){this._cornerRadius[0]!==e&&(this._cornerRadius[0]=e)}get cornerRadiusY(){return this._cornerRadius[1]}set cornerRadiusY(e){this._cornerRadius[1]!==e&&(this._cornerRadius[1]=e)}get cornerRadiusZ(){return this._cornerRadius[2]}set cornerRadiusZ(e){this._cornerRadius[2]!==e&&(this._cornerRadius[2]=e)}get cornerRadiusW(){return this._cornerRadius[3]}set cornerRadiusW(e){this._cornerRadius[3]!==e&&(this._cornerRadius[3]=e)}constructor(e){super(e),this.name=e,this._thickness=1,this._cornerRadius=[0,0,0,0],this._cachedRadius=[0,0,0,0]}_getTypeName(){return"Rectangle"}_computeAdditionalOffsetX(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_computeAdditionalOffsetY(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_getRectangleFill(e){return this._getBackgroundColor(e)}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),(this._background||this._backgroundGradient)&&(e.fillStyle=this._getRectangleFill(e),0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.fill()):e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._thickness&&((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),(this.color||this.gradient)&&(e.strokeStyle=this.gradient?this.gradient.getCanvasGradient(e):this.color),e.lineWidth=this._thickness,0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.stroke()):e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness)),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_drawRoundedRect(e,t=0){const i=this._currentMeasure.left+t,s=this._currentMeasure.top+t,r=this._currentMeasure.width-2*t,n=this._currentMeasure.height-2*t;for(let e=0;ei&&(i=t.width)}if(this._resizeToFit){if(this._textWrapping===VD.Clip||this._forceResizeWidth){const e=Math.ceil(this._paddingLeftInPixels)+Math.ceil(this._paddingRightInPixels)+Math.ceil(i);e!==this._width.getValueInPixel(this._host,this._tempParentMeasure.width)&&(this._width.updateInPlace(e,PD.UNITMODE_PIXEL),this._rebuildLayout=!0)}let e=this._paddingTopInPixels+this._paddingBottomInPixels+this._fontOffset.height*this._lines.length|0;if(this._lines.length>0&&0!==this._lineSpacing.internalValue){let t=0;t=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),e+=(this._lines.length-1)*t}e!==this._height.internalValue&&(this._height.updateInPlace(e,PD.UNITMODE_PIXEL),this._rebuildLayout=!0)}}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=0;switch(this._textHorizontalAlignment){case BD.HORIZONTAL_ALIGNMENT_LEFT:n=0;break;case BD.HORIZONTAL_ALIGNMENT_RIGHT:n=r-t;break;case BD.HORIZONTAL_ALIGNMENT_CENTER:n=(r-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,this._currentMeasure.left+n,i),this._underline&&this._drawLine(this._currentMeasure.left+n,i+3,this._currentMeasure.left+n+t,i+3,s),this._lineThrough&&this._drawLine(this._currentMeasure.left+n,i-this.fontSizeInPixels/3,this._currentMeasure.left+n+t,i-this.fontSizeInPixels/3,s)}_drawLine(e,t,i,s,r){if(r.beginPath(),r.lineWidth=Math.round(.05*this.fontSizeInPixels),r.moveTo(e,t),r.lineTo(i,s),this.outlineWidth&&this.applyOutlineToUnderline)r.stroke(),r.fill();else{const e=r.strokeStyle;r.strokeStyle=r.fillStyle,r.stroke(),r.strokeStyle=e}r.closePath()}_draw(e){e.save(),this._applyStates(e),this._renderLines(e),e.restore()}_applyStates(e){super._applyStates(e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor,e.lineJoin="miter",e.miterLimit=2)}_breakLines(e,t,i){this._linesTemp.length=0;const s=this.text.split("\n");if(this._textWrapping===VD.Ellipsis)for(const t of s)this._linesTemp.push(this._parseLineEllipsis(t,e,i));else if(this._textWrapping===VD.WordWrap)for(const t of s)this._linesTemp.push(...this._parseLineWordWrap(t,e,i));else if(this._textWrapping===VD.WordWrapEllipsis)for(const r of s)this._linesTemp.push(...this._parseLineWordWrapEllipsis(r,e,t,i));else for(const e of s)this._linesTemp.push(this._parseLine(e,i));return this._linesTemp}_parseLine(e="",t){return{text:e,width:this._getTextMetricsWidth(t.measureText(e))}}_getCharsToRemove(e,t,i){const s=e>t?e-t:0,r=e/i;return Math.max(Math.floor(s/r),1)}_parseLineEllipsis(e="",t,i){let s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);const n=Array.from&&Array.from(e);if(n)for(;n.length&&s>t;)n.splice(n.length-r,r),e=`${n.join("")}…`,s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);else{for(;e.length>2&&s>t;)e=e.slice(0,-r),s=this._getTextMetricsWidth(i.measureText(e+"…")),r=this._getCharsToRemove(s,t,e.length);e+="…"}return{text:e,width:s}}_getTextMetricsWidth(e){return void 0!==e.actualBoundingBoxLeft?Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight):e.width}_parseLineWordWrap(e="",t,i){const s=[],r=this.wordSplittingFunction?this.wordSplittingFunction(e):e.split(this._wordDivider);let n=this._getTextMetricsWidth(i.measureText(e));for(let o=0;o0?e+this._wordDivider+r[o]:r[0],l=this._getTextMetricsWidth(i.measureText(a));l>t&&o>0?(s.push({text:e,width:n}),e=r[o],n=this._getTextMetricsWidth(i.measureText(e))):(n=l,e=a)}return s.push({text:e,width:n}),s}_parseLineWordWrapEllipsis(e="",t,i,s){const r=this._parseLineWordWrap(e,t,s);for(let e=1;e<=r.length;e++)if(this._computeHeightForLinesOf(e)>i&&e>1){const i=r[e-2],n=r[e-1];r[e-2]=this._parseLineEllipsis(i.text+this._wordDivider+n.text,t,s);const o=r.length-e+1;for(let e=0;e0&&0!==this._lineSpacing.internalValue){let i=0;i=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),t+=(e-1)*i}return t}isDimensionFullyDefined(e){return!!this.resizeToFit||super.isDimensionFullyDefined(e)}computeExpectedHeight(){if(this.text&&this.widthInPixels){const e=se.LastCreatedEngine?.createCanvas(0,0).getContext("2d");if(e){this._applyStates(e),this._fontOffset||(this._fontOffset=BD._GetFontOffset(e.font));const t=this._lines?this._lines:this._breakLines(this.widthInPixels-this._paddingLeftInPixels-this._paddingRightInPixels,this.heightInPixels-this._paddingTopInPixels-this._paddingBottomInPixels,e);return this._computeHeightForLinesOf(t.length)}}return 0}dispose(){super.dispose(),this.onTextChangedObservable.clear()}}qe([st()],UD.prototype,"resizeToFit",null),qe([st()],UD.prototype,"textWrapping",null),qe([st()],UD.prototype,"text",null),qe([st()],UD.prototype,"textHorizontalAlignment",null),qe([st()],UD.prototype,"textVerticalAlignment",null),qe([st()],UD.prototype,"lineSpacing",null),qe([st()],UD.prototype,"outlineWidth",null),qe([st()],UD.prototype,"underline",null),qe([st()],UD.prototype,"lineThrough",null),qe([st()],UD.prototype,"applyOutlineToUnderline",null),qe([st()],UD.prototype,"outlineColor",null),qe([st()],UD.prototype,"wordDivider",null),qe([st()],UD.prototype,"forceResizeWidth",null),ee("BABYLON.GUI.TextBlock",UD);class GD extends BD{get isLoaded(){return this._loaded}isReady(){return this.isLoaded}get detectPointerOnOpaqueOnly(){return this._detectPointerOnOpaqueOnly}set detectPointerOnOpaqueOnly(e){this._detectPointerOnOpaqueOnly!==e&&(this._detectPointerOnOpaqueOnly=e)}get sliceLeft(){return this._sliceLeft}set sliceLeft(e){this._sliceLeft!==e&&(this._sliceLeft=e,this._markAsDirty())}get sliceRight(){return this._sliceRight}set sliceRight(e){this._sliceRight!==e&&(this._sliceRight=e,this._markAsDirty())}get sliceTop(){return this._sliceTop}set sliceTop(e){this._sliceTop!==e&&(this._sliceTop=e,this._markAsDirty())}get sliceBottom(){return this._sliceBottom}set sliceBottom(e){this._sliceBottom!==e&&(this._sliceBottom=e,this._markAsDirty())}get sourceLeft(){return this._sourceLeft}set sourceLeft(e){this._sourceLeft!==e&&(this._sourceLeft=e,this._markAsDirty())}get sourceTop(){return this._sourceTop}set sourceTop(e){this._sourceTop!==e&&(this._sourceTop=e,this._markAsDirty())}get sourceWidth(){return this._sourceWidth}set sourceWidth(e){this._sourceWidth!==e&&(this._sourceWidth=e,this._markAsDirty())}get sourceHeight(){return this._sourceHeight}set sourceHeight(e){this._sourceHeight!==e&&(this._sourceHeight=e,this._markAsDirty())}get imageWidth(){return this._imageWidth}get imageHeight(){return this._imageHeight}get populateNinePatchSlicesFromImage(){return this._populateNinePatchSlicesFromImage}set populateNinePatchSlicesFromImage(e){this._populateNinePatchSlicesFromImage!==e&&(this._populateNinePatchSlicesFromImage=e,this._populateNinePatchSlicesFromImage&&this._loaded&&this._extractNinePatchSliceDataFromImage())}get isSVG(){return this._isSVG}get svgAttributesComputationCompleted(){return this._svgAttributesComputationCompleted}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale!==e&&(this._autoScale=e,e&&this._loaded&&this.synchronizeSizeWithContent())}get stretch(){return this._stretch}set stretch(e){this._stretch!==e&&(this._stretch=e,this._markAsDirty())}_rotate90(e,t=!1){const i=this._domImage.width,s=this._domImage.height,r=this._host?.getScene()?.getEngine()||se.LastCreatedEngine;if(!r)throw new Error("Invalid engine. Unable to create a canvas.");const n=r.createCanvas(s,i),o=n.getContext("2d");o.translate(n.width/2,n.height/2),o.rotate(e*Math.PI/2),o.drawImage(this._domImage,0,0,i,s,-i/2,-s/2,i,s);const a=n.toDataURL("image/jpg"),l=new GD(this.name+"rotated",a);return t&&(l._stretch=this._stretch,l._autoScale=this._autoScale,l._cellId=this._cellId,l._cellWidth=e%1?this._cellHeight:this._cellWidth,l._cellHeight=e%1?this._cellWidth:this._cellHeight),this._handleRotationForSVGImage(this,l,e),this._imageDataCache.data=null,l}_handleRotationForSVGImage(e,t,i){e._isSVG&&(e._svgAttributesComputationCompleted?(this._rotate90SourceProperties(e,t,i),this._markAsDirty()):e.onSVGAttributesComputedObservable.addOnce((()=>{this._rotate90SourceProperties(e,t,i),this._markAsDirty()})))}_rotate90SourceProperties(e,t,i){let s=e.sourceLeft,r=e.sourceTop,n=e.domImage.width,o=e.domImage.height,a=s,l=r,h=e.sourceWidth,c=e.sourceHeight;if(0!=i){const e=i<0?-1:1;i%=4;for(let t=0;t127&&-1===this._sliceLeft)this._sliceLeft=t;else if(e<127&&this._sliceLeft>-1){this._sliceRight=t;break}}this._sliceTop=-1,this._sliceBottom=-1;for(let i=0;i127&&-1===this._sliceTop)this._sliceTop=i;else if(t<127&&this._sliceTop>-1){this._sliceBottom=i;break}}}set domImage(e){this._domImage=e,this._loaded=!1,this._imageDataCache.data=null,this._domImage.width?this._onImageLoaded():this._domImage.onload=()=>{this._onImageLoaded()}}get domImage(){return this._domImage}_onImageLoaded(){this._imageDataCache.data=null,this._imageWidth=this._domImage.width,this._imageHeight=this._domImage.height,this._loaded=!0,this._populateNinePatchSlicesFromImage&&this._extractNinePatchSliceDataFromImage(),this._autoScale&&this.synchronizeSizeWithContent(),this.onImageLoadedObservable.notifyObservers(this),this._markAsDirty()}get source(){return this._source}static ResetImageCache(){GD.SourceImgCache.clear()}_removeCacheUsage(e){const t=e&&GD.SourceImgCache.get(e);t&&(t.timesUsed-=1,0===t.timesUsed&&GD.SourceImgCache.delete(e))}set source(e){if(this._source===e)return;this._removeCacheUsage(this._source),this._loaded=!1,this._source=e,this._imageDataCache.data=null,e&&(e=this._svgCheck(e));const t=this._host?.getScene()?.getEngine()||se.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");if(e&&GD.SourceImgCache.has(e)){const t=GD.SourceImgCache.get(e);return this._domImage=t.img,t.timesUsed+=1,void(t.loaded?this._onImageLoaded():t.waitingForLoadCallback.push(this._onImageLoaded.bind(this)))}this._domImage=t.createCanvasImage(),e&&GD.SourceImgCache.set(e,{img:this._domImage,timesUsed:1,loaded:!1,waitingForLoadCallback:[this._onImageLoaded.bind(this)]}),this._domImage.onload=()=>{if(e){const t=GD.SourceImgCache.get(e);if(t){t.loaded=!0;for(const e of t.waitingForLoadCallback)e();return void(t.waitingForLoadCallback.length=0)}}this._onImageLoaded()},e&&(hs.SetCorsBehavior(e,this._domImage),hs.SetReferrerPolicyBehavior(this.referrerPolicy,this._domImage),this._domImage.src=e)}_svgCheck(e){if(window.SVGSVGElement&&-1!==e.search(/.svg#/gi)&&e.indexOf("#")===e.lastIndexOf("#")){this._isSVG=!0;const t=e.split("#")[0],i=e.split("#")[1],s=document.body.querySelector('object[data="'+t+'"]');if(s){const t=s.contentDocument;if(t&&t.documentElement){const r=t.documentElement.getAttribute("viewBox"),n=Number(t.documentElement.getAttribute("width")),o=Number(t.documentElement.getAttribute("height"));if(t.getElementById(i)&&r&&n&&o)return this._getSVGAttribs(s,i),e}s.addEventListener("load",(()=>{this._getSVGAttribs(s,i)}))}else{const e=document.createElement("object");e.data=t,e.type="image/svg+xml",e.width="0%",e.height="0%",document.body.appendChild(e),e.onload=()=>{const e=document.body.querySelector('object[data="'+t+'"]');e&&this._getSVGAttribs(e,i)}}return t}return e}_getSVGAttribs(e,t){const i=e.contentDocument;if(i&&i.documentElement){const e=i.documentElement.getAttribute("viewBox"),s=Number(i.documentElement.getAttribute("width")),r=Number(i.documentElement.getAttribute("height")),n=i.getElementById(t);if(e&&s&&r&&n){const t=Number(e.split(" ")[2]),i=Number(e.split(" ")[3]),o=n.getBBox();let a=1,l=1,h=0,c=0;const u=n.transform.baseVal.consolidate().matrix;n.transform&&n.transform.baseVal.consolidate()&&(a=u.a,l=u.d,h=u.e,c=u.f),this.sourceLeft=(a*o.x+h)*s/t,this.sourceTop=(l*o.y+c)*r/i,this.sourceWidth=o.width*a*(s/t),this.sourceHeight=o.height*l*(r/i),this._svgAttributesComputationCompleted=!0,this.onSVGAttributesComputedObservable.notifyObservers(this)}}}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth!==e&&(this._cellWidth=e,this._markAsDirty())}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight!==e&&(this._cellHeight=e,this._markAsDirty())}get cellId(){return this._cellId}set cellId(e){this._cellId!==e&&(this._cellId=e,this._markAsDirty())}constructor(e,t=null){super(e),this.name=e,this._workingCanvas=null,this._loaded=!1,this._stretch=GD.STRETCH_FILL,this._autoScale=!1,this._sourceLeft=0,this._sourceTop=0,this._sourceWidth=0,this._sourceHeight=0,this._svgAttributesComputationCompleted=!1,this._isSVG=!1,this._cellWidth=0,this._cellHeight=0,this._cellId=-1,this._populateNinePatchSlicesFromImage=!1,this._imageDataCache={data:null,key:""},this.onImageLoadedObservable=new X,this.onSVGAttributesComputedObservable=new X,this.source=t}contains(e,t){if(!super.contains(e,t))return!1;if(!this._detectPointerOnOpaqueOnly||!this._workingCanvas)return!0;const i=0|this._currentMeasure.width,s=0|this._currentMeasure.height,r=i+"_"+s;let n=this._imageDataCache.data;if(!n||this._imageDataCache.key!==r){const e=this._workingCanvas.getContext("2d");this._imageDataCache.data=n=e.getImageData(0,0,i,s).data,this._imageDataCache.key=r}return n[4*((e=e-this._currentMeasure.left|0)+(t=t-this._currentMeasure.top|0)*i)+3]>0}_getTypeName(){return"Image"}synchronizeSizeWithContent(){this._loaded&&(this.width=this._domImage.width+"px",this.height=this._domImage.height+"px")}_processMeasures(e,t){if(this._loaded)switch(this._stretch){case GD.STRETCH_NONE:case GD.STRETCH_FILL:case GD.STRETCH_UNIFORM:case GD.STRETCH_NINE_PATCH:break;case GD.STRETCH_EXTEND:this._autoScale&&this.synchronizeSizeWithContent(),this.parent&&this.parent.parent&&(this.parent.adaptWidthToChildren=!0,this.parent.adaptHeightToChildren=!0)}super._processMeasures(e,t)}_prepareWorkingCanvasForOpaqueDetection(){if(!this._detectPointerOnOpaqueOnly)return;const e=this._currentMeasure.width,t=this._currentMeasure.height;if(!this._workingCanvas){const i=this._host?.getScene()?.getEngine()||se.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");this._workingCanvas=i.createCanvas(e,t)}this._workingCanvas.getContext("2d").clearRect(0,0,e,t)}_drawImage(e,t,i,s,r,n,o,a,l){if(e.drawImage(this._domImage,t,i,s,r,n,o,a,l),!this._detectPointerOnOpaqueOnly)return;const h=e.getTransform(),c=this._workingCanvas.getContext("2d");c.save();const u=n-this._currentMeasure.left,d=o-this._currentMeasure.top;c.setTransform(h.a,h.b,h.c,h.d,(u+a)/2,(d+l)/2),c.translate(-(u+a)/2,-(d+l)/2),c.drawImage(this._domImage,t,i,s,r,u,d,a,l),c.restore()}_draw(e){let t,i,s,r;if(e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),-1==this.cellId)t=this._sourceLeft,i=this._sourceTop,s=this._sourceWidth?this._sourceWidth:this._imageWidth,r=this._sourceHeight?this._sourceHeight:this._imageHeight;else{const e=this._domImage.naturalWidth/this.cellWidth,n=this.cellId/e|0,o=this.cellId%e;t=this.cellWidth*o,i=this.cellHeight*n,s=this.cellWidth,r=this.cellHeight}if(this._prepareWorkingCanvasForOpaqueDetection(),this._applyStates(e),this._loaded)switch(this._stretch){case GD.STRETCH_NONE:case GD.STRETCH_FILL:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case GD.STRETCH_UNIFORM:{const n=this._currentMeasure.width/s,o=this._currentMeasure.height/r,a=Math.min(n,o),l=(this._currentMeasure.width-s*a)/2,h=(this._currentMeasure.height-r*a)/2;this._drawImage(e,t,i,s,r,this._currentMeasure.left+l,this._currentMeasure.top+h,s*a,r*a);break}case GD.STRETCH_EXTEND:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case GD.STRETCH_NINE_PATCH:this._renderNinePatch(e,t,i,s,r)}e.restore()}_renderNinePatch(e,t,i,s,r){const n=this._sliceLeft,o=this._sliceTop,a=r-this._sliceBottom,l=s-this._sliceRight,h=this._sliceRight-this._sliceLeft,c=this._sliceBottom-this._sliceTop,u=this._currentMeasure.width-l-n+2,d=this._currentMeasure.height-a-o+2,_=this._currentMeasure.left+n-1,p=this._currentMeasure.top+o-1,f=this._currentMeasure.left+this._currentMeasure.width-l,m=this._currentMeasure.top+this._currentMeasure.height-a;this._drawImage(e,t,i,n,o,this._currentMeasure.left,this._currentMeasure.top,n,o),this._drawImage(e,t+this._sliceLeft,i,h,o,_+1,this._currentMeasure.top,u-2,o),this._drawImage(e,t+this._sliceRight,i,l,o,f,this._currentMeasure.top,l,o),this._drawImage(e,t,i+this._sliceTop,n,c,this._currentMeasure.left,p+1,n,d-2),this._drawImage(e,t+this._sliceLeft,i+this._sliceTop,h,c,_,p,u,d),this._drawImage(e,t+this._sliceRight,i+this._sliceTop,l,c,f,p+1,l,d-2),this._drawImage(e,t,i+this._sliceBottom,n,a,this._currentMeasure.left,m,n,a),this._drawImage(e,t+this.sliceLeft,i+this._sliceBottom,h,a,_+1,m,u-2,a),this._drawImage(e,t+this._sliceRight,i+this._sliceBottom,l,a,f,m,l,a)}dispose(){super.dispose(),this.onImageLoadedObservable.clear(),this.onSVGAttributesComputedObservable.clear(),this._removeCacheUsage(this._source)}}GD.SourceImgCache=new Map,GD.STRETCH_NONE=0,GD.STRETCH_FILL=1,GD.STRETCH_UNIFORM=2,GD.STRETCH_EXTEND=3,GD.STRETCH_NINE_PATCH=4,qe([st()],GD.prototype,"detectPointerOnOpaqueOnly",null),qe([st()],GD.prototype,"sliceLeft",null),qe([st()],GD.prototype,"sliceRight",null),qe([st()],GD.prototype,"sliceTop",null),qe([st()],GD.prototype,"sliceBottom",null),qe([st()],GD.prototype,"sourceLeft",null),qe([st()],GD.prototype,"sourceTop",null),qe([st()],GD.prototype,"sourceWidth",null),qe([st()],GD.prototype,"sourceHeight",null),qe([st()],GD.prototype,"populateNinePatchSlicesFromImage",null),qe([st()],GD.prototype,"autoScale",null),qe([st()],GD.prototype,"stretch",null),qe([st()],GD.prototype,"source",null),qe([st()],GD.prototype,"cellWidth",null),qe([st()],GD.prototype,"cellHeight",null),qe([st()],GD.prototype,"cellId",null),ee("BABYLON.GUI.Image",GD);class zD extends kD{get image(){return this._image}get textBlock(){return this._textBlock}constructor(e){super(e),this.name=e,this.thickness=1,this.isPointerBlocker=!0;let t=null;this.pointerEnterAnimation=()=>{t=this.alpha,this.alpha-=.1},this.pointerOutAnimation=()=>{null!==t&&(this.alpha=t)},this.pointerDownAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"Button"}_processPicking(e,t,i,s,r,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(s,e,t,i,r,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(!this.isReadOnly&&this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)}_onPointerOut(e,t,i=!1){!this.isReadOnly&&this.pointerOutAnimation&&this.pointerOutAnimation(),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(!this.isReadOnly&&this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_getRectangleFill(e){return this.isEnabled?this._getBackgroundColor(e):this._disabledColor}_onPointerUp(e,t,i,s,r,n){!this.isReadOnly&&this.pointerUpAnimation&&this.pointerUpAnimation(),super._onPointerUp(e,t,i,s,r,n)}serialize(e,t){super.serialize(e,t),(this.isSerializable||t)&&(this._textBlock&&(e.textBlockName=this._textBlock.name),this._image&&(e.imageName=this._image.name))}_parseFromContent(e,t){super._parseFromContent(e,t),e.textBlockName&&(this._textBlock=this.getChildByName(e.textBlockName)),e.imageName&&(this._image=this.getChildByName(e.imageName))}static CreateImageButton(e,t,i){const s=new this(e),r=new UD(e+"_button",t);r.textWrapping=!0,r.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,r.paddingLeft="20%",s.addControl(r);const n=new GD(e+"_icon",i);return n.width="20%",n.stretch=GD.STRETCH_UNIFORM,n.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,s.addControl(n),s._image=n,s._textBlock=r,s}static CreateImageOnlyButton(e,t){const i=new this(e),s=new GD(e+"_icon",t);return s.stretch=GD.STRETCH_FILL,s.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,i.addControl(s),i._image=s,i}static CreateSimpleButton(e,t){const i=new this(e),s=new UD(e+"_button",t);return s.textWrapping=!0,s.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,i.addControl(s),i._textBlock=s,i}static CreateImageWithCenterTextButton(e,t,i){const s=new this(e),r=new GD(e+"_icon",i);r.stretch=GD.STRETCH_FILL,s.addControl(r);const n=new UD(e+"_button",t);return n.textWrapping=!0,n.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,s.addControl(n),s._image=r,s._textBlock=n,s}}ee("BABYLON.GUI.Button",zD);class WD extends LD{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get spacing(){return this._spacing}set spacing(e){this._spacing!==e&&(this._spacing=e,this._markAsDirty())}set width(e){this._doNotTrackManualChanges||(this._manualWidth=!0),this._width.toString(this._host)!==e&&this._width.fromString(e)&&this._markAsDirty()}get width(){return this._width.toString(this._host)}set height(e){this._doNotTrackManualChanges||(this._manualHeight=!0),this._height.toString(this._host)!==e&&this._height.fromString(e)&&this._markAsDirty()}get height(){return this._height.toString(this._host)}constructor(e){super(e),this.name=e,this._isVertical=!0,this._manualWidth=!1,this._manualHeight=!1,this._doNotTrackManualChanges=!1,this._spacing=0,this.ignoreLayoutWarnings=!1}_getTypeName(){return"StackPanel"}_preMeasure(e,t){for(const e of this._children)this._isVertical?e.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP:e.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT;super._preMeasure(e,t)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(e),this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this.isVertical&&!this._manualWidth||(this._measureForChildren.width=this._currentMeasure.width),(this.isVertical||this._manualHeight)&&(this._measureForChildren.height=this._currentMeasure.height)}_postMeasure(){let e=0,t=0;const i=this._children.length;for(let s=0;s=0?Math.min(e,this._characters.length):this._characters.length+Math.max(e,-this._characters.length),void 0===t?t=this._characters.length-e:(isNaN(t)||t<0)&&(t=0);const i=[];for(;--t>=0;)i[t]=this._characters[e+t];return i.join("")}return this._text.substr(e,t)}substring(e,t){if(this._characters){isNaN(e)?e=0:e>this._characters.length?e=this._characters.length:e<0&&(e=0),void 0===t?t=this._characters.length:isNaN(t)?t=0:t>this._characters.length?t=this._characters.length:t<0&&(t=0);const i=[];let s=0;for(;e{switch(e.type){case qf.COPY:this._onCopyText(e.event),this.onTextCopyObservable.notifyObservers(this);break;case qf.CUT:this._onCutText(e.event),this.onTextCutObservable.notifyObservers(this);break;case qf.PASTE:this._onPasteText(e.event),this.onTextPasteObservable.notifyObservers(this);break;default:return}}));const e=this._host.getScene();e&&(this._onPointerDblTapObserver=e.onPointerObservable.add((e=>{this._isFocused&&e.type===Ms.POINTERDOUBLETAP&&this._processDblClick(e)}))),this._onFocusSelectAll&&this._selectAllText()}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}_getTypeName(){return"InputText"}keepsFocusWith(){return this._connectedVirtualKeyboard?[this._connectedVirtualKeyboard]:null}processKey(e,t,i){if(!this.isReadOnly&&(!i||!i.ctrlKey&&!i.metaKey||67!==e&&86!==e&&88!==e)){if(i&&(i.ctrlKey||i.metaKey)&&65===e)return this._selectAllText(),void i.preventDefault();switch(e){case 32:t=" ";break;case 191:i&&i.preventDefault();break;case 8:if(this._textWrapper.text&&this._textWrapper.length>0){if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this._blinkIsEven=!1,void(i&&i.preventDefault());if(0===this._cursorOffset)this.text=this._textWrapper.substr(0,this._textWrapper.length-1);else{const e=this._textWrapper.length-this._cursorOffset;e>0&&(this._textWrapper.removePart(e-1,e),this._textHasChanged())}}return void(i&&i.preventDefault());case 46:if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,void(i&&i.preventDefault());if(this._textWrapper.text&&this._textWrapper.length>0&&this._cursorOffset>0){const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e+1),this._textHasChanged(),this._cursorOffset--}return void(i&&i.preventDefault());case 13:return this._host.focusedControl=null,void(this.isTextHighlightOn=!1);case 35:return this._cursorOffset=0,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 36:return this._cursorOffset=this._textWrapper.length,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 37:if(this._cursorOffset++,this._cursorOffset>this._textWrapper.length&&(this._cursorOffset=this._textWrapper.length),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(this._textWrapper.length===this._cursorOffset)return;this._endHighlightIndex=this._textWrapper.length-this._cursorOffset+1}return this._startHighlightIndex=0,this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=this._textWrapper.length,this.isTextHighlightOn=!0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=0===this._startHighlightIndex?this._textWrapper.length:this._textWrapper.length-this._startHighlightIndex+1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset>=this._textWrapper.length?this._textWrapper.length:this._cursorOffset-1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=this._textWrapper.length,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty();case 39:if(this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(0===this._cursorOffset)return;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset-1}return this._endHighlightIndex=this._textWrapper.length,this.isTextHighlightOn=!0,this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=this._textWrapper.length===this._endHighlightIndex?0:this._textWrapper.length-this._endHighlightIndex-1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset<=0?0:this._cursorOffset+1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._endHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=0,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty()}if(32===e&&(t=i?.key??" "),this._deadKey="Dead"===t,t&&(-1===e||32===e||34===e||39===e||e>47&&e<64||e>64&&e<91||e>159&&e<193||e>218&&e<223||e>95&&e<112)&&(this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&!this._deadKey))if(this.isTextHighlightOn)this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex,t),this._textHasChanged(),this._cursorOffset=this._textWrapper.length-(this._startHighlightIndex+1),this.isTextHighlightOn=!1,this._blinkIsEven=!1,this._markAsDirty();else if(0===this._cursorOffset)this.text+=this._deadKey&&i?.key?i.key:t;else{const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e,t),this._textHasChanged()}}}_updateValueFromCursorIndex(e){if(this._blinkIsEven=!1,-1===this._cursorIndex)this._cursorIndex=e;else if(this._cursorIndexthis._cursorOffset))return this.isTextHighlightOn=!1,void this._markAsDirty();this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex}this.isTextHighlightOn=!0,this._markAsDirty()}_processDblClick(e){let t,i;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset,this._endHighlightIndex=this._startHighlightIndex;do{i=this._endHighlightIndex0&&this._textWrapper.isWord(this._startHighlightIndex-1)?--this._startHighlightIndex:0}while(t||i);this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!0,this._clickedCoordinate=null,this._blinkIsEven=!0,this._cursorIndex=-1,this._markAsDirty()}_selectAllText(){this._blinkIsEven=!0,this.isTextHighlightOn=!0,this._startHighlightIndex=0,this._endHighlightIndex=this._textWrapper.length,this._cursorOffset=this._textWrapper.length,this._cursorIndex=-1,this._markAsDirty()}processKeyboard(e){this.processKey(e.keyCode,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e)}_onCopyText(e){this.isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._highlightedText=""}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData;const i=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(i,i,t),this._textHasChanged()}_draw(e){e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._fontOffset&&!this._wasDirty||(this._fontOffset=BD._GetFontOffset(e.font));const t=this._currentMeasure.left+this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this.color&&(e.fillStyle=this.color);let i=this._beforeRenderText(this._textWrapper);this._isFocused||this._textWrapper.text||!this._placeholderText||(i=new XD,i.text=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(i.text).width;const s=2*this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,this._tempParentMeasure.width),this._textWidth+s)+"px",this._autoStretchWidth=!0);const r=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,n=this._width.getValueInPixel(this._host,this._tempParentMeasure.width)-s;if(e.save(),e.beginPath(),e.rect(t,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,n+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>n){const e=t-this._textWidth+n;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=t;if(this.outlineWidth&&e.strokeText(i.text,this._scrollLeft,this._currentMeasure.top+r),e.fillText(i.text,this._scrollLeft,this._currentMeasure.top+r),this._isFocused){if(this._clickedCoordinate){const t=this._scrollLeft+this._textWidth-this._clickedCoordinate;let s=0;this._cursorOffset=0;let r=0;do{this._cursorOffset&&(r=Math.abs(t-s)),this._cursorOffset++,s=e.measureText(i.substr(i.length-this._cursorOffset,this._cursorOffset)).width}while(s=this._cursorOffset);Math.abs(t-s)>r&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){const s=i.substr(i.length-this._cursorOffset),r=e.measureText(s).width;let o=this._scrollLeft+this._textWidth-r;ot+n&&(this._scrollLeft+=t+n-o,o=t+n,this._markAsDirty()),this.isTextHighlightOn||e.fillRect(o,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}if(clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500),this.isTextHighlightOn){clearTimeout(this._blinkTimeout);const s=e.measureText(i.substring(this._startHighlightIndex)).width;let r=this._scrollLeft+this._textWidth-s;this._highlightedText=i.substring(this._startHighlightIndex,this._endHighlightIndex);let n=e.measureText(i.substring(this._startHighlightIndex,this._endHighlightIndex)).width;r=this._rowDefinitions.length?null:this._rowDefinitions[e]}getColumnDefinition(e){return e<0||e>=this._columnDefinitions.length?null:this._columnDefinitions[e]}addRowDefinition(e,t=!1){return this._rowDefinitions.push(new PD(e,t?PD.UNITMODE_PIXEL:PD.UNITMODE_PERCENTAGE)),this._rowDefinitionObservers.push(this._rowDefinitions[this.rowCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}addColumnDefinition(e,t=!1){return this._columnDefinitions.push(new PD(e,t?PD.UNITMODE_PIXEL:PD.UNITMODE_PERCENTAGE)),this._columnDefinitionObservers.push(this._columnDefinitions[this.columnCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}setRowDefinition(e,t,i=!1){if(e<0||e>=this._rowDefinitions.length)return this;const s=this._rowDefinitions[e];return s&&s.isPixel===i&&s.value===t||(this._rowDefinitions[e].onChangedObservable.remove(this._rowDefinitionObservers[e]),this._rowDefinitions[e]=new PD(t,i?PD.UNITMODE_PIXEL:PD.UNITMODE_PERCENTAGE),this._rowDefinitionObservers[e]=this._rowDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}setColumnDefinition(e,t,i=!1){if(e<0||e>=this._columnDefinitions.length)return this;const s=this._columnDefinitions[e];return s&&s.isPixel===i&&s.value===t||(this._columnDefinitions[e].onChangedObservable.remove(this._columnDefinitionObservers[e]),this._columnDefinitions[e]=new PD(t,i?PD.UNITMODE_PIXEL:PD.UNITMODE_PERCENTAGE),this._columnDefinitionObservers[e]=this._columnDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}getChildrenAt(e,t){const i=this._cells[`${e}:${t}`];return i?i.children:null}getChildCellInfo(e){return e._tag}_removeCell(e,t){if(e){super.removeControl(e);for(const t of e.children){const e=this._childControls.indexOf(t);-1!==e&&this._childControls.splice(e,1)}delete this._cells[t]}}_offsetCell(e,t){if(this._cells[t]){this._cells[e]=this._cells[t];for(const t of this._cells[e].children)t._tag=e;delete this._cells[t]}}removeColumnDefinition(e){if(e<0||e>=this._columnDefinitions.length)return this;for(let t=0;t=this._rowDefinitions.length)return this;for(let t=0;t{for(const r in this._cells){if(!Object.prototype.hasOwnProperty.call(this._cells,r))continue;const n=r.split(":"),o=parseInt(n[0]),a=parseInt(n[1]),l=this._cells[r];l.leftInPixels=e[a],l.topInPixels=t[o],l.widthInPixels=i[a],l.heightInPixels=s[o],l._left.ignoreAdaptiveScaling=!0,l._top.ignoreAdaptiveScaling=!0,l._width.ignoreAdaptiveScaling=!0,l._height.ignoreAdaptiveScaling=!0}})),super._additionalProcessing(e,t)}_flagDescendantsAsMatrixDirty(){for(const e in this._cells)Object.prototype.hasOwnProperty.call(this._cells,e)&&this._cells[e]._markMatrixAsDirty()}_renderHighlightSpecific(e){super._renderHighlightSpecific(e),this._getGridDefinitions(((t,i,s,r)=>{for(let i=0;i{e.tags.push(t._tag)}))}}_parseFromContent(e,t){super._parseFromContent(e,t);const i=[];this.children.forEach((e=>{i.push(e)})),this.removeRowDefinition(0),this.removeColumnDefinition(0);for(let t=0;t=1-jD._Epsilon&&(this._value.r=1),this._value.g>=1-jD._Epsilon&&(this._value.g=1),this._value.b>=1-jD._Epsilon&&(this._value.b=1),this.onValueChangedObservable.notifyObservers(this._value))}get width(){return this._width.toString(this._host)}set width(e){this._width.toString(this._host)!==e&&this._width.fromString(e)&&(0===this._width.getValue(this._host)&&(e="1px",this._width.fromString(e)),this._height.fromString(e),this._markAsDirty())}get height(){return this._height.toString(this._host)}set height(e){this._height.toString(this._host)!==e&&this._height.fromString(e)&&(0===this._height.getValue(this._host)&&(e="1px",this._height.fromString(e)),this._width.fromString(e),this._markAsDirty())}get size(){return this.width}set size(e){this.width=e}constructor(e){super(e),this.name=e,this._value=Ce.Red(),this._tmpColor=new Ce,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._squareLeft=0,this._squareTop=0,this._squareSize=0,this._h=360,this._s=1,this._v=1,this._lastPointerDownId=-1,this.onValueChangedObservable=new X,this._pointerIsDown=!1,this.value=new Ce(.88,.1,.1),this.size="200px",this.isPointerBlocker=!0}_getTypeName(){return"ColorPicker"}_preMeasure(e){e.widthl||sg?f:(f-p)*(e-m)/(g-m)+p,d=(r-h)/(e-h),o[u+3]=d<_?d/_*255:d>1-_?255*(1-(d-(1-_))/_):255}return r.putImageData(n,0,0),s}_draw(e){e.save(),this._applyStates(e);const t=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),i=.2*t,s=this._currentMeasure.left,r=this._currentMeasure.top;this._colorWheelCanvas&&this._colorWheelCanvas.width==2*t||(this._colorWheelCanvas=this._createColorWheelCanvas(t,i)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,s,r),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);let n=this._squareLeft+this._squareSize*this._s,o=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(n,o,.04*t,e);const a=t-.5*i;n=s+t+Math.cos((this._h-180)*Math.PI/180)*a,o=r+t+Math.sin((this._h-180)*Math.PI/180)*a,this._drawCircle(n,o,.35*i,e),e.restore()}_updateValueFromPointer(e,t){if(this._pointerStartedOnWheel){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),s=i+this._currentMeasure.left,r=i+this._currentMeasure.top;this._h=180*Math.atan2(t-r,e-s)/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(e-this._squareLeft)/this._squareSize,this._v=1-(t-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,jD._Epsilon),this._v=Math.min(this._v,1),this._v=Math.max(this._v,jD._Epsilon));Ce.HSVtoRGBToRef(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor}_isPointOnSquare(e,t){this._updateSquareProps();const i=this._squareLeft,s=this._squareTop,r=this._squareSize;return e>=i&&e<=i+r&&t>=s&&t<=s+r}_isPointOnWheel(e,t){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),s=i-.2*i,r=e-(i+this._currentMeasure.left),n=t-(i+this._currentMeasure.top),o=r*r+n*n;return o<=i*i&&o>=s*s}_onPointerDown(e,t,i,s,r){if(!super._onPointerDown(e,t,i,s,r))return!1;if(this.isReadOnly)return!0;this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const n=this._transformedPosition.x,o=this._transformedPosition.y;return this._isPointOnSquare(n,o)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(n,o)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(n,o),this._host._capturingControl[i]=this,this._lastPointerDownId=i,!0}_onPointerMove(e,t,i,s){if(i==this._lastPointerDownId){if(!this.isReadOnly){this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const e=this._transformedPosition.x,i=this._transformedPosition.y;this._pointerIsDown&&this._updateValueFromPointer(e,i)}super._onPointerMove(e,t,i,s)}}_onPointerUp(e,t,i,s,r,n){this._pointerIsDown=!1,delete this._host._capturingControl[i],super._onPointerUp(e,t,i,s,r,n)}_onCanvasBlur(){this._forcePointerUp(),super._onCanvasBlur()}static ShowPickerDialogAsync(e,t){return new Promise((i=>{t.pickerWidth=t.pickerWidth||"640px",t.pickerHeight=t.pickerHeight||"400px",t.headerHeight=t.headerHeight||"35px",t.lastColor=t.lastColor||"#000000",t.swatchLimit=t.swatchLimit||20,t.numSwatchesPerLine=t.numSwatchesPerLine||10;const s=t.swatchLimit/t.numSwatchesPerLine,r=parseFloat(t.pickerWidth)/t.numSwatchesPerLine,n=Math.floor(.25*r),o=n*(t.numSwatchesPerLine+1),a=Math.floor((parseFloat(t.pickerWidth)-o)/t.numSwatchesPerLine),l=a*s+n*(s+1),h=(parseInt(t.pickerHeight)+l+Math.floor(.25*a)).toString()+"px",c="#c0c0c0",u="#535353",d="#414141",_="515151",p="#555555",f="#454545",m=Ce.FromHexString("#dddddd"),g=m.r+m.g+m.b,v="#aaaaaa",x="#ffffff";let b,T;const y=["R","G","B"],S="#454545",C="#f0f0f0";let E,A,P,R,I,M=!1;const O=new QD;if(O.name="Dialog Container",O.width=t.pickerWidth,t.savedColors){O.height=h;const e=parseInt(t.pickerHeight)/parseInt(h);O.addRowDefinition(e,!1),O.addRowDefinition(1-e,!1)}else O.height=t.pickerHeight,O.addRowDefinition(1,!1);if(e.addControl(O),t.savedColors){A=new QD,A.name="Swatch Drawer",A.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,A.background=u,A.width=t.pickerWidth;const e=t.savedColors.length/t.numSwatchesPerLine;let i;i=0==e?0:e+1,A.height=(a*e+i*n).toString()+"px",A.top=Math.floor(.25*a).toString()+"px";for(let e=0;e<2*Math.ceil(t.savedColors.length/t.numSwatchesPerLine)+1;e++)e%2!=0?A.addRowDefinition(a,!0):A.addRowDefinition(n,!0);for(let e=0;e<2*t.numSwatchesPerLine+1;e++)e%2!=0?A.addColumnDefinition(a,!0):A.addColumnDefinition(n,!0);O.addControl(A,1,0)}const D=new QD;D.name="Picker Panel",D.height=t.pickerHeight;const w=parseInt(t.headerHeight)/parseInt(t.pickerHeight),N=[w,1-w];D.addRowDefinition(N[0],!1),D.addRowDefinition(N[1],!1),O.addControl(D,0,0);const F=new kD;F.name="Dialogue Header Bar",F.background="#cccccc",F.thickness=0,D.addControl(F,0,0);const B=zD.CreateSimpleButton("closeButton","a");B.fontFamily="coreglyphs";const L=Ce.FromHexString(F.background),k=new Ce(1-L.r,1-L.g,1-L.b);B.color=k.toHexString(),B.fontSize=Math.floor(.6*parseInt(t.headerHeight)),B.textBlock.textVerticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,B.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_RIGHT,B.height=B.width=t.headerHeight,B.background=F.background,B.thickness=0,B.pointerDownAnimation=()=>{},B.pointerUpAnimation=()=>{B.background=F.background},B.pointerEnterAnimation=()=>{B.color=F.background,B.background="red"},B.pointerOutAnimation=()=>{B.color=k.toHexString(),B.background=F.background},B.onPointerClickObservable.add((()=>{De(te.background)})),D.addControl(B,0,0);const V=new QD;V.name="Dialogue Body",V.background=u;const U=[.4375,.5625];V.addRowDefinition(1,!1),V.addColumnDefinition(U[0],!1),V.addColumnDefinition(U[1],!1),D.addControl(V,1,0);const G=new QD;G.name="Picker Grid",G.addRowDefinition(.85,!1),G.addRowDefinition(.15,!1),V.addControl(G,0,0);const z=new jD;z.name="GUI Color Picker",t.pickerHeight{I=z.name,R="",Re(!1)})),z.onValueChangedObservable.add((function(e){I==z.name&&Se(e,z.name)})),G.addControl(z,0,0);const W=new QD;W.name="Dialogue Right Half",W.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT;const H=[.514,.486];W.addRowDefinition(H[0],!1),W.addRowDefinition(H[1],!1),V.addControl(W,1,1);const X=new QD;X.name="Swatches and Buttons";const Y=[.417,.583];X.addRowDefinition(1,!1),X.addColumnDefinition(Y[0],!1),X.addColumnDefinition(Y[1],!1),W.addControl(X,0,0);const Q=new QD;Q.name="New and Current Swatches";const j=[.04,.16,.64,.16];Q.addRowDefinition(j[0],!1),Q.addRowDefinition(j[1],!1),Q.addRowDefinition(j[2],!1),Q.addRowDefinition(j[3],!1),X.addControl(Q,0,0);const K=new QD;K.name="Active Swatches",K.width=.67,K.addRowDefinition(.5,!1),K.addRowDefinition(.5,!1),Q.addControl(K,2,0);const $=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[0]*.11),q=Math.floor(parseInt(t.pickerHeight)*N[1]*H[0]*j[1]*.5);let Z;Z=t.pickerWidth>t.pickerHeight?q:$;const J=new UD;J.text="new",J.name="New Color Label",J.color=c,J.fontSize=Z,Q.addControl(J,1,0);const ee=new kD;ee.name="New Color Swatch",ee.background=t.lastColor,ee.thickness=0,K.addControl(ee,0,0);const te=zD.CreateSimpleButton("currentSwatch","");te.background=t.lastColor,te.thickness=0,te.onPointerClickObservable.add((()=>{Se(Ce.FromHexString(te.background),te.name),Re(!1)})),te.pointerDownAnimation=()=>{},te.pointerUpAnimation=()=>{},te.pointerEnterAnimation=()=>{},te.pointerOutAnimation=()=>{},K.addControl(te,1,0);const ie=new kD;ie.name="Swatch Outline",ie.width=.67,ie.thickness=2,ie.color="#404040",ie.isHitTestVisible=!1,Q.addControl(ie,2,0);const se=new UD;se.name="Current Color Label",se.text="current",se.color=c,se.fontSize=Z,Q.addControl(se,3,0);const re=new QD;re.name="Button Grid",re.height=.8;const ne=1/3;re.addRowDefinition(ne,!1),re.addRowDefinition(ne,!1),re.addRowDefinition(ne,!1),X.addControl(re,0,1);const oe=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[1]*.67).toString()+"px",ae=Math.floor(parseInt(t.pickerHeight)*N[1]*H[0]*(parseFloat(re.height.toString())/100)*ne*.7).toString()+"px";b=parseFloat(oe)>parseFloat(ae)?Math.floor(.45*parseFloat(ae)):Math.floor(.11*parseFloat(oe));const le=zD.CreateSimpleButton("butOK","OK");le.width=oe,le.height=ae,le.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,le.thickness=2,le.color=c,le.fontSize=b,le.background=u,le.onPointerEnterObservable.add((()=>{le.background=d})),le.onPointerOutObservable.add((()=>{le.background=u})),le.pointerDownAnimation=()=>{le.background=_},le.pointerUpAnimation=()=>{le.background=d},le.onPointerClickObservable.add((()=>{Re(!1),De(ee.background)})),re.addControl(le,0,0);const he=zD.CreateSimpleButton("butCancel","Cancel");he.width=oe,he.height=ae,he.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,he.thickness=2,he.color=c,he.fontSize=b,he.background=u,he.onPointerEnterObservable.add((()=>{he.background=d})),he.onPointerOutObservable.add((()=>{he.background=u})),he.pointerDownAnimation=()=>{he.background=_},he.pointerUpAnimation=()=>{he.background=d},he.onPointerClickObservable.add((()=>{Re(!1),De(te.background)})),re.addControl(he,1,0),t.savedColors&&(P=zD.CreateSimpleButton("butSave","Save"),P.width=oe,P.height=ae,P.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,P.thickness=2,P.fontSize=b,t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&(0==t.savedColors.length&&Me(!0),t.savedColors.length0&&Me(!0),re.addControl(P,2,0));const ce=new QD;ce.name="Dialog Lower Right",ce.addRowDefinition(.02,!1),ce.addRowDefinition(.63,!1),ce.addRowDefinition(.21,!1),ce.addRowDefinition(.14,!1),W.addControl(ce,1,0);const ue=Ce.FromHexString(t.lastColor),de=new QD;de.name="RGB Values",de.width=.82,de.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,de.addRowDefinition(1/3,!1),de.addRowDefinition(1/3,!1),de.addRowDefinition(1/3,!1),de.addColumnDefinition(.1,!1),de.addColumnDefinition(.2,!1),de.addColumnDefinition(.7,!1),ce.addControl(de,1,0);for(let e=0;e{I=_e.name,R=_e.text,Re(!1)})),_e.onBlurObservable.add((()=>{""==_e.text&&(_e.text="0"),Ee(_e,"r"),I==_e.name&&(I="")})),_e.onTextChangedObservable.add((()=>{I==_e.name&&Ee(_e,"r")})),de.addControl(_e,0,1);const pe=new YD;pe.width=.83,pe.height=.72,pe.name="gIntField",pe.fontSize=b,pe.text=(255*ue.g).toString(),pe.color=C,pe.background=S,pe.onFocusObservable.add((()=>{I=pe.name,R=pe.text,Re(!1)})),pe.onBlurObservable.add((()=>{""==pe.text&&(pe.text="0"),Ee(pe,"g"),I==pe.name&&(I="")})),pe.onTextChangedObservable.add((()=>{I==pe.name&&Ee(pe,"g")})),de.addControl(pe,1,1);const fe=new YD;fe.width=.83,fe.height=.72,fe.name="bIntField",fe.fontSize=b,fe.text=(255*ue.b).toString(),fe.color=C,fe.background=S,fe.onFocusObservable.add((()=>{I=fe.name,R=fe.text,Re(!1)})),fe.onBlurObservable.add((()=>{""==fe.text&&(fe.text="0"),Ee(fe,"b"),I==fe.name&&(I="")})),fe.onTextChangedObservable.add((()=>{I==fe.name&&Ee(fe,"b")})),de.addControl(fe,2,1);const me=new YD;me.width=.95,me.height=.72,me.name="rDecField",me.fontSize=b,me.text=ue.r.toString(),me.color=C,me.background=S,me.onFocusObservable.add((()=>{I=me.name,R=me.text,Re(!1)})),me.onBlurObservable.add((()=>{0!=parseFloat(me.text)&&""!=me.text||(me.text="0",Ae(me,"r")),I==me.name&&(I="")})),me.onTextChangedObservable.add((()=>{I==me.name&&Ae(me,"r")})),de.addControl(me,0,2);const ge=new YD;ge.width=.95,ge.height=.72,ge.name="gDecField",ge.fontSize=b,ge.text=ue.g.toString(),ge.color=C,ge.background=S,ge.onFocusObservable.add((()=>{I=ge.name,R=ge.text,Re(!1)})),ge.onBlurObservable.add((()=>{0!=parseFloat(ge.text)&&""!=ge.text||(ge.text="0",Ae(ge,"g")),I==ge.name&&(I="")})),ge.onTextChangedObservable.add((()=>{I==ge.name&&Ae(ge,"g")})),de.addControl(ge,1,2);const ve=new YD;ve.width=.95,ve.height=.72,ve.name="bDecField",ve.fontSize=b,ve.text=ue.b.toString(),ve.color=C,ve.background=S,ve.onFocusObservable.add((()=>{I=ve.name,R=ve.text,Re(!1)})),ve.onBlurObservable.add((()=>{0!=parseFloat(ve.text)&&""!=ve.text||(ve.text="0",Ae(ve,"b")),I==ve.name&&(I="")})),ve.onTextChangedObservable.add((()=>{I==ve.name&&Ae(ve,"b")})),de.addControl(ve,2,2);const xe=new QD;xe.name="Hex Value",xe.width=.82,xe.addRowDefinition(1,!1),xe.addColumnDefinition(.1,!1),xe.addColumnDefinition(.9,!1),ce.addControl(xe,2,0);const be=new UD;be.text="#",be.color=c,be.fontSize=b,xe.addControl(be,0,0);const Te=new YD;Te.width=.96,Te.height=.72,Te.name="hexField",Te.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,Te.fontSize=b;const ye=t.lastColor.split("#");function Se(e,t){I=t;const i=e.toHexString();if(ee.background=i,_e.name!=I&&(_e.text=Math.floor(255*e.r).toString()),pe.name!=I&&(pe.text=Math.floor(255*e.g).toString()),fe.name!=I&&(fe.text=Math.floor(255*e.b).toString()),me.name!=I&&(me.text=e.r.toString()),ge.name!=I&&(ge.text=e.g.toString()),ve.name!=I&&(ve.text=e.b.toString()),Te.name!=I){const e=i.split("#");Te.text=e[1]}z.name!=I&&(z.value=e)}function Ee(e,t){let i=e.text;if(/[^0-9]/g.test(i))e.text=R;else if(""!=i&&(Math.floor(parseInt(i))<0?i="0":Math.floor(parseInt(i))>255?i="255":isNaN(parseInt(i))&&(i="0")),I==e.name&&(R=i),""!=i){i=parseInt(i).toString(),e.text=i;const s=Ce.FromHexString(ee.background);I==e.name&&Se("r"==t?new Ce(parseInt(i)/255,s.g,s.b):"g"==t?new Ce(s.r,parseInt(i)/255,s.b):new Ce(s.r,s.g,parseInt(i)/255),e.name)}}function Ae(e,t){let i=e.text;if(/[^0-9.]/g.test(i))return void(e.text=R);""!=i&&"."!=i&&0!=parseFloat(i)&&(parseFloat(i)<0?i="0.0":parseFloat(i)>1?i="1.0":isNaN(parseFloat(i))&&(i="0.0")),I==e.name&&(R=i),""!=i&&"."!=i&&0!=parseFloat(i)?(i=parseFloat(i).toString(),e.text=i):i="0.0";const s=Ce.FromHexString(ee.background);I==e.name&&Se("r"==t?new Ce(parseFloat(i),s.g,s.b):"g"==t?new Ce(s.r,parseFloat(i),s.b):new Ce(s.r,s.g,parseFloat(i)),e.name)}function Pe(){if(t.savedColors&&t.savedColors[E]){let e;e=M?"b":"";const i=zD.CreateSimpleButton("Swatch_"+E,e);i.fontFamily="coreglyphs";const s=Ce.FromHexString(t.savedColors[E]),r=s.r+s.g+s.b;i.color=r>g?v:x,i.fontSize=Math.floor(.7*a),i.textBlock.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,i.height=i.width=a.toString()+"px",i.background=t.savedColors[E],i.thickness=2;const n=E;return i.pointerDownAnimation=()=>{i.thickness=4},i.pointerUpAnimation=()=>{i.thickness=3},i.pointerEnterAnimation=()=>{i.thickness=3},i.pointerOutAnimation=()=>{i.thickness=2},i.onPointerClickObservable.add((()=>{var e;M?(e=n,t.savedColors&&t.savedColors.splice(e,1),t.savedColors&&0==t.savedColors.length&&(Me(!1),M=!1),Ie("",P)):t.savedColors&&Se(Ce.FromHexString(t.savedColors[n]),i.name)})),i}return null}function Re(e){let t;if(void 0!==e&&(M=e),M){for(let e=0;ei*t.numSwatchesPerLine?t.numSwatchesPerLine:t.savedColors.length-(i-1)*t.numSwatchesPerLine;const r=Math.min(Math.max(s,0),t.numSwatchesPerLine);for(let i=0,s=1;it.numSwatchesPerLine)continue;const r=Pe();null!=r&&(A.addControl(r,e,s),s+=2,E++)}}t.savedColors.length>=t.swatchLimit?Oe(i,!0):Oe(i,!1)}}function Me(e){e?(T=zD.CreateSimpleButton("butEdit","Edit"),T.width=oe,T.height=ae,T.left=Math.floor(.1*parseInt(oe)).toString()+"px",T.top=(-1*parseFloat(T.left)).toString()+"px",T.verticalAlignment=BD.VERTICAL_ALIGNMENT_BOTTOM,T.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,T.thickness=2,T.color=c,T.fontSize=b,T.background=u,T.onPointerEnterObservable.add((()=>{T.background=d})),T.onPointerOutObservable.add((()=>{T.background=u})),T.pointerDownAnimation=()=>{T.background=_},T.pointerUpAnimation=()=>{T.background=d},T.onPointerClickObservable.add((()=>{M=!M,Re()})),G.addControl(T,1,0)):G.removeControl(T)}function Oe(e,t){t?(e.color=p,e.background=f):(e.color=c,e.background=u)}function De(s){t.savedColors&&t.savedColors.length>0?i({savedColors:t.savedColors,pickedColor:s}):i({pickedColor:s}),e.removeControl(O)}Te.text=ye[1],Te.color=C,Te.background=S,Te.onFocusObservable.add((()=>{I=Te.name,R=Te.text,Re(!1)})),Te.onBlurObservable.add((()=>{if(3==Te.text.length){const e=Te.text.split("");Te.text=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]}""==Te.text&&(Te.text="000000",Se(Ce.FromHexString(Te.text),"b")),I==Te.name&&(I="")})),Te.onTextChangedObservable.add((()=>{let e=Te.text;const t=/[^0-9A-F]/i.test(e);if((Te.text.length>6||t)&&I==Te.name)Te.text=R;else{if(Te.text.length<6){const t=6-Te.text.length;for(let i=0;i0&&Ie("",P)}))}}jD._Epsilon=1e-6,qe([st()],jD.prototype,"value",null),qe([st()],jD.prototype,"width",null),qe([st()],jD.prototype,"height",null),qe([st()],jD.prototype,"size",null),ee("BABYLON.GUI.ColorPicker",jD);class KD extends LD{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thickness=1}_getTypeName(){return"Ellipse"}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),(this._backgroundGradient||this._background)&&(e.fillStyle=this._getBackgroundColor(e),e.fill()),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.stroke()),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_clipForChildren(e){BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2,this._currentMeasure.height/2,e),e.clip()}_renderHighlightSpecific(e){BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._highlightLineWidth/2,this._currentMeasure.height/2-this._highlightLineWidth/2,e),e.stroke()}}qe([st()],KD.prototype,"thickness",null),ee("BABYLON.GUI.Ellipse",KD);class $D extends zD{constructor(e){super(e),this.name=e,this.focusedColor=null,this._isFocused=!1,this._unfocusedColor=null,this.onFocusObservable=new X,this.onBlurObservable=new X,this.onKeyboardEventProcessedObservable=new X,this._unfocusedColor=this.color}onBlur(){this._isFocused&&(this._isFocused=!1,this.focusedColor&&null!=this._unfocusedColor&&(this.color=this._unfocusedColor),this.onBlurObservable.notifyObservers(this))}onFocus(){this._isFocused=!0,this.focusedColor&&(this._unfocusedColor=this.color,this.color=this.focusedColor),this.onFocusObservable.notifyObservers(this)}keepsFocusWith(){return null}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}processKeyboard(e){this.onKeyboardEventProcessedObservable.notifyObservers(e,-1,this)}_onPointerDown(e,t,i,s,r){return this.isReadOnly||this.focus(),super._onPointerDown(e,t,i,s,r)}dispose(){super.dispose(),this.onBlurObservable.clear(),this.onFocusObservable.clear(),this.onKeyboardEventProcessedObservable.clear()}}ee("BABYLON.GUI.FocusableButton",$D);class qD extends YD{get autoStretchHeight(){return this._autoStretchHeight}set autoStretchHeight(e){this._autoStretchHeight!==e&&(this._autoStretchHeight=e,this._markAsDirty())}set height(e){this.fixedRatioMasterIsWidth=!1,this._height.toString(this._host)!==e&&(this._height.fromString(e)&&this._markAsDirty(),this._autoStretchHeight=!1)}get maxHeight(){return this._maxHeight.toString(this._host)}get maxHeightInPixels(){return this._maxHeight.getValueInPixel(this._host,this._cachedParentMeasure.height)}set maxHeight(e){this._maxHeight.toString(this._host)!==e&&this._maxHeight.fromString(e)&&this._markAsDirty()}constructor(e,t=""){super(e),this.name=e,this._textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._textVerticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._prevText=this.text,this._lineSpacing=new PD(0),this._maxHeight=new PD(1,PD.UNITMODE_PERCENTAGE,!1),this.onLinesReadyObservable=new X,this.text=t,this.isPointerBlocker=!0,this.onLinesReadyObservable.add((()=>this._updateCursorPosition())),this._highlightCursorInfo={initialStartIndex:-1,initialRelativeStartIndex:-1,initialLineIndex:-1},this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeEndIndex:0,relativeStartIndex:0,currentLineIndex:0}}_getTypeName(){return"InputTextArea"}processKeyboard(e){this.isReadOnly||(this.alternativeProcessKey(e.code,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e))}alternativeProcessKey(e,t,i){if(!i||!i.ctrlKey&&!i.metaKey||"KeyC"!==e&&"KeyV"!==e&&"KeyX"!==e){switch(e){case"KeyA":if(i&&(i.ctrlKey||i.metaKey))return this._selectAllText(),void i.preventDefault();break;case"Period":i&&i.shiftKey&&i.preventDefault();break;case"Backspace":!this._isTextHighlightOn&&this._cursorInfo.globalStartIndex>0&&(this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--),this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,i&&i.preventDefault(),this._blinkIsEven=!1,this._isTextHighlightOn=!1,this._textHasChanged();break;case"Delete":!this._isTextHighlightOn&&this._cursorInfo.globalEndIndexthis._highlightCursorInfo.initialStartIndex?this._cursorInfo.globalEndIndex--:this._cursorInfo.globalStartIndex--:(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--,this._isTextHighlightOn=!0),this._blinkIsEven=!0,void i.preventDefault()):(this._isTextHighlightOn?this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex:i&&(i.ctrlKey||i.metaKey)?(this._cursorInfo.globalStartIndex-=this._cursorInfo.relativeStartIndex,i.preventDefault()):this._cursorInfo.globalStartIndex>0&&this._cursorInfo.globalStartIndex--,this._blinkIsEven=!1,void(this._isTextHighlightOn=!1));case"ArrowRight":if(this._markAsDirty(),i&&i.shiftKey){if(i.ctrlKey||i.metaKey){const e=this._lines[this._cursorInfo.currentLineIndex].text.length-this._cursorInfo.relativeEndIndex-1;this._cursorInfo.globalEndIndex+=e,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex}return this._isTextHighlightOn?this._cursorInfo.globalStartIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndex<=this._highlightCursorInfo.initialLineIndex?(this._cursorInfo.globalStartIndex=i,this._cursorInfo.globalEndIndex=this._highlightCursorInfo.initialStartIndex,this._cursorInfo.relativeEndIndex=this._highlightCursorInfo.initialRelativeStartIndex):this._cursorInfo.globalEndIndex=i:this._cursorInfo.globalStartIndex=i}return void this._markAsDirty();case"ArrowDown":if(this._blinkIsEven=!1,i&&(i.shiftKey?(this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex),this._isTextHighlightOn=!0,this._blinkIsEven=!0):this._isTextHighlightOn=!1,i.preventDefault()),this._cursorInfo.currentLineIndex===this._lines.length-1)this._cursorInfo.globalStartIndex=this.text.length;else{const e=this._lines[this._cursorInfo.currentLineIndex],t=this._lines[this._cursorInfo.currentLineIndex+1];let i=0,s=0;!this._isTextHighlightOn||this._cursorInfo.currentLineIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndexthis._cursorInfo.globalEndIndex&&(this._cursorInfo.globalEndIndex+=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex=this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex-=this._cursorInfo.globalStartIndex)):(this._cursorInfo.globalEndIndex=i,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex):this._cursorInfo.globalStartIndex=i}return void this._markAsDirty()}1===t?.length&&(i?.preventDefault(),this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&(this._isTextHighlightOn=!1,this._blinkIsEven=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t),this._cursorInfo.globalStartIndex+=t.length,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()))}}_parseLineWordWrap(e="",t,i){const s=[],r=e.split(" ");let n=0;for(let o=0;o0?e+" "+r[o]:r[0],l=i.measureText(a).width;if(l>t){o>0&&(n=i.measureText(e).width,s.push({text:e,width:n,lineEnding:" "})),e=r[o];let a="";e.split("").map((e=>{i.measureText(a+e).width>t&&(s.push({text:a,width:i.measureText(a).width,lineEnding:""}),a=""),a+=e})),e=a,n=i.measureText(e).width}else n=l,e=a}return s.push({text:e,width:n,lineEnding:" "}),s}_breakLines(e,t){const i=[],s=(this.text||this.placeholderText).split("\n");if(this.clipContent)for(const r of s)i.push(...this._parseLineWordWrap(r,e,t));else for(const e of s)i.push(this._parseLine(e,t));return i[i.length-1].lineEnding="\n",i}_parseLine(e="",t){return{text:e,width:t.measureText(e).width,lineEnding:" "}}_preMeasure(e,t){this._fontOffset&&!this._wasDirty||(this._fontOffset=BD._GetFontOffset(t.font));let i=this._beforeRenderText(this._textWrapper).text;!this.text&&this._placeholderText&&(i=this._placeholderText),this._textWidth=t.measureText(i).width;const s=2*this._margin.getValueInPixel(this._host,e.width);if(this._autoStretchWidth){const r=i.split("\n").reduce(((e,i)=>t.measureText(i).width>t.measureText(e).width?i:e),""),n=t.measureText(r).width;this.width=Math.min(this._maxWidth.getValueInPixel(this._host,e.width),n+s)+"px",this.autoStretchWidth=!0}if(this._availableWidth=this._width.getValueInPixel(this._host,e.width)-s,this._lines=this._breakLines(this._availableWidth,t),this._contextForBreakLines=t,this._autoStretchHeight){const t=this._lines.length*this._fontOffset.height+2*this._margin.getValueInPixel(this._host,e.height);this.height=Math.min(this._maxHeight.getValueInPixel(this._host,e.height),t)+"px",this._autoStretchHeight=!0}if(this._availableHeight=this._height.getValueInPixel(this._host,e.height)-s,this._isFocused){this._cursorInfo.currentLineIndex=0;let e=this._lines[this._cursorInfo.currentLineIndex].text.length+this._lines[this._cursorInfo.currentLineIndex].lineEnding.length,t=0;for(;t+e<=this._cursorInfo.globalStartIndex;)t+=e,this._cursorInfo.currentLineIndexthis._availableWidth){const e=this._clipTextLeft-this._lines[this._cursorInfo.currentLineIndex].width+this._availableWidth;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=this._clipTextLeft;if(this._isFocused&&!this._autoStretchHeight){const e=(this._cursorInfo.currentLineIndex+1)*this._fontOffset.height,t=this._clipTextTop-e;this._scrollTop||(this._scrollTop=t)}else this._scrollTop=this._clipTextTop}_additionalProcessing(){this.highlightedText="",this.onLinesReadyObservable.notifyObservers(this)}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=this._scrollLeft;switch(this._textHorizontalAlignment){case BD.HORIZONTAL_ALIGNMENT_LEFT:n+=0;break;case BD.HORIZONTAL_ALIGNMENT_RIGHT:n+=r-t;break;case BD.HORIZONTAL_ALIGNMENT_CENTER:n+=(r-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,n,i)}_onCopyText(e){this._isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._textHasChanged()}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData,this._isTextHighlightOn=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t);const i=t.length-(this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex);this._cursorInfo.globalStartIndex+=i,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()}_draw(e){this._computeScroll(),this._scrollLeft=this._scrollLeft??0,this._scrollTop=this._scrollTop??0,e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this.color&&(e.fillStyle=this.color);const t=this._currentMeasure.height,i=this._currentMeasure.width;let s=0;switch(this._textVerticalAlignment){case BD.VERTICAL_ALIGNMENT_TOP:s=this._fontOffset.ascent;break;case BD.VERTICAL_ALIGNMENT_BOTTOM:s=t-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case BD.VERTICAL_ALIGNMENT_CENTER:s=this._fontOffset.ascent+(t-this._fontOffset.height*this._lines.length)/2}e.save(),e.beginPath(),e.fillStyle=this.fontStyle,!this._textWrapper.text&&this.placeholderText&&(e.fillStyle=this._placeholderColor),e.rect(this._clipTextLeft,this._clipTextTop,this._availableWidth+2,this._availableHeight+2),e.clip(),s+=this._scrollTop;for(let t=0;tthis._clipTextLeft+this._availableWidth&&(this._scrollLeft+=this._clipTextLeft+this._availableWidth-t,t=this._clipTextLeft+this._availableWidth,this._markAsDirty());let i=this._scrollTop+this._cursorInfo.currentLineIndex*this._fontOffset.height;ithis._clipTextTop+this._availableHeight&&(this._scrollTop+=this._clipTextTop+this._availableHeight-i-this._fontOffset.height,i=this._clipTextTop+this._availableHeight-this._fontOffset.height,this._markAsDirty()),this._isTextHighlightOn||e.fillRect(t,i,2,this._fontOffset.height)}if(this._resetBlinking(),this._isTextHighlightOn){clearTimeout(this._blinkTimeout),this._highlightedText=this.text.substring(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),e.globalAlpha=this._highligherOpacity,e.fillStyle=this._textHighlightColor;const t=Math.min(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex),s=Math.max(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex);let r=this._scrollTop+t*this._fontOffset.height;for(let n=t;n<=s;n++){const o=this._lines[n];let a=this._scrollLeft;switch(this._textHorizontalAlignment){case BD.HORIZONTAL_ALIGNMENT_LEFT:a+=0;break;case BD.HORIZONTAL_ALIGNMENT_RIGHT:a+=i-o.width;break;case BD.HORIZONTAL_ALIGNMENT_CENTER:a+=(i-o.width)/2}const l=n===t?this._cursorInfo.relativeStartIndex:0,h=n===s?this._cursorInfo.relativeEndIndex:o.text.length,c=e.measureText(o.text.substr(0,l)).width,u=o.text.substring(l,h),d=e.measureText(u).width;e.fillRect(a+c,r,d,this._fontOffset.height),r+=this._fontOffset.height}this._cursorInfo.globalEndIndex===this._cursorInfo.globalStartIndex&&this._resetBlinking()}}e.restore(),this._thickness&&(this._isFocused?this.focusedColor&&(e.strokeStyle=this.focusedColor):this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}_resetBlinking(){clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500)}_onPointerDown(e,t,i,s,r){return!(!super._onPointerDown(e,t,i,s,r)||!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn=!1,this._highlightedText="",this._isPointerDown=!0,this._host._capturingControl[i]=this,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),0):!this._isEnabled||(this._host.focusedControl=this,0)))}_onPointerMove(e,t,i,s){0===s.event.movementX&&0===s.event.movementY||(this._host.focusedControl===this&&this._isPointerDown&&!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._isTextHighlightOn=!0),this._markAsDirty()),super._onPointerMove(e,t,i,s))}_updateCursorPosition(){if(this._isFocused)if(!this._textWrapper.text&&this.placeholderText)this._cursorInfo.currentLineIndex=0,this._cursorInfo.globalStartIndex=0,this._cursorInfo.globalEndIndex=0,this._cursorInfo.relativeStartIndex=0,this._cursorInfo.relativeEndIndex=0;else if(this._clickedCoordinateX&&this._clickedCoordinateY){this._isTextHighlightOn||(this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeStartIndex:0,relativeEndIndex:0,currentLineIndex:0});let e=0,t=0;const i=this._clickedCoordinateY-this._scrollTop,s=Math.floor(i/this._fontOffset.height);this._cursorInfo.currentLineIndex=Math.min(Math.max(s,0),this._lines.length-1);let r=0;const n=this._clickedCoordinateX-(this._scrollLeft??0);let o=0;for(let t=0;tt;)t++,o=Math.abs(n-r),r=this._contextForBreakLines.measureText(this._lines[this._cursorInfo.currentLineIndex].text.substr(0,t)).width;Math.abs(n-r)>o&&t>0&&t--,e+=t,this._isTextHighlightOn?e=this._highlightCursorInfo.initialStartIndex){for(;t+e<=this._cursorInfo.globalEndIndex;)t+=e,this._cursorInfo.currentLineIndex0&&this._textWrapper.isWord(this._cursorInfo.globalStartIndex-1)?--this._cursorInfo.globalStartIndex:0,i=this._cursorInfo.globalEndIndexthis._markAsDirty()))),this._connectedControl=e,this._markAsDirty())}get x1(){return this._x1.toString(this._host)}set x1(e){this._x1.toString(this._host)!==e&&this._x1.fromString(e)&&this._markAsDirty()}get y1(){return this._y1.toString(this._host)}set y1(e){this._y1.toString(this._host)!==e&&this._y1.fromString(e)&&this._markAsDirty()}get x2(){return this._x2.toString(this._host)}set x2(e){this._x2.toString(this._host)!==e&&this._x2.fromString(e)&&this._markAsDirty()}get y2(){return this._y2.toString(this._host)}set y2(e){this._y2.toString(this._host)!==e&&this._y2.fromString(e)&&this._markAsDirty()}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}get _effectiveX2(){return(this._connectedControl?this._connectedControl.centerX:0)+this._x2.getValue(this._host)}get _effectiveY2(){return(this._connectedControl?this._connectedControl.centerY:0)+this._y2.getValue(this._host)}constructor(e){super(e),this.name=e,this._lineWidth=1,this._x1=new PD(0),this._y1=new PD(0),this._x2=new PD(0),this._y2=new PD(0),this._dash=new Array,this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP}_getTypeName(){return"Line"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this._getColor(e),e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath(),e.moveTo(this._cachedParentMeasure.left+this._x1.getValue(this._host),this._cachedParentMeasure.top+this._y1.getValue(this._host)),e.lineTo(this._cachedParentMeasure.left+this._effectiveX2,this._cachedParentMeasure.top+this._effectiveY2),e.stroke(),e.restore()}_measure(){this._currentMeasure.width=Math.abs(this._x1.getValue(this._host)-this._effectiveX2)+this._lineWidth,this._currentMeasure.height=Math.abs(this._y1.getValue(this._host)-this._effectiveY2)+this._lineWidth}_computeAlignment(e){this._currentMeasure.left=e.left+Math.min(this._x1.getValue(this._host),this._effectiveX2)-this._lineWidth/2,this._currentMeasure.top=e.top+Math.min(this._y1.getValue(this._host),this._effectiveY2)-this._lineWidth/2}moveToVector3(e,t,i=!1){if(!this._host||this.parent!==this._host._rootContainer)return void hs.Error("Cannot move a control to a vector3 if the control is not at root level");const s=this._host._getGlobalViewport(),r=de.Project(e,fe.IdentityReadOnly,t.getTransformMatrix(),s);this._moveToProjectedPosition(r,i),r.z<0||r.z>1?this.notRenderable=!0:this.notRenderable=!1}_moveToProjectedPosition(e,t=!1){const i=e.x+this._linkOffsetX.getValue(this._host)+"px",s=e.y+this._linkOffsetY.getValue(this._host)+"px";t?(this.x2=i,this.y2=s,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=s,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)}}qe([st()],JD.prototype,"dash",null),qe([st()],JD.prototype,"x1",null),qe([st()],JD.prototype,"y1",null),qe([st()],JD.prototype,"x2",null),qe([st()],JD.prototype,"y2",null),qe([st()],JD.prototype,"lineWidth",null),ee("BABYLON.GUI.Line",JD);class ew{constructor(e){this._multiLine=e,this._x=new PD(0),this._y=new PD(0),this._point=new de(0,0,0)}get x(){return this._x.toString(this._multiLine._host)}set x(e){this._x.toString(this._multiLine._host)!==e&&this._x.fromString(e)&&this._multiLine._markAsDirty()}get y(){return this._y.toString(this._multiLine._host)}set y(e){this._y.toString(this._multiLine._host)!==e&&this._y.fromString(e)&&this._multiLine._markAsDirty()}get control(){return this._control}set control(e){this._control!==e&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=e,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=e,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}resetLinks(){this.control=null,this.mesh=null}translate(){return this._point=this._translatePoint(),this._point}_translatePoint(){if(null!=this._mesh)return this._multiLine._host.getProjectedPositionWithZ(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(null!=this._control)return new de(this._control.centerX,this._control.centerY,1-K);{const e=this._multiLine._host,t=this._x.getValueInPixel(e,Number(e._canvas.width)),i=this._y.getValueInPixel(e,Number(e._canvas.height));return new de(t,i,1-K)}}dispose(){this.resetLinks()}}class tw extends BD{constructor(e){super(e),this.name=e,this._lineWidth=1,this.onPointUpdate=()=>{this._markAsDirty()},this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._dash=[],this._points=[]}get dash(){return this._dash}set dash(e){this._dash!==e&&(this._dash=e,this._markAsDirty())}getAt(e){return this._points[e]||(this._points[e]=new ew(this)),this._points[e]}add(...e){return e.map((e=>this.push(e)))}push(e){const t=this.getAt(this._points.length);return null==e||(e instanceof Sn?t.mesh=e:e instanceof BD?t.control=e:null!=e.x&&null!=e.y&&(t.x=e.x,t.y=e.y)),t}remove(e){let t;if(e instanceof ew){if(t=this._points.indexOf(e),-1===t)return}else t=e;const i=this._points[t];i&&(i.dispose(),this._points.splice(t,1))}reset(){for(;this._points.length>0;)this.remove(this._points.length-1)}resetLinks(){this._points.forEach((e=>{null!=e&&e.resetLinks()}))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}_getTypeName(){return"MultiLine"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this.color,e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath();let t,i=!0;this._points.forEach((s=>{s&&(i?(e.moveTo(s._point.x,s._point.y),i=!1):s._point.z<1&&t.z<1?e.lineTo(s._point.x,s._point.y):e.moveTo(s._point.x,s._point.y),t=s._point)})),e.stroke(),e.restore()}_additionalProcessing(){this._minX=null,this._minY=null,this._maxX=null,this._maxY=null,this._points.forEach((e=>{e&&(e.translate(),(null==this._minX||e._point.xthis._maxX)&&(this._maxX=e._point.x),(null==this._maxY||e._point.y>this._maxY)&&(this._maxY=e._point.y))})),null==this._minX&&(this._minX=0),null==this._minY&&(this._minY=0),null==this._maxX&&(this._maxX=0),null==this._maxY&&(this._maxY=0)}_measure(){null!=this._minX&&null!=this._maxX&&null!=this._minY&&null!=this._maxY&&(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)}_computeAlignment(){null!=this._minX&&null!=this._minY&&(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)}dispose(){this.reset(),super.dispose()}}qe([st()],tw.prototype,"dash",null),ee("BABYLON.GUI.MultiLine",tw);class iw extends BD{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get checkSizeRatio(){return this._checkSizeRatio}set checkSizeRatio(e){e=Math.max(Math.min(1,e),0),this._checkSizeRatio!==e&&(this._checkSizeRatio=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get isChecked(){return this._isChecked}set isChecked(e){this._isChecked!==e&&(this._isChecked=e,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(e),this._isChecked&&this._host&&this._host.executeOnAllControls((e=>{if(e===this)return;if(void 0===e.group)return;const t=e;t.group===this.group&&(t.isChecked=!1)})))}constructor(e){super(e),this.name=e,this._isChecked=!1,this._background="black",this._checkSizeRatio=.8,this._thickness=1,this.group="",this.onIsCheckedChangedObservable=new X,this.isPointerBlocker=!0}_getTypeName(){return"RadioButton"}_draw(e){e.save(),this._applyStates(e);const t=this._currentMeasure.width-this._thickness,i=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this._isEnabled?this.color:this._disabledColor;const s=t*this._checkSizeRatio,r=i*this._checkSizeRatio;BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,s/2-this._thickness/2,r/2-this._thickness/2,e),e.fill()}e.restore()}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(this.isReadOnly||this.isChecked||(this.isChecked=!0),!0)}static AddRadioButtonWithHeader(e,t,i,s){const r=new WD;r.isVertical=!1,r.height="30px";const n=new iw;n.width="20px",n.height="20px",n.isChecked=i,n.color="green",n.group=t,n.onIsCheckedChangedObservable.add((e=>s(n,e))),r.addControl(n);const o=new UD;return o.text=e,o.width="180px",o.paddingLeft="5px",o.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,o.color="white",r.addControl(o),r}}qe([st()],iw.prototype,"thickness",null),qe([st()],iw.prototype,"group",void 0),qe([st()],iw.prototype,"checkSizeRatio",null),qe([st()],iw.prototype,"background",null),qe([st()],iw.prototype,"isChecked",null),ee("BABYLON.GUI.RadioButton",iw);class sw extends BD{get displayThumb(){return this._displayThumb}set displayThumb(e){this._displayThumb!==e&&(this._displayThumb=e,this._markAsDirty())}get step(){return this._step}set step(e){this._step!==e&&(this._step=e,this._markAsDirty())}get barOffset(){return this._barOffset.toString(this._host)}get barOffsetInPixels(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)}set barOffset(e){this._barOffset.toString(this._host)!==e&&this._barOffset.fromString(e)&&this._markAsDirty()}get thumbWidth(){return this._thumbWidth.toString(this._host)}get thumbWidthInPixels(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)}set thumbWidth(e){this._thumbWidth.toString(this._host)!==e&&this._thumbWidth.fromString(e)&&this._markAsDirty()}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get value(){return this._value}set value(e){e=Math.max(Math.min(e,this._maximum),this._minimum),this._value!==e&&(this._value=e,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))}get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get isThumbClamped(){return this._isThumbClamped}set isThumbClamped(e){this._isThumbClamped!==e&&(this._isThumbClamped=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbWidth=new PD(20,PD.UNITMODE_PIXEL,!1),this._minimum=0,this._maximum=100,this._value=50,this._isVertical=!1,this._barOffset=new PD(5,PD.UNITMODE_PIXEL,!1),this._isThumbClamped=!1,this._displayThumb=!0,this._step=0,this._lastPointerDownId=-1,this._effectiveBarOffset=0,this.onValueChangedObservable=new X,this._pointerIsDown=!1,this.isPointerBlocker=!0}_getTypeName(){return"BaseSlider"}_getThumbPosition(){return this.isVertical?(this.maximum-this.value)/(this.maximum-this.minimum)*this._backgroundBoxLength:(this.value-this.minimum)/(this.maximum-this.minimum)*this._backgroundBoxLength}_getThumbThickness(e){let t=0;switch(e){case"circle":t=this._thumbWidth.isPixel?Math.max(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host);break;case"rectangle":t=this._thumbWidth.isPixel?Math.min(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host)}return t}_prepareRenderingData(e){this._effectiveBarOffset=0,this._renderLeft=this._currentMeasure.left,this._renderTop=this._currentMeasure.top,this._renderWidth=this._currentMeasure.width,this._renderHeight=this._currentMeasure.height,this._backgroundBoxLength=Math.max(this._currentMeasure.width,this._currentMeasure.height),this._backgroundBoxThickness=Math.min(this._currentMeasure.width,this._currentMeasure.height),this._effectiveThumbThickness=this._getThumbThickness(e),this.displayThumb&&(this._backgroundBoxLength-=this._effectiveThumbThickness),this.isVertical&&this._currentMeasure.height=this._selectors.length))return this._selectors[e]}removeSelector(e){e<0||e>=this._selectors.length||(this._groupPanel.removeControl(this._selectors[e]),this._selectors.splice(e,1))}}class ow extends nw{addCheckbox(e,t=(e=>{}),i=!1){i=i||!1;const s=new HD;s.width="20px",s.height="20px",s.color="#364249",s.background="#CCCCCC",s.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,s.onIsCheckedChangedObservable.add((function(e){t(e)}));const r=BD.AddHeader(s,e,"200px",{isHorizontal:!0,controlFirst:!0});r.height="30px",r.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,r.left="4px",this.groupPanel.addControl(r),this.selectors.push(r),s.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(s.color=this.groupPanel.parent.parent.buttonColor,s.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class aw extends nw{constructor(){super(...arguments),this._selectNb=0}addRadio(e,t=(e=>{}),i=!1){const s=this._selectNb++,r=new iw;r.name=e,r.width="20px",r.height="20px",r.color="#364249",r.background="#CCCCCC",r.group=this.name,r.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,r.onIsCheckedChangedObservable.add((function(e){e&&t(s)}));const n=BD.AddHeader(r,e,"200px",{isHorizontal:!0,controlFirst:!0});n.height="30px",n.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,n.left="4px",this.groupPanel.addControl(n),this.selectors.push(n),r.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(r.color=this.groupPanel.parent.parent.buttonColor,r.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class lw extends nw{addSlider(e,t=(e=>{}),i="Units",s=0,r=0,n=0,o=(e=>0|e)){const a=new rw;a.name=i,a.value=n,a.minimum=s,a.maximum=r,a.width=.9,a.height="20px",a.color="#364249",a.background="#CCCCCC",a.borderColor="black",a.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,a.left="4px",a.paddingBottom="4px",a.onValueChangedObservable.add((function(e){a.parent.children[0].text=a.parent.children[0].name+": "+o(e)+" "+a.name,t(e)}));const l=BD.AddHeader(a,e+": "+o(n)+" "+i,"30px",{isHorizontal:!1,controlFirst:!1});l.height="60px",l.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,l.left="4px",l.children[0].name=e,this.groupPanel.addControl(l),this.selectors.push(l),this.groupPanel.parent&&this.groupPanel.parent.parent&&(a.color=this.groupPanel.parent.parent.buttonColor,a.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[0].name=t,this.selectors[e].children[0].text=t+": "+this.selectors[e].children[1].value+" "+this.selectors[e].children[1].name}_setSelectorLabelColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[1].background=t}}class hw extends kD{constructor(e,t=[]){if(super(e),this.name=e,this.groups=t,this._buttonColor="#364249",this._buttonBackground="#CCCCCC",this._headerColor="black",this._barColor="white",this._barHeight="2px",this._spacerHeight="20px",this._bars=new Array,this._groups=t,this.thickness=2,this._panel=new WD,this._panel.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._panel.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._panel.top=5,this._panel.left=5,this._panel.width=.95,t.length>0){for(let e=0;e0&&this._addSpacer(),this._panel.addControl(e.groupPanel),this._groups.push(e),e.groupPanel.children[0].color=this._headerColor;for(let t=0;t=this._groups.length)return;const t=this._groups[e];this._panel.removeControl(t.groupPanel),this._groups.splice(e,1),e=this._groups.length||(this._groups[t].groupPanel.children[0].text=e)}relabel(e,t,i){if(t<0||t>=this._groups.length)return;const s=this._groups[t];i<0||i>=s.selectors.length||s._setSelectorLabel(i,e)}removeFromGroupSelector(e,t){if(e<0||e>=this._groups.length)return;const i=this._groups[e];t<0||t>=i.selectors.length||i.removeSelector(t)}addToGroupCheckbox(e,t,i=(()=>{}),s=!1){e<0||e>=this._groups.length||this._groups[e].addCheckbox(t,i,s)}addToGroupRadio(e,t,i=(()=>{}),s=!1){e<0||e>=this._groups.length||this._groups[e].addRadio(t,i,s)}addToGroupSlider(e,t,i=(()=>{}),s="Units",r=0,n=0,o=0,a=(e=>0|e)){e<0||e>=this._groups.length||this._groups[e].addSlider(t,i,s,r,n,o,a)}}class cw extends LD{get freezeControls(){return this._freezeControls}set freezeControls(e){if(this._freezeControls===e)return;e||this._restoreMeasures(),this._freezeControls=!1;const t=this.host.getSize(),i=t.width,s=t.height,r=this.host.getContext(),n=new DD(0,0,i,s);this.host._numLayoutCalls=0,this.host._rootContainer._layout(n,r),e&&(this._updateMeasures(),this._useBuckets()&&this._makeBuckets()),this._freezeControls=e,this.host.markAsDirty()}get bucketWidth(){return this._bucketWidth}get bucketHeight(){return this._bucketHeight}setBucketSizes(e,t){this._bucketWidth=e,this._bucketHeight=t,this._useBuckets()?this._freezeControls&&this._makeBuckets():this._buckets={}}_useBuckets(){return this._bucketWidth>0&&this._bucketHeight>0}_makeBuckets(){this._buckets={},this._bucketLen=Math.ceil(this.widthInPixels/this._bucketWidth),this._dispatchInBuckets(this._children),this._oldLeft=null,this._oldTop=null}_dispatchInBuckets(e){for(let t=0;t0&&this._dispatchInBuckets(i._children)}}_updateMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left-=e,this._measureForChildren.top-=t,this._currentMeasure.left-=e,this._currentMeasure.top-=t,this._customData.origLeftForChildren=this._measureForChildren.left,this._customData.origTopForChildren=this._measureForChildren.top,this._customData.origLeft=this._currentMeasure.left,this._customData.origTop=this._currentMeasure.top,this._updateChildrenMeasures(this._children,e,t)}_updateChildrenMeasures(e,t,i){for(let s=0;s0&&this._updateChildrenMeasures(r._children,t,i)}}_restoreMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left=this._customData.origLeftForChildren+e,this._measureForChildren.top=this._customData.origTopForChildren+t,this._currentMeasure.left=this._customData.origLeft+e,this._currentMeasure.top=this._customData.origTop+t}constructor(e){super(e),this._freezeControls=!1,this._bucketWidth=0,this._bucketHeight=0,this._buckets={}}_getTypeName(){return"ScrollViewerWindow"}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._parentMeasure=e,this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this._measureForChildren.width=e.width,this._measureForChildren.height=e.height}_layout(e,t){return this._freezeControls?(this.invalidateRect(),!1):super._layout(e,t)}_scrollChildren(e,t,i){for(let s=0;s0&&this._scrollChildren(r._children,t,i)}}_scrollChildrenWithBuckets(e,t,i,s){const r=Math.max(0,Math.floor(-e/this._bucketWidth)),n=Math.floor((-e+this._parentMeasure.width-1)/this._bucketWidth),o=Math.floor((-t+this._parentMeasure.height-1)/this._bucketHeight);let a=Math.max(0,Math.floor(-t/this._bucketHeight));for(;a<=o;){for(let e=r;e<=n;++e){const t=a*this._bucketLen+e,r=this._buckets[t];if(r)for(let e=0;ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;s=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}serialize(e){super.serialize(e),this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient))}_parseFromContent(e,t){if(super._parseFromContent(e,t),e.backgroundGradient){const t=hs.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this.backgroundGradient=new t,this.backgroundGradient.parse(e.backgroundGradient)}}}qe([st()],uw.prototype,"borderColor",null),qe([st()],uw.prototype,"background",null),qe([st()],uw.prototype,"invertScrollDirection",null),ee("BABYLON.GUI.Scrollbar",uw);class dw extends sw{get invertScrollDirection(){return this._invertScrollDirection}set invertScrollDirection(e){this._invertScrollDirection=e}get backgroundImage(){return this._backgroundBaseImage}set backgroundImage(e){this._backgroundBaseImage!==e&&(this._backgroundBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._backgroundImage=e._rotate90(this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(this.num90RotationInVerticalMode,!0);this._backgroundImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._backgroundImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbImage(){return this._thumbBaseImage}set thumbImage(e){this._thumbBaseImage!==e&&(this._thumbBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._thumbImage=e._rotate90(-this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(-this.num90RotationInVerticalMode,!0);this._thumbImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbLength(){return this._thumbLength}set thumbLength(e){this._thumbLength!==e&&(this._thumbLength=e,this._markAsDirty())}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){this._thumbLength!==e&&(this._thumbHeight=e,this._markAsDirty())}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){this._barImageHeight!==e&&(this._barImageHeight=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._tempMeasure=new DD(0,0,0,0),this._invertScrollDirection=!1,this.num90RotationInVerticalMode=1}_getTypeName(){return"ImageScrollBar"}_getThumbThickness(){let e=0;return e=this._thumbWidth.isPixel?this._thumbWidth.getValue(this._host):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host),e}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isVertical?(this._tempMeasure.copyFromFloats(i+r*(1-this._barImageHeight)*.5,this._currentMeasure.top,r*this._barImageHeight,n),this._tempMeasure.height+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)):(this._tempMeasure.copyFromFloats(this._currentMeasure.left,s+n*(1-this._barImageHeight)*.5,r,n*this._barImageHeight),this._tempMeasure.width+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)),this._backgroundImage._draw(e)),this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset+this._currentMeasure.width*(1-this._thumbHeight)*.5,this._currentMeasure.top+t,this._currentMeasure.width*this._thumbHeight,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top+this._currentMeasure.height*(1-this._thumbHeight)*.5,this._effectiveThumbThickness,this._currentMeasure.height*this._thumbHeight),this._thumbImage&&(this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}_updateValueFromPointer(e,t){0!=this.rotation&&(this._invertTransformMatrix.transformCoordinates(e,t,this._transformedPosition),e=this._transformedPosition.x,t=this._transformedPosition.y);const i=this._invertScrollDirection?-1:1;this._first&&(this._first=!1,this._originX=e,this._originY=t,(ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;s=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}}qe([st()],dw.prototype,"num90RotationInVerticalMode",void 0),qe([st()],dw.prototype,"invertScrollDirection",null);class _w extends kD{get horizontalBar(){return this._horizontalBar}get verticalBar(){return this._verticalBar}addControl(e){return e?(this._window.addControl(e),this):this}removeControl(e){return this._window.removeControl(e),this}get children(){return this._window.children}_flagDescendantsAsMatrixDirty(){for(const e of this._children)e._markMatrixAsDirty()}get freezeControls(){return this._window.freezeControls}set freezeControls(e){this._window.freezeControls=e}get bucketWidth(){return this._window.bucketWidth}get bucketHeight(){return this._window.bucketHeight}setBucketSizes(e,t){this._window.setBucketSizes(e,t)}get forceHorizontalBar(){return this._forceHorizontalBar}set forceHorizontalBar(e){this._grid.setRowDefinition(1,e?this._barSize:0,!0),this._horizontalBar.isVisible=e,this._forceHorizontalBar=e}get forceVerticalBar(){return this._forceVerticalBar}set forceVerticalBar(e){this._grid.setColumnDefinition(1,e?this._barSize:0,!0),this._verticalBar.isVisible=e,this._forceVerticalBar=e}constructor(e,t){super(e),this._barSize=20,this._pointerIsOver=!1,this._wheelPrecision=.05,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._horizontalBarImageHeight=1,this._verticalBarImageHeight=1,this._oldWindowContentsWidth=0,this._oldWindowContentsHeight=0,this._forceHorizontalBar=!1,this._forceVerticalBar=!1,this._useImageBar=t||!1,this.onDirtyObservable.add((()=>{this._horizontalBarSpace.color=this.color,this._verticalBarSpace.color=this.color,this._dragSpace.color=this.color})),this.onPointerEnterObservable.add((()=>{this._pointerIsOver=!0})),this.onPointerOutObservable.add((()=>{this._pointerIsOver=!1})),this._grid=new QD,this._useImageBar?(this._horizontalBar=new dw,this._verticalBar=new dw):(this._horizontalBar=new uw,this._verticalBar=new uw),this._window=new cw("scrollViewer_window"),this._window.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._window.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._grid.addColumnDefinition(1),this._grid.addColumnDefinition(0,!0),this._grid.addRowDefinition(1),this._grid.addRowDefinition(0,!0),super.addControl(this._grid),this._grid.addControl(this._window,0,0),this._verticalBarSpace=new kD,this._verticalBarSpace.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._verticalBarSpace.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._verticalBarSpace.thickness=1,this._grid.addControl(this._verticalBarSpace,0,1),this._addBar(this._verticalBar,this._verticalBarSpace,!0,Math.PI),this._horizontalBarSpace=new kD,this._horizontalBarSpace.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._horizontalBarSpace.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._horizontalBarSpace.thickness=1,this._grid.addControl(this._horizontalBarSpace,1,0),this._addBar(this._horizontalBar,this._horizontalBarSpace,!1,0),this._dragSpace=new kD,this._dragSpace.thickness=1,this._grid.addControl(this._dragSpace,1,1),this._grid.clipChildren=!1,this._useImageBar||(this.barColor="grey",this.barBackground="transparent")}resetWindow(){this._window.width="100%",this._window.height="100%"}_getTypeName(){return"ScrollViewer"}_buildClientSizes(){const e=this.host.idealRatio;this._window.parentClientWidth=this._currentMeasure.width-(this._verticalBar.isVisible||this.forceVerticalBar?this._barSize*e:0)-2*this.thickness,this._window.parentClientHeight=this._currentMeasure.height-(this._horizontalBar.isVisible||this.forceHorizontalBar?this._barSize*e:0)-2*this.thickness,this._clientWidth=this._window.parentClientWidth,this._clientHeight=this._window.parentClientHeight}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._buildClientSizes()}_postMeasure(){super._postMeasure(),this._updateScroller(),this._setWindowPosition(!1)}get wheelPrecision(){return this._wheelPrecision}set wheelPrecision(e){this._wheelPrecision!==e&&(e<0&&(e=0),e>1&&(e=1),this._wheelPrecision=e)}get scrollBackground(){return this._horizontalBarSpace.background}set scrollBackground(e){this._horizontalBarSpace.background!==e&&(this._horizontalBarSpace.background=e,this._verticalBarSpace.background=e)}get barColor(){return this._barColor}set barColor(e){this._barColor!==e&&(this._barColor=e,this._horizontalBar.color=e,this._verticalBar.color=e)}get thumbImage(){return this._barImage}set thumbImage(e){if(this._barImage===e)return;this._barImage=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbImage=e,i.thumbImage=e}get horizontalThumbImage(){return this._horizontalBarImage}set horizontalThumbImage(e){this._horizontalBarImage!==e&&(this._horizontalBarImage=e,this._horizontalBar.thumbImage=e)}get verticalThumbImage(){return this._verticalBarImage}set verticalThumbImage(e){this._verticalBarImage!==e&&(this._verticalBarImage=e,this._verticalBar.thumbImage=e)}get barSize(){return this._barSize}set barSize(e){this._barSize!==e&&(this._barSize=e,this._markAsDirty(),this._horizontalBar.isVisible&&this._grid.setRowDefinition(1,this._barSize,!0),this._verticalBar.isVisible&&this._grid.setColumnDefinition(1,this._barSize,!0))}get thumbLength(){return this._thumbLength}set thumbLength(e){if(this._thumbLength===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbLength=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbLength=e,i.thumbLength=e,this._markAsDirty()}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){if(this._thumbHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbHeight=e,i.thumbHeight=e,this._markAsDirty()}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){if(this._barImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._barImageHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.barImageHeight=e,i.barImageHeight=e,this._markAsDirty()}get horizontalBarImageHeight(){return this._horizontalBarImageHeight}set horizontalBarImageHeight(e){this._horizontalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._horizontalBarImageHeight=e,this._horizontalBar.barImageHeight=e,this._markAsDirty())}get verticalBarImageHeight(){return this._verticalBarImageHeight}set verticalBarImageHeight(e){this._verticalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._verticalBarImageHeight=e,this._verticalBar.barImageHeight=e,this._markAsDirty())}get barBackground(){return this._barBackground}set barBackground(e){if(this._barBackground===e)return;this._barBackground=e;const t=this._horizontalBar,i=this._verticalBar;t.background=e,i.background=e,this._dragSpace.background=e}get barImage(){return this._barBackgroundImage}set barImage(e){this._barBackgroundImage=e;const t=this._horizontalBar,i=this._verticalBar;t.backgroundImage=e,i.backgroundImage=e}get horizontalBarImage(){return this._horizontalBarBackgroundImage}set horizontalBarImage(e){this._horizontalBarBackgroundImage=e,this._horizontalBar.backgroundImage=e}get verticalBarImage(){return this._verticalBarBackgroundImage}set verticalBarImage(e){this._verticalBarBackgroundImage=e,this._verticalBar.backgroundImage=e}_setWindowPosition(e=!0){const t=this.host.idealRatio,i=this._window._currentMeasure.width,s=this._window._currentMeasure.height;if(!e&&this._oldWindowContentsWidth===i&&this._oldWindowContentsHeight===s)return;this._oldWindowContentsWidth=i,this._oldWindowContentsHeight=s;const r=this._clientWidth-i,n=this._clientHeight-s,o=this._horizontalBar.value/t*r+"px",a=this._verticalBar.value/t*n+"px";o!==this._window.left&&(this._window.left=o,this.freezeControls||(this._rebuildLayout=!0)),a!==this._window.top&&(this._window.top=a,this.freezeControls||(this._rebuildLayout=!0))}_updateScroller(){const e=this._window._currentMeasure.width,t=this._window._currentMeasure.height;this._horizontalBar.isVisible&&e<=this._clientWidth&&!this.forceHorizontalBar?(this._grid.setRowDefinition(1,0,!0),this._horizontalBar.isVisible=!1,this._horizontalBar.value=0,this._rebuildLayout=!0):!this._horizontalBar.isVisible&&(e>this._clientWidth||this.forceHorizontalBar)&&(this._grid.setRowDefinition(1,this._barSize,!0),this._horizontalBar.isVisible=!0,this._rebuildLayout=!0),this._verticalBar.isVisible&&t<=this._clientHeight&&!this.forceVerticalBar?(this._grid.setColumnDefinition(1,0,!0),this._verticalBar.isVisible=!1,this._verticalBar.value=0,this._rebuildLayout=!0):!this._verticalBar.isVisible&&(t>this._clientHeight||this.forceVerticalBar)&&(this._grid.setColumnDefinition(1,this._barSize,!0),this._verticalBar.isVisible=!0,this._rebuildLayout=!0),this._buildClientSizes();const i=this.host.idealRatio;this._horizontalBar.thumbWidth=.9*this._thumbLength*(this._clientWidth/i)+"px",this._verticalBar.thumbWidth=.9*this._thumbLength*(this._clientHeight/i)+"px"}_link(e){super._link(e),this._attachWheel()}_addBar(e,t,i,s){e.paddingLeft=0,e.width="100%",e.height="100%",e.barOffset=0,e.value=0,e.maximum=1,e.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,e.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,e.isVertical=i,e.rotation=s,e.isVisible=!1,t.addControl(e),e.onValueChangedObservable.add((()=>{this._setWindowPosition()}))}_attachWheel(){this._host&&!this._onWheelObserver&&(this._onWheelObserver=this.onWheelObservable.add((e=>{this._pointerIsOver&&!this.isReadOnly&&(1==this._verticalBar.isVisible&&(e.y<0&&this._verticalBar.value>0?this._verticalBar.value-=this._wheelPrecision:e.y>0&&this._verticalBar.value0&&this._horizontalBar.value>0&&(this._horizontalBar.value-=this._wheelPrecision)))})))}_renderHighlightSpecific(e){this.isHighlighted&&(super._renderHighlightSpecific(e),this._grid._renderHighlightSpecific(e),e.restore())}dispose(){this.onWheelObservable.remove(this._onWheelObserver),this._onWheelObserver=null,super.dispose()}}qe([st()],_w.prototype,"wheelPrecision",null),qe([st()],_w.prototype,"scrollBackground",null),qe([st()],_w.prototype,"barColor",null),qe([st()],_w.prototype,"barSize",null),qe([st()],_w.prototype,"barBackground",null),ee("BABYLON.GUI.ScrollViewer",_w);class pw extends kD{get group(){return this._group}set group(e){this._group!==e&&(this._group=e)}get isActive(){return this._isActive}set isActive(e){this._isActive!==e&&(this._isActive=e,this._isActive?this.toActiveAnimation?.():this.toInactiveAnimation?.(),this._markAsDirty(),this.onIsActiveChangedObservable.notifyObservers(e),this._isActive&&this._host&&this._group&&this._host.executeOnAllControls((e=>{if("ToggleButton"===e.typeName){if(e===this)return;const t=e;t.group===this.group&&(t.isActive=!1)}})))}constructor(e,t){super(e),this.name=e,this.onIsActiveChangedObservable=new X,this.delegatePickingToChildren=!1,this._isActive=!1,this.group=t??"",this.thickness=0,this.isPointerBlocker=!0;let i=null;this.toActiveAnimation=()=>{this.thickness=1},this.toInactiveAnimation=()=>{this.thickness=0},this.pointerEnterActiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutActiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownActiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpActiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05},this.pointerEnterInactiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutInactiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownInactiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpInactiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"ToggleButton"}_processPicking(e,t,i,s,r,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(s,e,t,i,r,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(this.isReadOnly||(this._isActive?this.pointerEnterActiveAnimation&&this.pointerEnterActiveAnimation():this.pointerEnterInactiveAnimation&&this.pointerEnterInactiveAnimation()),!0)}_onPointerOut(e,t,i=!1){this.isReadOnly||(this._isActive?this.pointerOutActiveAnimation&&this.pointerOutActiveAnimation():this.pointerOutInactiveAnimation&&this.pointerOutInactiveAnimation()),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(this.isReadOnly||(this._isActive?this.pointerDownActiveAnimation&&this.pointerDownActiveAnimation():this.pointerDownInactiveAnimation&&this.pointerDownInactiveAnimation()),!0)}_onPointerUp(e,t,i,s,r,n){this.isReadOnly||(this._isActive?this.pointerUpActiveAnimation&&this.pointerUpActiveAnimation():this.pointerUpInactiveAnimation&&this.pointerUpInactiveAnimation()),super._onPointerUp(e,t,i,s,r,n)}}ee("BABYLON.GUI.ToggleButton",pw);class fw{}class mw extends WD{constructor(){super(...arguments),this.onKeyPressObservable=new X,this.defaultButtonWidth="40px",this.defaultButtonHeight="40px",this.defaultButtonPaddingLeft="2px",this.defaultButtonPaddingRight="2px",this.defaultButtonPaddingTop="2px",this.defaultButtonPaddingBottom="2px",this.defaultButtonColor="#DDD",this.defaultButtonBackground="#070707",this.shiftButtonColor="#7799FF",this.selectedShiftThickness=1,this.shiftState=0,this._currentlyConnectedInputText=null,this._connectedInputTexts=[],this._onKeyPressObserver=null}_getTypeName(){return"VirtualKeyboard"}_createKey(e,t){const i=zD.CreateSimpleButton(e,e);return i.width=t&&t.width?t.width:this.defaultButtonWidth,i.height=t&&t.height?t.height:this.defaultButtonHeight,i.color=t&&t.color?t.color:this.defaultButtonColor,i.background=t&&t.background?t.background:this.defaultButtonBackground,i.paddingLeft=t&&t.paddingLeft?t.paddingLeft:this.defaultButtonPaddingLeft,i.paddingRight=t&&t.paddingRight?t.paddingRight:this.defaultButtonPaddingRight,i.paddingTop=t&&t.paddingTop?t.paddingTop:this.defaultButtonPaddingTop,i.paddingBottom=t&&t.paddingBottom?t.paddingBottom:this.defaultButtonPaddingBottom,i.thickness=0,i.isFocusInvisible=!0,i.shadowColor=this.shadowColor,i.shadowBlur=this.shadowBlur,i.shadowOffsetX=this.shadowOffsetX,i.shadowOffsetY=this.shadowOffsetY,i.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e)})),i}addKeysRow(e,t){const i=new WD;i.isVertical=!1,i.isFocusInvisible=!0;let s=null;for(let r=0;rs.heightInPixels)&&(s=o),i.addControl(o)}i.height=s?s.height:this.defaultButtonHeight,this.addControl(i)}applyShiftState(e){if(this.children)for(let t=0;t1?this.selectedShiftThickness:0),r.text=e>0?r.text.toUpperCase():r.text.toLowerCase()}}}get connectedInputText(){return this._currentlyConnectedInputText}connect(e){if(this._connectedInputTexts.some((t=>t.input===e)))return;null===this._onKeyPressObserver&&(this._onKeyPressObserver=this.onKeyPressObservable.add((e=>{if(this._currentlyConnectedInputText){switch(this._currentlyConnectedInputText._host.focusedControl=this._currentlyConnectedInputText,e){case"⇧":return this.shiftState++,this.shiftState>2&&(this.shiftState=0),void this.applyShiftState(this.shiftState);case"←":return void(this._currentlyConnectedInputText instanceof qD?this._currentlyConnectedInputText.alternativeProcessKey("Backspace"):this._currentlyConnectedInputText.processKey(8));case"↵":return void(this._currentlyConnectedInputText instanceof qD?this._currentlyConnectedInputText.alternativeProcessKey("Enter"):this._currentlyConnectedInputText.processKey(13))}this._currentlyConnectedInputText instanceof qD?this._currentlyConnectedInputText.alternativeProcessKey("",this.shiftState?e.toUpperCase():e):this._currentlyConnectedInputText.processKey(-1,this.shiftState?e.toUpperCase():e),1===this.shiftState&&(this.shiftState=0,this.applyShiftState(this.shiftState))}}))),this.isVisible=!1,this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this;const t=e.onFocusObservable.add((()=>{this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this,this.isVisible=!0})),i=e.onBlurObservable.add((()=>{e._connectedVirtualKeyboard=null,this._currentlyConnectedInputText=null,this.isVisible=!1}));this._connectedInputTexts.push({input:e,onBlurObserver:i,onFocusObserver:t})}disconnect(e){if(e){const t=this._connectedInputTexts.filter((t=>t.input===e));1===t.length&&(this._removeConnectedInputObservables(t[0]),this._connectedInputTexts=this._connectedInputTexts.filter((t=>t.input!==e)),this._currentlyConnectedInputText===e&&(this._currentlyConnectedInputText=null))}else this._connectedInputTexts.forEach((e=>{this._removeConnectedInputObservables(e)})),this._connectedInputTexts.length=0;0===this._connectedInputTexts.length&&(this._currentlyConnectedInputText=null,this.onKeyPressObservable.remove(this._onKeyPressObserver),this._onKeyPressObserver=null)}_removeConnectedInputObservables(e){e.input._connectedVirtualKeyboard=null,e.input.onFocusObservable.remove(e.onFocusObserver),e.input.onBlurObservable.remove(e.onBlurObserver)}dispose(){super.dispose(),this.disconnect()}static CreateDefaultLayout(e){const t=new mw(e);return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","←"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","↵"]),t.addKeysRow(["⇧","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t}_parseFromContent(e,t){super._parseFromContent(e,t);for(const e of this.children)if("StackPanel"===e.getClassName()){const t=e;for(const e of t.children)"Button"===e.getClassName()&&e.name&&e.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e.name)}))}}}ee("BABYLON.GUI.VirtualKeyboard",mw);class gw extends BD{get displayMinorLines(){return this._displayMinorLines}set displayMinorLines(e){this._displayMinorLines!==e&&(this._displayMinorLines=e,this._markAsDirty())}get displayMajorLines(){return this._displayMajorLines}set displayMajorLines(e){this._displayMajorLines!==e&&(this._displayMajorLines=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth=e,this._markAsDirty()}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight=e,this._markAsDirty()}get minorLineTickness(){return this._minorLineTickness}set minorLineTickness(e){this._minorLineTickness=e,this._markAsDirty()}get minorLineColor(){return this._minorLineColor}set minorLineColor(e){this._minorLineColor=e,this._markAsDirty()}get majorLineTickness(){return this._majorLineTickness}set majorLineTickness(e){this._majorLineTickness=e,this._markAsDirty()}get majorLineColor(){return this._majorLineColor}set majorLineColor(e){this._majorLineColor=e,this._markAsDirty()}get majorLineFrequency(){return this._majorLineFrequency}set majorLineFrequency(e){this._majorLineFrequency=e,this._markAsDirty()}constructor(e){super(e),this.name=e,this._cellWidth=20,this._cellHeight=20,this._minorLineTickness=1,this._minorLineColor="DarkGray",this._majorLineTickness=2,this._majorLineColor="White",this._majorLineFrequency=5,this._background="Black",this._displayMajorLines=!0,this._displayMinorLines=!0}_draw(e){if(e.save(),this._applyStates(e),this._isEnabled){this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height));const t=this._currentMeasure.width/this._cellWidth,i=this._currentMeasure.height/this._cellHeight,s=this._currentMeasure.left+this._currentMeasure.width/2,r=this._currentMeasure.top+this._currentMeasure.height/2;if(this._displayMinorLines){e.strokeStyle=this._minorLineColor,e.lineWidth=this._minorLineTickness;for(let i=-t/2+1;ithis._markAsDirty())),this._markAsDirty())}get valueBarImage(){return this._valueBarImage}set valueBarImage(e){this._valueBarImage!==e&&(this._valueBarImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}get thumbImage(){return this._thumbImage}set thumbImage(e){this._thumbImage!==e&&(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}constructor(e){super(e),this.name=e,this._tempMeasure=new DD(0,0,0,0)}_getTypeName(){return"ImageBasedSlider"}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isThumbClamped&&this.displayThumb&&(this.isVertical?this._tempMeasure.height+=this._effectiveThumbThickness:this._tempMeasure.width+=this._effectiveThumbThickness),this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure),this._backgroundImage._draw(e)),this._valueBarImage&&(this.isVertical?this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s+t,r,n-t+this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(i,s+t,r,n-t):this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s,t+this._effectiveThumbThickness/2,n):this._tempMeasure.copyFromFloats(i,s,t,n),this._valueBarImage._currentMeasure.copyFrom(this._tempMeasure),this._valueBarImage._draw(e)),this.displayThumb&&(this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset,this._currentMeasure.top+t,this._currentMeasure.width,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top,this._effectiveThumbThickness,this._currentMeasure.height),this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}serialize(e){super.serialize(e);const t={},i={},s={};this.backgroundImage.serialize(t),this.thumbImage.serialize(i),this.valueBarImage.serialize(s),e.backgroundImage=t,e.thumbImage=i,e.valueBarImage=s}_parseFromContent(e,t){super._parseFromContent(e,t),this.backgroundImage=GD.Parse(e.backgroundImage,t),this.thumbImage=GD.Parse(e.thumbImage,t),this.valueBarImage=GD.Parse(e.valueBarImage,t)}}qe([st()],vw.prototype,"displayThumb",null),ee("BABYLON.GUI.ImageBasedSlider",vw);const xw="Statics";BD.AddHeader=function(e,t,i,s){const r=new WD("panel"),n=!s||s.isHorizontal,o=!s||s.controlFirst;r.isVertical=!n;const a=new UD("header");return a.text=t,a.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,n?a.width=i:a.height=i,o?(r.addControl(e),r.addControl(a),a.paddingLeft="5px"):(r.addControl(a),r.addControl(e),a.paddingRight="5px"),a.shadowBlur=e.shadowBlur,a.shadowColor=e.shadowColor,a.shadowOffsetX=e.shadowOffsetX,a.shadowOffsetY=e.shadowOffsetY,r};class bw{constructor(){this._colorStops=[],this._gradientDirty=!0}_addColorStopsToCanvasGradient(){for(const e of this._colorStops)this._canvasGradient.addColorStop(e.offset,e.color)}getCanvasGradient(e){return(this._gradientDirty||this._context!==e)&&(this._context=e,this._canvasGradient=this._createCanvasGradient(e),this._addColorStopsToCanvasGradient(),this._gradientDirty=!1),this._canvasGradient}addColorStop(e,t){this._colorStops.push({offset:e,color:t}),this._gradientDirty=!0}removeColorStop(e){this._colorStops=this._colorStops.filter((t=>t.offset!==e)),this._gradientDirty=!0}clearColorStops(){this._colorStops=[],this._gradientDirty=!0}get colorStops(){return this._colorStops}getClassName(){return"BaseGradient"}serialize(e){e.colorStops=this._colorStops,e.className=this.getClassName()}parse(e){this._colorStops=e.colorStops}}class Tw extends bw{constructor(e,t,i,s){super(),this._x0=e??0,this._y0=t??0,this._x1=i??0,this._y1=s??0}_createCanvasGradient(e){return e.createLinearGradient(this._x0,this._y0,this._x1,this._y1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}getClassName(){return"LinearGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.x1=this._x1,e.y1=this._y1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._x1=e.x1,this._y1=e.y1}}ee("BABYLON.GUI.LinearGradient",Tw);class yw extends bw{constructor(e,t,i,s,r,n){super(),this._x0=e??0,this._y0=t??0,this._r0=i??0,this._x1=s??0,this._y1=r??0,this._r1=n??0}_createCanvasGradient(e){return e.createRadialGradient(this._x0,this._y0,this._r0,this._x1,this._y1,this._r1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}get r0(){return this._r0}get r1(){return this._r1}getClassName(){return"RadialGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.r0=this._r0,e.x1=this._x1,e.y1=this._y1,e.r1=this._r1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._r0=e.r0,this._x1=e.x1,this._y1=e.y1,this._r1=e.r1}}ee("BABYLON.GUI.RadialGradient",yw);class Sw{constructor(e){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new PD(18,PD.UNITMODE_PIXEL,!1),this.onChangedObservable=new X,this._host=e}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&this.onChangedObservable.notifyObservers(this)}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.onChangedObservable.notifyObservers(this))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.onChangedObservable.notifyObservers(this))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.onChangedObservable.notifyObservers(this))}dispose(){this.onChangedObservable.clear()}}class Cw extends Sc{get numLayoutCalls(){return this._numLayoutCalls}get numRenderCalls(){return this._numRenderCalls}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this._onResize())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this.markAsDirty())}get idealWidth(){return this._idealWidth}set idealWidth(e){this._idealWidth!==e&&(this._idealWidth=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get idealHeight(){return this._idealHeight}set idealHeight(e){this._idealHeight!==e&&(this._idealHeight=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get useSmallestIdeal(){return this._useSmallestIdeal}set useSmallestIdeal(e){this._useSmallestIdeal!==e&&(this._useSmallestIdeal=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get renderAtIdealSize(){return this._renderAtIdealSize}set renderAtIdealSize(e){this._renderAtIdealSize!==e&&(this._renderAtIdealSize=e,this._onResize())}get idealRatio(){let e=0,t=0;return this._idealWidth&&(e=this.getSize().width/this._idealWidth),this._idealHeight&&(t=this.getSize().height/this._idealHeight),this._useSmallestIdeal&&this._idealWidth&&this._idealHeight?window.innerWidtht.typeName===e))}getControlByName(e){return this._getControlByKey("name",e)}_getControlByKey(e,t){return this._rootContainer.getDescendants().find((i=>i[e]===t))||null}get focusedControl(){return this._focusedControl}set focusedControl(e){this._focusedControl!=e&&(this._focusedControl&&this._focusedControl.onBlur(),e&&e.onFocus(),this._focusedControl=e)}get isForeground(){return!this.layer||!this.layer.isBackground}set isForeground(e){this.layer&&this.layer.isBackground!==!e&&(this.layer.isBackground=!e)}get clipboardData(){return this._clipboardData}set clipboardData(e){this._clipboardData=e}constructor(e,t=0,i=0,s,r=!1,n=Vo.NEAREST_SAMPLINGMODE,o=!0){super(e,{width:t,height:i},s,r,n,Yd.TEXTUREFORMAT_RGBA,o),this.onGuiReadyObservable=new X,this._isDirty=!1,this._rootContainer=new LD("root"),this._lastControlOver={},this._lastControlDown={},this._capturingControl={},this._linkedControls=new Array,this._isFullscreen=!1,this._fullscreenViewport=new jr(0,0,1,1),this._idealWidth=0,this._idealHeight=0,this._useSmallestIdeal=!1,this._renderAtIdealSize=!1,this._blockNextFocusCheck=!1,this._renderScale=1,this._cursorChanged=!1,this._defaultMousePointerId=0,this._rootChildrenHaveChanged=!1,this._capturedPointerIds=new Set,this._numLayoutCalls=0,this._numRenderCalls=0,this._clipboardData="",this.onClipboardObservable=new X,this.onControlPickedObservable=new X,this.onBeginLayoutObservable=new X,this.onEndLayoutObservable=new X,this.onBeginRenderObservable=new X,this.onEndRenderObservable=new X,this.premulAlpha=!1,this.applyYInversionOnUpdate=!0,this.skipBlockEvents=0,this.checkPointerEveryFrame=!1,this._useInvalidateRectOptimization=!0,this._invalidatedRectangle=null,this._clearMeasure=new DD(0,0,0,0),this._onClipboardCopy=e=>{const t=e,i=new Zf(qf.COPY,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardCut=e=>{const t=e,i=new Zf(qf.CUT,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardPaste=e=>{const t=e,i=new Zf(qf.PASTE,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this.parseContent=this.parseSerializedObject,(s=this.getScene())&&this._texture&&(this.applyYInversionOnUpdate=o,this._rootElement=s.getEngine().getInputElement(),this._renderObserver=s.onBeforeCameraRenderObservable.add((e=>this._checkUpdate(e))),this._controlAddedObserver=this._rootContainer.onControlAddedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._controlRemovedObserver=this._rootContainer.onControlRemovedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._preKeyboardObserver=s.onPreKeyboardObservable.add((e=>{this._focusedControl&&(e.type===Ns.KEYDOWN&&this._focusedControl.processKeyboard(e.event),e.skipOnPointerObservable=!0)})),this._rootContainer._link(this),this.hasAlpha=!0,t&&i||(this._resizeObserver=s.getEngine().onResizeObservable.add((()=>this._onResize())),this._onResize()),this._texture.isReady=!0)}getClassName(){return"AdvancedDynamicTexture"}executeOnAllControls(e,t){t||(t=this._rootContainer),e(t);for(const i of t.children)i.children?this.executeOnAllControls(e,i):e(i)}get useInvalidateRectOptimization(){return this._useInvalidateRectOptimization}set useInvalidateRectOptimization(e){this._useInvalidateRectOptimization=e}invalidateRect(e,t,i,s){if(this._useInvalidateRectOptimization)if(this._invalidatedRectangle){const r=Math.ceil(Math.max(this._invalidatedRectangle.left+this._invalidatedRectangle.width-1,i)),n=Math.ceil(Math.max(this._invalidatedRectangle.top+this._invalidatedRectangle.height-1,s));this._invalidatedRectangle.left=Math.floor(Math.min(this._invalidatedRectangle.left,e)),this._invalidatedRectangle.top=Math.floor(Math.min(this._invalidatedRectangle.top,t)),this._invalidatedRectangle.width=r-this._invalidatedRectangle.left+1,this._invalidatedRectangle.height=n-this._invalidatedRectangle.top+1}else this._invalidatedRectangle=new DD(e,t,i-e+1,s-t+1)}markAsDirty(){this._isDirty=!0}createStyle(){return new Sw(this)}addControl(e){return this._rootContainer.addControl(e),this}removeControl(e){return this._rootContainer.removeControl(e),this}moveToNonOverlappedPosition(e,t=1,i=1){let s;if(Array.isArray(e))s=e;else{const t=this.getDescendants(!0);s=void 0===e?t.filter((e=>void 0!==e.overlapGroup)):t.filter((t=>t.overlapGroup===e))}s.forEach((e=>{let r=ue.Zero();const n=new ue(e.centerX,e.centerY);s.forEach((t=>{if(e!==t&&Cw._Overlaps(e,t)){const e=n.subtract(new ue(t.centerX,t.centerY)),s=e.length();s>0&&(r=r.add(e.normalize().scale(i/s)))}})),r.length()>0&&(r=r.normalize().scale(t*(e.overlapDeltaMultiplier??1)),e.linkOffsetXInPixels+=r.x,e.linkOffsetYInPixels+=r.y)}))}dispose(){const e=this.getScene();e&&(this._rootElement=null,e.onBeforeCameraRenderObservable.remove(this._renderObserver),this._resizeObserver&&e.getEngine().onResizeObservable.remove(this._resizeObserver),this._prePointerObserver&&e.onPrePointerObservable.remove(this._prePointerObserver),this._sceneRenderObserver&&e.onBeforeRenderObservable.remove(this._sceneRenderObserver),this._pointerObserver&&e.onPointerObservable.remove(this._pointerObserver),this._preKeyboardObserver&&e.onPreKeyboardObservable.remove(this._preKeyboardObserver),this._canvasPointerOutObserver&&e.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver),this._canvasBlurObserver&&e.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver),this._controlAddedObserver&&this._rootContainer.onControlAddedObservable.remove(this._controlAddedObserver),this._controlRemovedObserver&&this._rootContainer.onControlRemovedObservable.remove(this._controlRemovedObserver),this._layerToDispose&&(this._layerToDispose.texture=null,this._layerToDispose.dispose(),this._layerToDispose=null),this._rootContainer.dispose(),this.onClipboardObservable.clear(),this.onControlPickedObservable.clear(),this.onBeginRenderObservable.clear(),this.onEndRenderObservable.clear(),this.onBeginLayoutObservable.clear(),this.onEndLayoutObservable.clear(),this.onGuiReadyObservable.clear(),super.dispose())}_onResize(){const e=this.getScene();if(!e)return;const t=e.getEngine(),i=this.getSize();let s=t.getRenderWidth()*this._renderScale,r=t.getRenderHeight()*this._renderScale;this._renderAtIdealSize&&(this._idealWidth?(r=r*this._idealWidth/s,s=this._idealWidth):this._idealHeight&&(s=s*this._idealHeight/r,r=this._idealHeight)),i.width===s&&i.height===r||(this.scaleTo(s,r),this.markAsDirty(),(this._idealWidth||this._idealHeight)&&this._rootContainer._markAllAsDirty()),this.invalidateRect(0,0,i.width-1,i.height-1)}_getGlobalViewport(){const e=this.getSize(),t=this._fullscreenViewport.toGlobal(e.width,e.height),i=Math.round(t.width*(1/this.rootContainer.scaleX)),s=Math.round(t.height*(1/this.rootContainer.scaleY));return t.x+=(t.width-i)/2,t.y+=(t.height-s)/2,t.width=i,t.height=s,t}getProjectedPosition(e,t){const i=this.getProjectedPositionWithZ(e,t);return new ue(i.x,i.y)}getProjectedPositionWithZ(e,t){const i=this.getScene();if(!i)return de.Zero();const s=this._getGlobalViewport(),r=de.Project(e,t,i.getTransformMatrix(),s);return new de(r.x,r.y,r.z)}_checkUpdate(e,t){if(!this._layerToDispose||e.layerMask&this._layerToDispose.layerMask){if(this._isFullscreen&&this._linkedControls.length){const e=this.getScene();if(!e)return;const t=this._getGlobalViewport();for(const i of this._linkedControls){if(!i.isVisible)continue;const s=i._linkedMesh;if(!s||s.isDisposed()){hs.SetImmediate((()=>{i.linkWithMesh(null)}));continue}const r=s.getBoundingInfo?s.getBoundingInfo().boundingSphere.center:de.ZeroReadOnly,n=de.Project(r,s.getWorldMatrix(),e.getTransformMatrix(),t);n.z<0||n.z>1?i.notRenderable=!0:(i.notRenderable=!1,this.useInvalidateRectOptimization&&i.invalidateRect(),i._moveToProjectedPosition(n))}}(this._isDirty||this._rootContainer.isDirty)&&(this._isDirty=!1,this._render(t),t||this.update(this.applyYInversionOnUpdate,this.premulAlpha,Cw.AllowGPUOptimizations))}}_render(e){const t=this.getSize(),i=t.width,s=t.height,r=this.getContext();if(r.font="18px Arial",r.strokeStyle="white",this.onGuiReadyObservable.hasObservers()&&this._checkGuiIsReady(),this._rootChildrenHaveChanged){const e=this.getScene()?.activeCamera;e&&(this._rootChildrenHaveChanged=!1,this._checkUpdate(e,!0))}this.onBeginLayoutObservable.notifyObservers(this);const n=new DD(0,0,i,s);this._numLayoutCalls=0,this._rootContainer._layout(n,r),this.onEndLayoutObservable.notifyObservers(this),this._isDirty=!1,e||(this._invalidatedRectangle?this._clearMeasure.copyFrom(this._invalidatedRectangle):this._clearMeasure.copyFromFloats(0,0,i,s),r.clearRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),this._background&&(r.save(),r.fillStyle=this._background,r.fillRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),r.restore()),this.onBeginRenderObservable.notifyObservers(this),this._numRenderCalls=0,this._rootContainer._render(r,this._invalidatedRectangle),this.onEndRenderObservable.notifyObservers(this),this._invalidatedRectangle=null)}_changeCursor(e){this._rootElement&&(this._rootElement.style.cursor=e,this._cursorChanged=!0)}_registerLastControlDown(e,t){this._lastControlDown[t]=e,this.onControlPickedObservable.notifyObservers(e)}_doPicking(e,t,i,s,r,n,o,a){const l=this.getScene();if(!l)return;const h=l.getEngine(),c=this.getSize();if(this._isFullscreen){const i=l.cameraToUseForPointers||l.activeCamera;if(!i)return;const s=i.viewport;e*=c.width/(h.getRenderWidth()*s.width),t*=c.height/(h.getRenderHeight()*s.height)}if(this._capturingControl[r])return this._capturingControl[r].isPointerBlocker&&(this._shouldBlockPointer=!0),void this._capturingControl[r]._processObservables(s,e,t,i,r,n);this._cursorChanged=!1,this._rootContainer._processPicking(e,t,i,s,r,n,o,a)||(l.doNotHandleCursors||this._changeCursor(""),s===Ms.POINTERMOVE&&this._lastControlOver[r]&&(this._lastControlOver[r]._onPointerOut(this._lastControlOver[r],i),delete this._lastControlOver[r])),this._cursorChanged||l.doNotHandleCursors||this._changeCursor(""),this._manageFocus()}_cleanControlAfterRemovalFromList(e,t){for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&e[i]===t&&delete e[i]}_cleanControlAfterRemoval(e){this._cleanControlAfterRemovalFromList(this._lastControlDown,e),this._cleanControlAfterRemovalFromList(this._lastControlOver,e)}pick(e,t,i=null){this._isFullscreen&&this._scene&&this._translateToPicking(this._scene,new jr(0,0,0,0),i,e,t)}_translateToPicking(e,t,i,s=e.pointerX,r=e.pointerY){const n=e.cameraToUseForPointers||e.activeCamera,o=e.getEngine(),a=e.cameraToUseForPointers;if(n)if(n.rigCameras.length){const i=new jr(0,0,1,1);n.rigCameras.forEach((n=>{n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),i);const a=s/o.getHardwareScalingLevel()-i.x,l=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-i.y-i.height);a<0||l<0||s>i.width||r>i.height||(e.cameraToUseForPointers=n,t.x=i.x,t.y=i.y,t.width=i.width,t.height=i.height)}))}else n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),t);else t.x=0,t.y=0,t.width=o.getRenderWidth(),t.height=o.getRenderHeight();const l=s/o.getHardwareScalingLevel()-t.x,h=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-t.y-t.height);if(this._shouldBlockPointer=!1,i){const e=i.event.pointerId||this._defaultMousePointerId;this._doPicking(l,h,i,i.type,e,i.event.button,i.event.deltaX,i.event.deltaY),(this._shouldBlockPointer&&!(i.type&this.skipBlockEvents)||this._capturingControl[e])&&(i.skipOnPointerObservable=!0)}else this._doPicking(l,h,null,Ms.POINTERMOVE,this._defaultMousePointerId,0);e.cameraToUseForPointers=a}attach(){const e=this.getScene();if(!e)return;const t=new jr(0,0,0,0);this._prePointerObserver=e.onPrePointerObservable.add((i=>{if((!e.isPointerCaptured(i.event.pointerId)||i.type!==Ms.POINTERUP||this._capturedPointerIds.has(i.event.pointerId))&&(i.type===Ms.POINTERMOVE||i.type===Ms.POINTERUP||i.type===Ms.POINTERDOWN||i.type===Ms.POINTERWHEEL)){if(i.type===Ms.POINTERMOVE){if(e.isPointerCaptured(i.event.pointerId))return;i.event.pointerId&&(this._defaultMousePointerId=i.event.pointerId)}this._translateToPicking(e,t,i)}})),this._attachPickingToSceneRender(e,(()=>this._translateToPicking(e,t,null)),!1),this._attachToOnPointerOut(e),this._attachToOnBlur(e)}registerClipboardEvents(){self.addEventListener("copy",this._onClipboardCopy,!1),self.addEventListener("cut",this._onClipboardCut,!1),self.addEventListener("paste",this._onClipboardPaste,!1)}unRegisterClipboardEvents(){self.removeEventListener("copy",this._onClipboardCopy),self.removeEventListener("cut",this._onClipboardCut),self.removeEventListener("paste",this._onClipboardPaste)}_transformUvs(e){const t=this.getTextureMatrix();let i;if(t.isIdentityAs3x2())i=e;else{const s=ge.Matrix[0];t.getRowToRef(0,ge.Vector4[0]),t.getRowToRef(1,ge.Vector4[1]),t.getRowToRef(2,ge.Vector4[2]);const r=ge.Vector4[0],n=ge.Vector4[1],o=ge.Vector4[2];s.setRowFromFloats(0,r.x,r.y,0,0),s.setRowFromFloats(1,n.x,n.y,0,0),s.setRowFromFloats(2,0,0,1,0),s.setRowFromFloats(3,o.x,o.y,0,1),i=ge.Vector2[0],ue.TransformToRef(e,s,i)}if((this.wrapU===Vo.WRAP_ADDRESSMODE||this.wrapU===Vo.MIRROR_ADDRESSMODE)&&i.x>1){let e=i.x-Math.trunc(i.x);this.wrapU===Vo.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.x=e}if((this.wrapV===Vo.WRAP_ADDRESSMODE||this.wrapV===Vo.MIRROR_ADDRESSMODE)&&i.y>1){let e=i.y-Math.trunc(i.y);this.wrapV===Vo.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.y=e}return i}attachToMesh(e,t=!0){const i=this.getScene();i&&(this._pointerObserver&&i.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=i.onPointerObservable.add((t=>{if(t.type!==Ms.POINTERMOVE&&t.type!==Ms.POINTERUP&&t.type!==Ms.POINTERDOWN&&t.type!==Ms.POINTERWHEEL)return;t.type===Ms.POINTERMOVE&&t.event.pointerId&&(this._defaultMousePointerId=t.event.pointerId);const i=t.event.pointerId||this._defaultMousePointerId;if(t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh===e){let e=t.pickInfo.getTextureCoordinates();if(e){e=this._transformUvs(e);const s=this.getSize();this._doPicking(e.x*s.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*s.height,t,t.type,i,t.event.button,t.event.deltaX,t.event.deltaY)}}else if(t.type===Ms.POINTERUP){if(this._lastControlDown[i]&&this._lastControlDown[i]._forcePointerUp(i),delete this._lastControlDown[i],this.focusedControl){const e=this.focusedControl.keepsFocusWith();let t=!0;if(e)for(const s of e){if(this===s._host)continue;const e=s._host;if(e._lastControlOver[i]&&e._lastControlOver[i].isAscendant(s)){t=!1;break}}t&&(this.focusedControl=null)}}else t.type===Ms.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i],t,!0),delete this._lastControlOver[i])})),e.enablePointerMoveEvents=t,this._attachPickingToSceneRender(i,(()=>{const t=this._defaultMousePointerId,s=i?.pick(i.pointerX,i.pointerY);if(s&&s.hit&&s.pickedMesh===e){let e=s.getTextureCoordinates();if(e){e=this._transformUvs(e);const i=this.getSize();this._doPicking(e.x*i.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*i.height,null,Ms.POINTERMOVE,t,0)}}else this._lastControlOver[t]&&this._lastControlOver[t]._onPointerOut(this._lastControlOver[t],null,!0),delete this._lastControlOver[t]}),!0),this._attachToOnPointerOut(i),this._attachToOnBlur(i))}moveFocusToControl(e){this.focusedControl=e,this._lastPickedControl=e,this._blockNextFocusCheck=!0}_manageFocus(){if(this._blockNextFocusCheck)return this._blockNextFocusCheck=!1,void(this._lastPickedControl=this._focusedControl);if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}}_attachPickingToSceneRender(e,t,i){this._sceneRenderObserver=e.onBeforeRenderObservable.add((()=>{this.checkPointerEveryFrame&&(this._linkedControls.length>0||i)&&t()}))}_attachToOnPointerOut(e){this._canvasPointerOutObserver=e.getEngine().onCanvasPointerOutObservable.add((e=>{this._lastControlOver[e.pointerId]&&this._lastControlOver[e.pointerId]._onPointerOut(this._lastControlOver[e.pointerId],null),delete this._lastControlOver[e.pointerId],this._lastControlDown[e.pointerId]&&this._lastControlDown[e.pointerId]!==this._capturingControl[e.pointerId]&&(this._lastControlDown[e.pointerId]._forcePointerUp(e.pointerId),delete this._lastControlDown[e.pointerId])}))}_attachToOnBlur(e){this._canvasBlurObserver=e.getEngine().onCanvasBlurObservable.add((()=>{Object.entries(this._lastControlDown).forEach((([,e])=>{e._onCanvasBlur()})),this.focusedControl=null,this._lastControlDown={}}))}serializeContent(){const e=this.getSize(),t={root:{},width:e.width,height:e.height};return this._rootContainer.serialize(t.root),t}parseSerializedObject(e,t){if(this._rootContainer=BD.Parse(e.root,this),t){const t=e.width,i=e.height;"number"==typeof t&&"number"==typeof i&&t>=0&&i>=0?this.scaleTo(t,i):this.scaleTo(1920,1080)}}clone(e,t){const i=this.getScene();if(!i)return this;const s=this.getSize(),r=this.serializeContent();let n;return n=this._isFullscreen?Cw.CreateFullscreenUI(e??"Clone of "+this.name):t?Cw.CreateForMesh(t,s.width,s.height):new Cw(e??"Clone of "+this.name,s.width,s.height,i,!this.noMipmap,this.samplingMode),n.parseSerializedObject(r),n}static async ParseFromSnippetAsync(e,t,i){const s=i??Cw.CreateFullscreenUI("ADT from snippet");if("_BLANK"===e)return s;const r=await Cw._LoadURLContentAsync(Cw.SnippetUrl+"/"+e.replace(/#/g,"/"),!0);return s.parseSerializedObject(r,t),s}parseFromSnippetAsync(e,t){return Cw.ParseFromSnippetAsync(e,t,this)}static async ParseFromFileAsync(e,t,i){const s=i??Cw.CreateFullscreenUI("ADT from URL"),r=await Cw._LoadURLContentAsync(e);return s.parseSerializedObject(r,t),s}parseFromURLAsync(e,t){return Cw.ParseFromFileAsync(e,t,this)}static _LoadURLContentAsync(e,t=!1){return""===e?Promise.reject("No URL provided"):new Promise(((i,s)=>{const r=new At;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let e;if(t){const t=JSON.parse(JSON.parse(r.responseText).jsonPayload);e=t.encodedGui?new TextDecoder("utf-8").decode(Jt(t.encodedGui)):t.gui}else e=r.responseText;const s=JSON.parse(e);i(s)}else s("Unable to load")})),r.open("GET",e),r.send()}))}static _Overlaps(e,t){return!(e.centerX>t.centerX+t.widthInPixels||e.centerX+e.widthInPixelst.centerY+t.heightInPixels)}static CreateForMesh(e,t=1024,i=1024,s=!0,r=!1,n,o=this._CreateMaterial){const a=ns(),l=new Cw(`AdvancedDynamicTexture for ${e.name} [${a}]`,t,i,e.getScene(),!0,Vo.TRILINEAR_SAMPLINGMODE,n);return o(e,a,l,r),l.attachToMesh(e,s),l}static _CreateMaterial(e,t,i,s){const r=te("BABYLON.StandardMaterial");if(!r)throw"StandardMaterial needs to be imported before as it contains a side-effect required by your code.";const n=new r(`AdvancedDynamicTextureMaterial for ${e.name} [${t}]`,e.getScene());n.backFaceCulling=!1,n.diffuseColor=Ce.Black(),n.specularColor=Ce.Black(),s?(n.diffuseTexture=i,n.emissiveTexture=i,i.hasAlpha=!0):(n.emissiveTexture=i,n.opacityTexture=i),e.material=n}static CreateForMeshTexture(e,t=1024,i=1024,s=!0,r){const n=new Cw(e.name+" AdvancedDynamicTexture",t,i,e.getScene(),!0,Vo.TRILINEAR_SAMPLINGMODE,r);return n.attachToMesh(e,s),n}static CreateFullscreenUI(e,t=!0,i=null,s=Vo.BILINEAR_SAMPLINGMODE,r=!1){const n=new Cw(e,0,0,i,!1,s),o=n.getScene(),a=new Xg(e+"_layer",null,o,!t);if(a.texture=n,n._layerToDispose=a,n._isFullscreen=!0,r&&o){const e=1/o.getEngine().getHardwareScalingLevel();n._rootContainer.scaleX=e,n._rootContainer.scaleY=e}return n.attach(),n}scale(e){super.scale(e),this.markAsDirty()}scaleTo(e,t){super.scaleTo(e,t),this.markAsDirty()}_checkGuiIsReady(){this.guiIsReady()&&(this.onGuiReadyObservable.notifyObservers(this),this.onGuiReadyObservable.clear())}guiIsReady(){return this._rootContainer.isReady()}}Cw.SnippetUrl=Yd.SnippetUrl,Cw.AllowGPUOptimizations=!0;class Ew{get renderTimeCounter(){return this._renderTime}get layoutTimeCounter(){return this._layoutTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeginRenderObserver=this.texture.onBeginRenderObservable.add((()=>{this._renderTime.beginMonitoring()})),this._onEndRenderObserver=this.texture.onEndRenderObservable.add((()=>{this._renderTime.endMonitoring(!0)}))):(this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null))}get captureLayoutTime(){return this._captureLayoutTime}set captureLayoutTime(e){e!==this._captureLayoutTime&&(this._captureLayoutTime=e,e?(this._onBeginLayoutObserver=this.texture.onBeginLayoutObservable.add((()=>{this._layoutTime.beginMonitoring()})),this._onEndLayoutObserver=this.texture.onEndLayoutObservable.add((()=>{this._layoutTime.endMonitoring(!0)}))):(this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null))}constructor(e){this.texture=e,this._captureRenderTime=!1,this._renderTime=new tr,this._captureLayoutTime=!1,this._layoutTime=new tr,this._onBeginRenderObserver=null,this._onEndRenderObserver=null,this._onBeginLayoutObserver=null,this._onEndLayoutObserver=null}dispose(){this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null,this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null,this.texture=null}}const Aw="XmlLoader Exception : XML file is malformed or corrupted.";class Pw{constructor(e=null){this._nodes={},this._nodeTypes={element:1,attribute:2,text:3},this._isLoaded=!1,this._objectAttributes={textHorizontalAlignment:1,textVerticalAlignment:2,horizontalAlignment:3,verticalAlignment:4,stretch:5},e&&(this._parentClass=e)}_getChainElement(e){let t=window;this._parentClass&&(t=this._parentClass);let i=e;i=i.split(".");for(let e=0;e0&&u>d)throw"XmlLoader Exception : In the Grid element, the number of columns is defined in the first row, do not add more columns in the subsequent rows.";if(0==c){if(!n[e].attributes.getNamedItem("width"))throw"XmlLoader Exception : Width must be defined for all the grid columns in the first row";s=Number(n[e].attributes.getNamedItem("width").nodeValue),h=!!n[e].attributes.getNamedItem("isPixel")&&JSON.parse(n[e].attributes.getNamedItem("isPixel").nodeValue),t.addColumnDefinition(s,h)}a=n[e].children;for(let e=0;e{if(4===r.readyState&&200===r.status){if(!r.responseXML){if(s)return void s(Aw);throw Aw}const e=r.responseXML.documentElement;this._parseXml(e.firstChild,t),this._isLoaded=!0,i&&i()}},r.onerror=function(){s&&s("an error occurred during loading the layout")},r.open("GET",e,!0),r.send()}async loadLayoutAsync(e,t){return new Promise(((i,s)=>{this.loadLayout(e,t,i,s)}))}}class Rw extends de{constructor(e,t=0){super(e.x,e.y,e.z),this.buttonIndex=t}}class Iw{get position(){return this._node?this._node.position:de.Zero()}set position(e){this._node&&(this._node.position=e)}get scaling(){return this._node?this._node.scaling:new de(1,1,1)}set scaling(e){this._node&&(this._isScaledByManager=!1,this._node.scaling=e)}get behaviors(){return this._behaviors}addBehavior(e){if(-1!==this._behaviors.indexOf(e))return this;e.init();const t=this._host.scene;return t.isLoading?t.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}get isVisible(){return this._isVisible}set isVisible(e){if(this._isVisible===e)return;this._isVisible=e;const t=this.mesh;t&&t.setEnabled(e)}constructor(e){this.name=e,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this._isScaledByManager=!1,this.onPointerMoveObservable=new X,this.onPointerOutObservable=new X,this.onPointerDownObservable=new X,this.onPointerUpObservable=new X,this.onPointerClickObservable=new X,this.onPointerEnterObservable=new X,this._behaviors=new Array}get typeName(){return this._getTypeName()}getClassName(){return this._getTypeName()}_getTypeName(){return"Control3D"}get node(){return this._node}get mesh(){return this._node instanceof Sn?this._node:null}linkToTransformNode(e){return this._node&&(this._node.parent=e),this}_prepareNode(e){if(!this._node){if(this._node=this._createNode(e),!this.node)return;this._injectGUI3DReservedDataStore(this.node).control=this;const t=this.mesh;t&&(t.isPickable=!0,this._affectMaterial(t))}}_injectGUI3DReservedDataStore(e){return e.reservedDataStore=e.reservedDataStore??{},e.reservedDataStore.GUI3D=e.reservedDataStore.GUI3D??{},e.reservedDataStore.GUI3D}_createNode(e){return null}_affectMaterial(e){e.material=null}_isTouchButton3D(e){return void 0!==e._generatePointerEventType}_onPointerMove(e,t){this.onPointerMoveObservable.notifyObservers(t,-1,e,this)}_onPointerEnter(e){return-1===this._enterCount&&(this._enterCount=0),this._enterCount++,!(this._enterCount>1||(this.onPointerEnterObservable.notifyObservers(this,-1,e,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),0))}_onPointerOut(e){this._enterCount--,this._enterCount>0||(this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,e,this),this.pointerOutAnimation&&this.pointerOutAnimation())}_onPointerDown(e,t,i,s){return this._downCount++,this._downPointerIds[i]=this._downPointerIds[i]+1||1,1===this._downCount&&(this.onPointerDownObservable.notifyObservers(new Rw(t,s),-1,e,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_onPointerUp(e,t,i,s,r){this._downCount--,this._downPointerIds[i]--,this._downPointerIds[i]<=0&&delete this._downPointerIds[i],this._downCount<0?this._downCount=0:0==this._downCount&&(r&&(this._enterCount>0||-1===this._enterCount)&&this.onPointerClickObservable.notifyObservers(new Rw(t,s),-1,e,this),this.onPointerUpObservable.notifyObservers(new Rw(t,s),-1,e,this),this.pointerUpAnimation&&this.pointerUpAnimation())}forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,de.Zero(),e,0,!0);else{for(const e in this._downPointerIds)this._onPointerUp(this,de.Zero(),+e,0,!0);this._downCount>0&&(this._downCount=1,this._onPointerUp(this,de.Zero(),0,0,!0))}}_processObservables(e,t,i,s,r){if(this._isTouchButton3D(this)&&i&&(e=this._generatePointerEventType(e,i,this._downCount)),e===Ms.POINTERMOVE){this._onPointerMove(this,t);const e=this._host._lastControlOver[s];return e&&e!==this&&e._onPointerOut(this),e!==this&&this._onPointerEnter(this),this._host._lastControlOver[s]=this,!0}return e===Ms.POINTERDOWN?(this._onPointerDown(this,t,s,r),this._host._lastControlDown[s]=this,this._host._lastPickedControl=this,!0):(e===Ms.POINTERUP||e===Ms.POINTERDOUBLETAP)&&(this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerUp(this,t,s,r,!0),delete this._host._lastControlDown[s],!0)}_disposeNode(){this._node&&(this._node.dispose(),this._node=null)}dispose(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(const e of this._behaviors)e.detach()}}class Mw extends Iw{constructor(){super(...arguments),this._contentResolution=512,this._contentScaleRatio=2}get content(){return this._content}set content(e){this._content=e,e&&this._host&&this._host.utilityLayer&&(this._facadeTexture?this._facadeTexture.rootContainer.clearControls():(this._facadeTexture=new Cw("Facade",this._contentResolution,this._contentResolution,this._host.utilityLayer.utilityLayerScene,!0,Vo.TRILINEAR_SAMPLINGMODE),this._setFacadeTextureScaling(),this._facadeTexture.premulAlpha=!0),this._facadeTexture.addControl(e),this._applyFacade(this._facadeTexture))}_setFacadeTextureScaling(){this._facadeTexture&&(this._facadeTexture.rootContainer.scaleX=this._contentScaleRatio,this._facadeTexture.rootContainer.scaleY=this._contentScaleRatioY??this._contentScaleRatio)}get contentResolution(){return this._contentResolution}set contentResolution(e){this._contentResolution!==e&&(this._contentResolution=e,this._resetContent())}_disposeFacadeTexture(){this._facadeTexture&&(this._facadeTexture.dispose(),this._facadeTexture=null)}_resetContent(){this._disposeFacadeTexture(),this.content=this._content}_applyFacade(e){}}class Ow extends Mw{constructor(e){super(e)}_getTypeName(){return"AbstractButton3D"}_createNode(e){return new xn("button"+this.name,e)}}class Dw extends Ow{constructor(e,t){super(e),this._options={width:1,height:1,depth:.08,...t},this.pointerEnterAnimation=()=>{this.mesh&&(this._currentMaterial.emissiveColor=Ce.Red())},this.pointerOutAnimation=()=>{this._currentMaterial.emissiveColor=Ce.Black()},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_applyFacade(e){this._currentMaterial.emissiveTexture=e}_getTypeName(){return"Button3D"}_createNode(e){const t=new Array(6);for(let e=0;e<6;e++)t[e]=new _e(0,0,0,0);e.useRightHandedSystem?t[0].copyFromFloats(1,0,0,1):t[1].copyFromFloats(0,0,1,1);const i=yu(this.name+"_rootMesh",{width:this._options.width,height:this._options.height,depth:this._options.depth,faceUV:t,wrap:!0},e);return this._contentScaleRatioY=this._contentScaleRatio*this._options.width/this._options.height,this._setFacadeTextureScaling(),i}_affectMaterial(e){const t=new yc(this.name+"Material",e.getScene());t.specularColor=Ce.Black(),e.material=t,this._currentMaterial=t,this._resetContent()}dispose(){super.dispose(),this._disposeFacadeTexture(),this._currentMaterial&&this._currentMaterial.dispose()}}class ww extends Iw{get children(){return this._children}get blockLayout(){return this._blockLayout}set blockLayout(e){this._blockLayout!==e&&(this._blockLayout=e,this._blockLayout||this._arrangeChildren())}constructor(e){super(e),this._blockLayout=!1,this._children=new Array}updateLayout(){return this._arrangeChildren(),this}containsControl(e){return-1!==this._children.indexOf(e)}addControl(e){return-1!==this._children.indexOf(e)||(e.parent=this,e._host=this._host,this._children.push(e),this._host.utilityLayer&&(e._prepareNode(this._host.utilityLayer.utilityLayerScene),e.node&&(e.node.parent=this.node),this.blockLayout||this._arrangeChildren())),this}_arrangeChildren(){}_createNode(e){return new xn("ContainerNode",e)}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null,e._disposeNode()),this}_getTypeName(){return"Container3D"}dispose(){for(const e of this._children)e.dispose();this._children.length=0,super.dispose()}}ww.UNSET_ORIENTATION=0,ww.FACEORIGIN_ORIENTATION=1,ww.FACEORIGINREVERSED_ORIENTATION=2,ww.FACEFORWARD_ORIENTATION=3,ww.FACEFORWARDREVERSED_ORIENTATION=4;class Nw extends ww{get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}get columns(){return this._columns}set columns(e){this._columns!==e&&(this._columns=e,this._rowThenColum=!0,hs.SetImmediate((()=>{this._arrangeChildren()})))}get rows(){return this._rows}set rows(e){this._rows!==e&&(this._rows=e,this._rowThenColum=!1,hs.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e){super(e),this._columns=10,this._rows=0,this._rowThenColum=!0,this._orientation=ww.FACEORIGIN_ORIENTATION,this.margin=0}_arrangeChildren(){this._cellWidth=0,this._cellHeight=0;let e=0,t=0,i=0;const s=fe.Invert(this.node.computeWorldMatrix(!0));for(const e of this._children){if(!e.mesh)continue;i++,e.mesh.computeWorldMatrix(!0);const t=e.mesh.getHierarchyBoundingVectors(),r=ge.Vector3[0],n=ge.Vector3[1];t.max.subtractToRef(t.min,n),n.scaleInPlace(.5),de.TransformNormalToRef(n,s,r),this._cellWidth=Math.max(this._cellWidth,2*r.x),this._cellHeight=Math.max(this._cellHeight,2*r.y)}this._cellWidth+=2*this.margin,this._cellHeight+=2*this.margin,this._rowThenColum?(t=this._columns,e=Math.ceil(i/this._columns)):(e=this._rows,t=Math.ceil(i/this._rows));const r=.5*t*this._cellWidth,n=.5*e*this._cellHeight,o=[];let a=0;if(this._rowThenColum)for(let s=0;si));e++);else for(let s=0;si));t++);a=0;for(const e of this._children)e.mesh&&(this._mapGridNode(e,o[a]),a++);this._finalProcessing()}_finalProcessing(){}}class Fw extends Nw{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._cylindricalMapping(t);switch(e.position=s,this.orientation){case ww.FACEORIGIN_ORIENTATION:i.lookAt(new de(2*s.x,s.y,2*s.z));break;case ww.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new de(-s.x,s.y,-s.z));break;case ww.FACEFORWARD_ORIENTATION:break;case ww.FACEFORWARDREVERSED_ORIENTATION:i.rotate(_r.Y,Math.PI,lr.LOCAL)}}_cylindricalMapping(e){const t=new de(0,e.y,this._radius),i=e.x/this._radius;return fe.RotationYawPitchRollToRef(i,0,0,ge.Matrix[0]),de.TransformNormal(t,ge.Matrix[0])}}bi.ShadersStore.fluentVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 world;uniform mat4 viewProjection;varying vec2 vUV;\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float borderWidth;uniform vec3 scaleFactor;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\n#endif\nvoid main(void) {vUV=uv;\n#ifdef BORDER\nvec3 scale=scaleFactor;float minScale=min(min(scale.x,scale.y),scale.z);float maxScale=max(max(scale.x,scale.y),scale.z);float minOverMiddleScale=minScale/(scale.x+scale.y+scale.z-minScale-maxScale);float areaYZ=scale.y*scale.z;float areaXZ=scale.x*scale.z;float areaXY=scale.x*scale.y;float scaledBorderWidth=borderWidth; \nif (abs(normal.x)==1.0) \n{scale.x=scale.y;scale.y=scale.z;if (areaYZ>areaXZ && areaYZ>areaXY)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse if (abs(normal.y)==1.0) \n{scale.x=scale.z;if (areaXZ>areaXY && areaXZ>areaYZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse \n{if (areaXY>areaYZ && areaXY>areaXZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);if (scale.x>scale.y)\n{scaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);scaleInfo.y=1.0-scaledBorderWidth;}\nelse\n{scaleInfo.x=1.0-scaledBorderWidth;scaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);} \n#endif \nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;}\n";bi.ShadersStore.fluentPixelShader="precision highp float;varying vec2 vUV;uniform vec4 albedoColor;\n#ifdef INNERGLOW\nuniform vec4 innerGlowColor;\n#endif\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float edgeSmoothingValue;uniform float borderMinValue;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;uniform vec3 hoverPosition;uniform vec4 hoverColor;uniform float hoverRadius;\n#endif\n#ifdef TEXTURE\nuniform sampler2D albedoSampler;uniform mat4 textureMatrix;vec2 finalUV;\n#endif\nvoid main(void) {vec3 albedo=albedoColor.rgb;float alpha=albedoColor.a;\n#ifdef TEXTURE\nfinalUV=vec2(textureMatrix*vec4(vUV,1.0,0.0));albedo=texture2D(albedoSampler,finalUV).rgb;\n#endif\n#ifdef HOVERLIGHT\nfloat pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;albedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.);\n#else\nfloat pointToHover=1.0;\n#endif\n#ifdef BORDER \nfloat borderPower=10.0;float inverseBorderPower=1.0/borderPower;vec3 borderColor=albedo*borderPower;vec2 distanceToEdge;distanceToEdge.x=abs(vUV.x-0.5)*2.0;distanceToEdge.y=abs(vUV.y-0.5)*2.0;float borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x),\nsmoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));borderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover); \nalbedo+=borderColor;alpha=max(alpha,borderValue);\n#endif\n#ifdef INNERGLOW\nvec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);uvGlow=uvGlow*uvGlow;uvGlow=uvGlow*uvGlow;albedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y); \n#endif\ngl_FragColor=vec4(albedo,alpha);}";class Bw extends Oa{constructor(){super(),this.INNERGLOW=!1,this.BORDER=!1,this.HOVERLIGHT=!1,this.TEXTURE=!1,this.rebuild()}}class Lw extends Ra{constructor(e,t){super(e,t),this.innerGlowColorIntensity=.5,this.innerGlowColor=new Ce(1,1,1),this.albedoColor=new Ce(.3,.35,.4),this.renderBorders=!1,this.borderWidth=.5,this.edgeSmoothingValue=.02,this.borderMinValue=.1,this.renderHoverLight=!1,this.hoverRadius=.01,this.hoverColor=new Ee(.3,.3,.3,1),this.hoverPosition=de.Zero()}needAlphaBlending(){return 1!==this.alpha}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new Bw);const s=this.getScene(),r=t.materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&r._renderId===s.getRenderId())return!0;if(r._areTexturesDirty)if(r.INNERGLOW=this.innerGlowColorIntensity>0,r.BORDER=this.renderBorders,r.HOVERLIGHT=this.renderHoverLight,this._albedoTexture){if(!this._albedoTexture.isReadyOrNotBlocking())return!1;r.TEXTURE=!0}else r.TEXTURE=!1;const n=s.getEngine();if(r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=[ys.PositionKind];e.push(ys.NormalKind),e.push(ys.UVKind);const i="fluent",o=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius","textureMatrix"],a=["albedoSampler"],l=[];co({uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:r,maxSimultaneousLights:4});const h=r.toString();t.setEffect(s.getEngine().createEffect(i,{attributes:e,uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:h,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n,i)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),r.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),r.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),t.getBoundingInfo().boundingBox.extendSize.multiplyToRef(t.scaling,ge.Vector3[0]),this._activeEffect.setVector3("scaleFactor",ge.Vector3[0])),r.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition)),r.TEXTURE&&this._albedoTexture)){this._activeEffect.setTexture("albedoSampler",this._albedoTexture);const e=this._albedoTexture.getTextureMatrix();this._activeEffect.setMatrix("textureMatrix",e)}this._afterBind(t,this._activeEffect,i)}}getActiveTextures(){return super.getActiveTextures()}hasTexture(e){return!!super.hasTexture(e)}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new Lw(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GUI.FluentMaterial",e}getClassName(){return"FluentMaterial"}static Parse(e,t,i){return yt.Parse((()=>new Lw(e.name,t)),e,t,i)}}qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Lw.prototype,"innerGlowColorIntensity",void 0),qe([nt()],Lw.prototype,"innerGlowColor",void 0),qe([nt()],Lw.prototype,"albedoColor",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Lw.prototype,"renderBorders",void 0),qe([st()],Lw.prototype,"borderWidth",void 0),qe([st()],Lw.prototype,"edgeSmoothingValue",void 0),qe([st()],Lw.prototype,"borderMinValue",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Lw.prototype,"renderHoverLight",void 0),qe([st()],Lw.prototype,"hoverRadius",void 0),qe([ut()],Lw.prototype,"hoverColor",void 0),qe([lt()],Lw.prototype,"hoverPosition",void 0),qe([rt("albedoTexture")],Lw.prototype,"_albedoTexture",void 0),qe([it("_markAllSubMeshesAsTexturesAndMiscDirty")],Lw.prototype,"albedoTexture",void 0),ee("BABYLON.GUI.FluentMaterial",Lw);class kw extends Nw{get backPlateMargin(){return this._backPlateMargin}set backPlateMargin(e){this._backPlateMargin=e,this._children.length>=1&&(this.children.forEach((e=>{this._updateCurrentMinMax(e.position)})),this._updateMargins())}_createNode(e){const t=new bo(`menu_${this.name}`,e);return this._backPlate=yu("backPlate"+this.name,{size:1},e),this._backPlate.parent=t,t}_affectMaterial(e){this._backPlateMaterial=new Lw(this.name+"backPlateMaterial",e.getScene()),this._backPlateMaterial.albedoColor=new Ce(.08,.15,.55),this._backPlateMaterial.renderBorders=!0,this._backPlateMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backPlateMaterial.hoverPosition=e,this._backPlateMaterial.hoverColor.a=1):this._backPlateMaterial.hoverColor.a=0})),this._backPlate.material=this._backPlateMaterial}_mapGridNode(e,t){e.mesh&&(e.position=t.clone(),this._updateCurrentMinMax(t))}_finalProcessing(){this._updateMargins()}_updateCurrentMinMax(e){this._currentMin||(this._currentMin=e.clone(),this._currentMax=e.clone()),this._currentMin.minimizeInPlace(e),this._currentMax.maximizeInPlace(e)}_updateMargins(){if(this._children.length>0){this._currentMin.addInPlaceFromFloats(-this._cellWidth/2,-this._cellHeight/2,0),this._currentMax.addInPlaceFromFloats(this._cellWidth/2,this._cellHeight/2,0);const e=this._currentMax.subtract(this._currentMin);this._backPlate.scaling.x=e.x+this._cellWidth*this.backPlateMargin,this._backPlate.scaling.y=e.y+this._cellHeight*this.backPlateMargin,this._backPlate.scaling.z=.001;for(let t=0;t0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Pick_Radius_B144(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid main()\n{vec3 Nrm_World_Q128;Nrm_World_Q128=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q131;vec3 Tangent_World_N_Q131;float Tangent_Length_Q131;Tangent_World_Q131=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q131=length(Tangent_World_Q131);Tangent_World_N_Q131=Tangent_World_Q131/Tangent_Length_Q131;vec3 Binormal_World_Q132;vec3 Binormal_World_N_Q132;float Binormal_Length_Q132;Object_To_World_Dir_B132(vec3(0,1,0),Binormal_World_Q132,Binormal_World_N_Q132,Binormal_Length_Q132);float Anisotropy_Q133=Tangent_Length_Q131/Binormal_Length_Q132;vec3 Result_Q177;Result_Q177=mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(_Use_Global_Left_Index_));vec3 Result_Q178;Result_Q178=mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(_Use_Global_Right_Index_));float Result_Q144;Pick_Radius_B144(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q144);vec3 Dir_Q140;PickDir_B140(_Angle_,Tangent_World_N_Q131,Binormal_World_N_Q132,Dir_Q140);float Radius_Q147;float Line_Width_Q147;RelativeOrAbsoluteDetail_B147(Result_Q144,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q132,Radius_Q147,Line_Width_Q147);vec4 Out_Color_Q145=vec4(Radius_Q147,Line_Width_Q147,0,1);vec3 New_P_Q129;vec2 New_UV_Q129;float Radial_Gradient_Q129;vec3 Radial_Dir_Q129;Move_Verts_B129(Anisotropy_Q133,position,Radius_Q147,New_P_Q129,New_UV_Q129,Radial_Gradient_Q129,Radial_Dir_Q129);vec3 Pos_World_Q115;Object_To_World_Pos_B115(New_P_Q129,Pos_World_Q115);vec4 Blob_Info_Q180;\n#if BLOB_ENABLE\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q177,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q180);\n#else\nBlob_Info_Q180=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q181;\n#if BLOB_ENABLE_2\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q178,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q181);\n#else\nBlob_Info_Q181=vec4(0,0,0,0);\n#endif\nfloat Gradient1_Q130;float Gradient2_Q130;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B130(Pos_World_Q115,position,normal,cameraPosition,Radial_Gradient_Q129,Radial_Dir_Q129,tangent,Gradient1_Q130,Gradient2_Q130);\n#else\nGradient1_Q130=1.0;Gradient2_Q130=1.0;\n#endif\nvec2 Rect_UV_Q139;vec4 Rect_Parms_Q139;vec2 Scale_XY_Q139;vec2 Line_UV_Q139;Round_Rect_Vertex_B139(New_UV_Q129,Radius_Q147,0.0,Anisotropy_Q133,Gradient1_Q130,Gradient2_Q130,Rect_UV_Q139,Rect_Parms_Q139,Scale_XY_Q139,Line_UV_Q139);vec3 Line_Vertex_Q135;Line_Vertex_B135(Scale_XY_Q139,Line_UV_Q139,0.0,_Rate_,_Highlight_Transform_,Line_Vertex_Q135);vec3 Position=Pos_World_Q115;vec3 Normal=Dir_Q140;vec2 UV=Rect_UV_Q139;vec3 Tangent=Line_Vertex_Q135;vec3 Binormal=Nrm_World_Q128;vec4 Color=Out_Color_Q145;vec4 Extra1=Rect_Parms_Q139;vec4 Extra2=Blob_Info_Q180;vec4 Extra3=Blob_Info_Q181;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class Uw extends Oa{constructor(){super(),this.BLOB_ENABLE=!0,this.BLOB_ENABLE_2=!0,this.SMOOTH_EDGES=!0,this.IRIDESCENT_MAP_ENABLE=!0,this._needNormals=!0,this.rebuild()}}class Gw extends Ra{constructor(e,t){super(e,t),this.radius=.03,this.lineWidth=.01,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Ee(.0392157,.0666667,.207843,1),this.lineColor=new Ee(.14902,.133333,.384314,1),this.blobIntensity=.98,this.blobFarSize=.04,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.blobNearSize=.22,this.blobPulse=0,this.blobFade=0,this.blobNearSize2=.22,this.blobPulse2=0,this.blobFade2=0,this._rate=.135,this.highlightColor=new Ee(.98,.98,.98,1),this.highlightWidth=.25,this._highlightTransform=new _e(1,1,0,0),this._highlight=1,this.iridescenceIntensity=0,this.iridescenceEdgeIntensity=1,this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.globalLeftIndexTipPosition=de.Zero(),this._globalLeftIndexTipPosition4=_e.Zero(),this.globalRightIndexTipPosition=de.Zero(),this._globalRightIndexTipPosition4=_e.Zero(),this.alphaMode=Yd.ALPHA_DISABLE,this.backFaceCulling=!1,this._blobTexture=new Vo(Gw.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE),this._iridescentMap=new Vo(Gw.IM_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new Uw);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="fluentBackplate",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Angle_","_Fade_Out_","_Reflected_","_Frequency_","_Vertical_Offset_","_Iridescent_Map_","_Use_Global_Left_Index_","_Use_Global_Right_Index_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position"],h=["_Blob_Texture_","_Iridescent_Map_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera?.position??de.ZeroReadOnly),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",1),this._activeEffect.setFloat("_Radius_Top_Right_",1),this._activeEffect.setFloat("_Radius_Bottom_Left_",1),this._activeEffect.setFloat("_Radius_Bottom_Right_",1),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMap),this._activeEffect.setFloat("_Use_Global_Left_Index_",1),this._activeEffect.setFloat("_Use_Global_Right_Index_",1),this._globalLeftIndexTipPosition4.set(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this._globalLeftIndexTipPosition4),this._globalRightIndexTipPosition4.set(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this._globalRightIndexTipPosition4),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._blobTexture.dispose(),this._iridescentMap.dispose()}clone(e){return yt.Clone((()=>new Gw(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentBackplateMaterial",e}getClassName(){return"FluentBackplateMaterial"}static Parse(e,t,i){return yt.Parse((()=>new Gw(e.name,t)),e,t,i)}}Gw.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-blob.png",Gw.IM_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-iridescence.png",qe([st()],Gw.prototype,"radius",void 0),qe([st()],Gw.prototype,"lineWidth",void 0),qe([st()],Gw.prototype,"absoluteSizes",void 0),qe([st()],Gw.prototype,"baseColor",void 0),qe([st()],Gw.prototype,"lineColor",void 0),qe([st()],Gw.prototype,"blobIntensity",void 0),qe([st()],Gw.prototype,"blobFarSize",void 0),qe([st()],Gw.prototype,"blobNearDistance",void 0),qe([st()],Gw.prototype,"blobFarDistance",void 0),qe([st()],Gw.prototype,"blobFadeLength",void 0),qe([st()],Gw.prototype,"blobNearSize",void 0),qe([st()],Gw.prototype,"blobPulse",void 0),qe([st()],Gw.prototype,"blobFade",void 0),qe([st()],Gw.prototype,"blobNearSize2",void 0),qe([st()],Gw.prototype,"blobPulse2",void 0),qe([st()],Gw.prototype,"blobFade2",void 0),qe([st()],Gw.prototype,"highlightColor",void 0),qe([st()],Gw.prototype,"highlightWidth",void 0),qe([st()],Gw.prototype,"iridescenceIntensity",void 0),qe([st()],Gw.prototype,"iridescenceEdgeIntensity",void 0),qe([st()],Gw.prototype,"fadeOut",void 0),qe([lt()],Gw.prototype,"globalLeftIndexTipPosition",void 0),qe([lt()],Gw.prototype,"globalRightIndexTipPosition",void 0),ee("BABYLON.GUI.FluentBackplateMaterial",Gw);class zw extends Iw{set renderingGroupId(e){this._model.renderingGroupId=e}get renderingGroupId(){return this._model.renderingGroupId}get material(){return this._material}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=t}_getTypeName(){return"HolographicBackplate"}_createNode(e){const t=yu((this.name??"HolographicBackplate")+"_CollisionMesh",{width:1,height:1,depth:1},e);return t.isPickable=!0,t.visibility=0,Pa.ImportMeshAsync(void 0,zw.MODEL_BASE_URL,zw.MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_frontPlate`,i.isPickable=!1,i.parent=t,this._material&&(i.material=this._material),this._model=i})),t}_createMaterial(e){this._material=new Gw(this.name+" Material",e.getScene())}_affectMaterial(e){this._shareMaterials?this._host._touchSharedMaterials.fluentBackplateMaterial?this._material=this._host._touchSharedMaterials.fluentBackplateMaterial:(this._createMaterial(e),this._host._touchSharedMaterials.fluentBackplateMaterial=this._material):this._createMaterial(e)}dispose(){super.dispose(),this.shareMaterials||this._material.dispose(),this._model.dispose()}}zw.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",zw.MODEL_FILENAME="mrtk-fluent-backplate.glb";class Ww extends Dw{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=ta("",{size:1},this._backPlate._scene);const t=ta("",{size:1,sideOrientation:bo.DOUBLESIDE},this._backPlate._scene),i=new yc("",this._backPlate._scene);i.diffuseColor=Ce.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=de.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=de.Up().scale(.7).add(de.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=Cw.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new UD,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new qo,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!0)},this.pointerOutAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!1)}}_getTypeName(){return"HolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new WD;if(e.isVertical=!0,Vt()&&document.createElement&&this._imageUrl){const t=new GD;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new UD;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this._frontPlate&&(this.content=e)}_createNode(e){return this._backPlate=yu(this.name+"BackMesh",{width:1,height:1,depth:.08},e),this._frontPlate=yu(this.name+"FrontMesh",{width:1,height:1,depth:.08},e),this._frontPlate.parent=this._backPlate,this._frontPlate.position=de.Forward(e.useRightHandedSystem).scale(-.08),this._frontPlate.isPickable=!1,this._frontPlate.setEnabled(!1),this._textPlate=super._createNode(e),this._textPlate.parent=this._backPlate,this._textPlate.position=de.Forward(e.useRightHandedSystem).scale(-.08),this._textPlate.isPickable=!1,this._backPlate}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e}_createBackMaterial(e){this._backMaterial=new Lw(this.name+"Back Material",e.getScene()),this._backMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backMaterial.hoverPosition=e,this._backMaterial.hoverColor.a=1):this._backMaterial.hoverColor.a=0}))}_createFrontMaterial(e){this._frontMaterial=new Lw(this.name+"Front Material",e.getScene()),this._frontMaterial.innerGlowColorIntensity=0,this._frontMaterial.alpha=.5,this._frontMaterial.renderBorders=!0}_createPlateMaterial(e){this._plateMaterial=new yc(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ce.Black()}_affectMaterial(e){this._shareMaterials?(this._host._sharedMaterials.backFluentMaterial?this._backMaterial=this._host._sharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._sharedMaterials.backFluentMaterial=this._backMaterial),this._host._sharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._sharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._sharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._frontPlate.material=this._frontMaterial,this._textPlate.material=this._plateMaterial,this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}bi.ShadersStore.fluentButtonPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform bool _Relative_Width_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool Enable_Fade;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool _Use_Blob_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Holo_Edge_Fragment_B35(\nvec4 Edges,\nfloat Edge_Width,\nout float NotEdge)\n{vec2 c=vec2(min(Edges.r,Edges.g),min(Edges.b,Edges.a));vec2 df=fwidth(c)*Edge_Width;vec2 g=clamp(c/df,0.0,1.0);NotEdge=g.x*g.y;}\nvoid Blob_Fragment_B39(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvec2 FilterStep(vec2 Edge,vec2 X)\n{vec2 dX=max(fwidth(X),vec2(0.00001,0.00001));return clamp( (X+dX-max(Edge,X-dX))/(dX*2.0),0.0,1.0);}\nvoid Wireframe_Fragment_B59(\nvec3 Widths,\nvec2 UV,\nfloat Proximity,\nvec4 Edge_Color,\nout vec4 Wireframe)\n{vec2 c=min(UV,vec2(1.0,1.0)-UV);vec2 g=FilterStep(Widths.xy*0.5,c); \nWireframe=(1.0-min(g.x,g.y))*Proximity*Edge_Color;}\nvoid Proximity_B53(\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec3 Position,\nvec3 Show_Selection,\nvec4 Extra1,\nfloat Dist_To_Face,\nfloat Intensity,\nout float Proximity)\n{vec2 delta1=Extra1.xy;vec2 delta2=Extra1.zw;float d2=sqrt(min(dot(delta1,delta1),dot(delta2,delta2))+Dist_To_Face*Dist_To_Face);Proximity=Intensity*Proximity_Max_Intensity*(1.0-clamp(d2/Proximity_Near_Radius,0.0,1.0))*(1.0-Show_Selection.x)+Show_Selection.x;}\nvoid To_XYZ_B46(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid main()\n{float NotEdge_Q35;\n#if ENABLE_FADE\nHolo_Edge_Fragment_B35(vColor,_Fade_Width_,NotEdge_Q35);\n#else\nNotEdge_Q35=1.0;\n#endif\nvec4 Blob_Color_Q39;float k=dot(vUV,vUV);vec2 blobTextureCoord=vec2(vec2(sqrt(k),vTangent.x).x,1.0-vec2(sqrt(k),vTangent.x).y);vec4 blobColor=mix(vec4(1.0,1.0,1.0,1.0)*step(1.0-vTangent.x,clamp(sqrt(k)+0.1,0.0,1.0)),texture(_Blob_Texture_,blobTextureCoord),float(_Use_Blob_Texture_));Blob_Color_Q39=vTangent.y*blobColor*(1.0-clamp(k,0.0,1.0));float Is_Quad_Q24;Is_Quad_Q24=vNormal.z;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));float X_Q46;float Y_Q46;float Z_Q46;To_XYZ_B46(vBinormal,X_Q46,Y_Q46,Z_Q46);float Proximity_Q53;Proximity_B53(Blob_Position_Q41,Blob_Position_Q42,_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vPosition,vBinormal,vExtra1,Y_Q46,Z_Q46,Proximity_Q53);vec4 Wireframe_Q59;Wireframe_Fragment_B59(vNormal,vUV,Proximity_Q53,_Edge_Color_,Wireframe_Q59);vec4 Wire_Or_Blob_Q23=mix(Wireframe_Q59,Blob_Color_Q39,Is_Quad_Q24);vec4 Result_Q22;Result_Q22=mix(Wire_Or_Blob_Q23,vec4(0.3,0.3,0.3,0.3),float(_Show_Frame_));vec4 Final_Color_Q37=NotEdge_Q35*Result_Q22;vec4 Out_Color=Final_Color_Q37;float Clip_Threshold=0.0;bool To_sRGB=false;gl_FragColor=Out_Color;}";bi.ShadersStore.fluentButtonVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool _Enable_Fade_;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;void Blob_Vertex_B47(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nvec3 Active_Face_Center,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal);Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B66(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Up,\nout vec4 Extra1,\nout float Distance_To_Face,\nout float Intensity)\n{vec3 Active_Face_Dir_X=normalize(cross(Active_Face_Dir,Up));vec3 Active_Face_Dir_Y=cross(Active_Face_Dir,Active_Face_Dir_X);float distz1,distz2;Extra1.xy=ProjectProximity(Blob_Position,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz1)/Relative_Scale;Extra1.zw=ProjectProximity(Blob_Position_2,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz2)/Relative_Scale;Distance_To_Face=dot(Active_Face_Dir,Position-Active_Face_Center);Intensity=1.0-clamp(min(distz1,distz2)/Proximity_Far_Distance,0.0,1.0);}\nvoid Holo_Edge_Vertex_B44(\nvec3 Incident,\nvec3 Normal,\nvec2 UV,\nvec3 Tangent,\nvec3 Bitangent,\nbool Smooth_Active_Face,\nfloat Active,\nout vec4 Holo_Edges)\n{float NdotI=dot(Incident,Normal);vec2 flip=(UV-vec2(0.5,0.5));float udot=dot(Incident,Tangent)*flip.x*NdotI;float uval=1.0-float(udot>0.0);float vdot=-dot(Incident,Bitangent)*flip.y*NdotI;float vval=1.0-float(vdot>0.0);float Smooth_And_Active=step(1.0,float(Smooth_Active_Face && Active>0.0));uval=mix(uval,max(1.0,uval),Smooth_And_Active); \nvval=mix(vval,max(1.0,vval),Smooth_And_Active);Holo_Edges=vec4(1.0,1.0,1.0,1.0)-vec4(uval*UV.x,uval*(1.0-UV.x),vval*UV.y,vval*(1.0-UV.y));}\nvoid Object_To_World_Pos_B13(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B38(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=float(Blob_Enable_1);float b2=float(Blob_Enable_2);Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Wireframe_Vertex_B51(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Edge_Width,\nvec2 Face_Size,\nout vec3 Wire_Vx_Pos,\nout vec2 UV,\nout vec2 Widths)\n{Widths.xy=Edge_Width/Face_Size;float x=dot(Position,Tangent);float y=dot(Position,Bitangent);float dx=0.5-abs(x);float newx=(0.5-dx*Widths.x*2.0)*sign(x);float dy=0.5-abs(y);float newy=(0.5-dy*Widths.y*2.0)*sign(y);Wire_Vx_Pos=Normal*0.5+newx*Tangent+newy*Bitangent;UV.x=dot(Wire_Vx_Pos,Tangent)+0.5;UV.y=dot(Wire_Vx_Pos,Bitangent)+0.5;}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B48(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float Active=max(0.0,dot(Active_Face_Dir,Normal));Show_Selection=mix(max(select1,select2),1.0,Selected)*Active;}\nvoid Proximity_Visibility_B54(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Input_Width,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nout float Width)\n{vec3 boxEdges=(world*vec4(vec3(0.5,0.5,0.5),0.0)).xyz;float boxMaxSize=length(boxEdges);float d1=dot(Proximity_Center-Active_Face_Center,Active_Face_Dir);vec3 blob1=Proximity_Center-d1*Active_Face_Dir;float d2=dot(Proximity_Center_2-Active_Face_Center,Active_Face_Dir);vec3 blob2=Proximity_Center_2-d2*Active_Face_Dir;vec3 delta1=blob1-Active_Face_Center;vec3 delta2=blob2-Active_Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=Input_Width*(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));}\nvoid Object_To_World_Dir_B67(\nvec3 Dir_Object,\nout vec3 Dir_World)\n{Dir_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid main()\n{vec3 Active_Face_Center_Q49;Active_Face_Center_Q49=(world*vec4(_Active_Face_Dir_*0.5,1.0)).xyz;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));vec3 Active_Face_Dir_Q64=normalize((world*vec4(_Active_Face_Dir_,0.0)).xyz);float Relative_Scale_Q57;\n#if RELATIVE_WIDTH\nRelative_Scale_Q57=length((world*vec4(vec3(0,1,0),0.0)).xyz);\n#else\nRelative_Scale_Q57=1.0;\n#endif\nvec3 Tangent_World_Q30;Tangent_World_Q30=(world*vec4(tangent,0.0)).xyz;vec3 Binormal_World_Q31;Binormal_World_Q31=(world*vec4((cross(normal,tangent)),0.0)).xyz;vec3 Normal_World_Q60;Normal_World_Q60=(world*vec4(normal,0.0)).xyz;vec3 Result_Q18=0.5*normal;vec3 Dir_World_Q67;Object_To_World_Dir_B67(_Active_Face_Up_,Dir_World_Q67);float Product_Q56=_Edge_Width_*Relative_Scale_Q57;vec3 Normal_World_N_Q29=normalize(Normal_World_Q60);vec3 Tangent_World_N_Q28=normalize(Tangent_World_Q30);vec3 Binormal_World_N_Q32=normalize(Binormal_World_Q31);vec3 Position_Q38;float Near_Size_Q38;float Inner_Fade_Q38;float Blob_Enable_Q38;float Fade_Q38;float Pulse_Q38;Choose_Blob_B38(color,Blob_Position_Q41,Blob_Position_Q42,_Blob_Enable_,_Blob_Enable_2_,_Blob_Near_Size_,_Blob_Near_Size_2_,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q38,Near_Size_Q38,Inner_Fade_Q38,Blob_Enable_Q38,Fade_Q38,Pulse_Q38);vec3 Face_Center_Q33;Face_Center_Q33=(world*vec4(Result_Q18,1.0)).xyz;vec2 Face_Size_Q50=vec2(length(Tangent_World_Q30),length(Binormal_World_Q31));float Show_Selection_Q48;Selection_Vertex_B48(Blob_Position_Q41,Blob_Position_Q42,Face_Center_Q33,Face_Size_Q50,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,Active_Face_Dir_Q64,Show_Selection_Q48);vec3 Normalized_Q72=normalize(Dir_World_Q67);float Active_Q34=max(0.0,dot(Active_Face_Dir_Q64,Normal_World_N_Q29));float Width_Q54;Proximity_Visibility_B54(Show_Selection_Q48,Blob_Position_Q41,Blob_Position_Q42,Product_Q56,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Active_Face_Center_Q49,Active_Face_Dir_Q64,Width_Q54);vec3 Wire_Vx_Pos_Q51;vec2 UV_Q51;vec2 Widths_Q51;Wireframe_Vertex_B51(position,normal,tangent,(cross(normal,tangent)),Width_Q54,Face_Size_Q50,Wire_Vx_Pos_Q51,UV_Q51,Widths_Q51);vec3 Vec3_Q27=vec3(Widths_Q51.x,Widths_Q51.y,color.r);vec3 Pos_World_Q13;Object_To_World_Pos_B13(Wire_Vx_Pos_Q51,Pos_World_Q13);vec3 Incident_Q36=normalize(Pos_World_Q13-cameraPosition);vec3 Out_Position_Q47;vec2 Out_UV_Q47;vec3 Blob_Info_Q47;Blob_Vertex_B47(Pos_World_Q13,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,Position_Q38,_Blob_Intensity_,Near_Size_Q38,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q33,Face_Size_Q50,UV_Q51,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q38,Active_Face_Center_Q49,Pulse_Q38,Fade_Q38,Blob_Enable_Q38,Out_Position_Q47,Out_UV_Q47,Blob_Info_Q47);vec4 Extra1_Q66;float Distance_To_Face_Q66;float Intensity_Q66;Proximity_Vertex_B66(Blob_Position_Q41,Blob_Position_Q42,Active_Face_Center_Q49,Active_Face_Dir_Q64,Pos_World_Q13,_Proximity_Far_Distance_,Relative_Scale_Q57,_Proximity_Anisotropy_,Normalized_Q72,Extra1_Q66,Distance_To_Face_Q66,Intensity_Q66);vec4 Holo_Edges_Q44;Holo_Edge_Vertex_B44(Incident_Q36,Normal_World_N_Q29,uv,Tangent_World_Q30,Binormal_World_Q31,_Smooth_Active_Face_,Active_Q34,Holo_Edges_Q44);vec3 Vec3_Q19=vec3(Show_Selection_Q48,Distance_To_Face_Q66,Intensity_Q66);vec3 Position=Out_Position_Q47;vec2 UV=Out_UV_Q47;vec3 Tangent=Blob_Info_Q47;vec3 Binormal=Vec3_Q19;vec3 Normal=Vec3_Q27;vec4 Extra1=Extra1_Q66;vec4 Color=Holo_Edges_Q44;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;}";class Hw extends Oa{constructor(){super(),this.RELATIVE_WIDTH=!0,this.ENABLE_FADE=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class Xw extends Ra{constructor(e,t){super(e,t),this.edgeWidth=.04,this.edgeColor=new Ee(.592157,.592157,.592157,1),this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=1.5,this.proximityAnisotropy=1,this.selectionFuzz=.5,this.selected=0,this.selectionFade=0,this.selectionFadeSize=.3,this.selectedDistance=.08,this.selectedFadeLength=.08,this.blobIntensity=.5,this.blobFarSize=.05,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.leftBlobEnable=!0,this.leftBlobNearSize=.025,this.leftBlobPulse=0,this.leftBlobFade=1,this.leftBlobInnerFade=.01,this.rightBlobEnable=!0,this.rightBlobNearSize=.025,this.rightBlobPulse=0,this.rightBlobFade=1,this.rightBlobInnerFade=.01,this.activeFaceDir=new de(0,0,-1),this.activeFaceUp=new de(0,1,0),this.enableFade=!0,this.fadeWidth=1.5,this.smoothActiveFace=!0,this.showFrame=!1,this.useBlobTexture=!0,this.globalLeftIndexTipPosition=de.Zero(),this.globalRightIndexTipPosition=de.Zero(),this.alphaMode=Yd.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Vo(Xw.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new Hw);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!0,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="fluentButton",a=s.toString(),l=["world","viewProjection","cameraPosition","_Edge_Width_","_Edge_Color_","_Relative_Width_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Active_Face_Dir_","_Active_Face_Up_","_Enable_Fade_","_Fade_Width_","_Smooth_Active_Face_","_Show_Frame_","_Use_Blob_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Blob_Texture_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setColor4("_Edge_Color_",new Ce(this.edgeColor.r,this.edgeColor.g,this.edgeColor.b),this.edgeColor.a),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Blob_Enable_",this.leftBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.leftBlobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.leftBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.leftBlobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.leftBlobFade),this._activeEffect.setFloat("_Blob_Enable_2_",this.rightBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.rightBlobNearSize),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.rightBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_2_",this.rightBlobPulse),this._activeEffect.setFloat("_Blob_Fade_2_",this.rightBlobFade),this._activeEffect.setVector3("_Active_Face_Dir_",this.activeFaceDir),this._activeEffect.setVector3("_Active_Face_Up_",this.activeFaceUp),this._activeEffect.setFloat("_Fade_Width_",this.fadeWidth),this._activeEffect.setFloat("_Smooth_Active_Face_",this.smoothActiveFace?1:0),this._activeEffect.setFloat("_Show_Frame_",this.showFrame?1:0),this._activeEffect.setFloat("_Use_Blob_Texture_",this.useBlobTexture?1:0),this._activeEffect.setFloat("Use_Global_Left_Index",1),this._activeEffect.setFloat("Use_Global_Right_Index",1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",new _e(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1)),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",new _e(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new Xw(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentButtonMaterial",e}getClassName(){return"FluentButtonMaterial"}static Parse(e,t,i){return yt.Parse((()=>new Xw(e.name,t)),e,t,i)}}Xw.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-button-blob.png",qe([st()],Xw.prototype,"edgeWidth",void 0),qe([ut()],Xw.prototype,"edgeColor",void 0),qe([st()],Xw.prototype,"proximityMaxIntensity",void 0),qe([st()],Xw.prototype,"proximityFarDistance",void 0),qe([st()],Xw.prototype,"proximityNearRadius",void 0),qe([st()],Xw.prototype,"proximityAnisotropy",void 0),qe([st()],Xw.prototype,"selectionFuzz",void 0),qe([st()],Xw.prototype,"selected",void 0),qe([st()],Xw.prototype,"selectionFade",void 0),qe([st()],Xw.prototype,"selectionFadeSize",void 0),qe([st()],Xw.prototype,"selectedDistance",void 0),qe([st()],Xw.prototype,"selectedFadeLength",void 0),qe([st()],Xw.prototype,"blobIntensity",void 0),qe([st()],Xw.prototype,"blobFarSize",void 0),qe([st()],Xw.prototype,"blobNearDistance",void 0),qe([st()],Xw.prototype,"blobFarDistance",void 0),qe([st()],Xw.prototype,"blobFadeLength",void 0),qe([st()],Xw.prototype,"leftBlobEnable",void 0),qe([st()],Xw.prototype,"leftBlobNearSize",void 0),qe([st()],Xw.prototype,"leftBlobPulse",void 0),qe([st()],Xw.prototype,"leftBlobFade",void 0),qe([st()],Xw.prototype,"leftBlobInnerFade",void 0),qe([st()],Xw.prototype,"rightBlobEnable",void 0),qe([st()],Xw.prototype,"rightBlobNearSize",void 0),qe([st()],Xw.prototype,"rightBlobPulse",void 0),qe([st()],Xw.prototype,"rightBlobFade",void 0),qe([st()],Xw.prototype,"rightBlobInnerFade",void 0),qe([lt()],Xw.prototype,"activeFaceDir",void 0),qe([lt()],Xw.prototype,"activeFaceUp",void 0),qe([st()],Xw.prototype,"enableFade",void 0),qe([st()],Xw.prototype,"fadeWidth",void 0),qe([st()],Xw.prototype,"smoothActiveFace",void 0),qe([st()],Xw.prototype,"showFrame",void 0),qe([st()],Xw.prototype,"useBlobTexture",void 0),qe([lt()],Xw.prototype,"globalLeftIndexTipPosition",void 0),qe([lt()],Xw.prototype,"globalRightIndexTipPosition",void 0),ee("BABYLON.GUI.FluentButtonMaterial",Xw);class Yw extends Dw{constructor(e,t){super(e),this._isNearPressed=!1,this._interactionSurfaceHeight=0,this._isToggleButton=!1,this._toggleState=!1,this._toggleButtonCallback=()=>{this._onToggle(!this._toggleState)},this.onToggleObservable=new X,this.collidableFrontDirection=de.Zero(),t&&(this.collisionMesh=t)}get isActiveNearInteraction(){return this._isNearPressed}set collidableFrontDirection(e){if(this._collidableFrontDirection=e.normalize(),this._collisionMesh){const e=ge.Matrix[0];e.copyFrom(this._collisionMesh.getWorldMatrix()),e.invert(),de.TransformNormalToRef(this._collidableFrontDirection,e,this._collidableFrontDirection),this._collidableFrontDirection.normalize()}}get collidableFrontDirection(){if(this._collisionMesh){const e=ge.Vector3[0];return de.TransformNormalToRef(this._collidableFrontDirection,this._collisionMesh.getWorldMatrix(),e),e.normalize()}return this._collidableFrontDirection}set collisionMesh(e){this._collisionMesh&&(this._collisionMesh.isNearPickable=!1,this._collisionMesh.reservedDataStore?.GUI3D&&(this._collisionMesh.reservedDataStore.GUI3D={}),this._collisionMesh.getChildMeshes().forEach((e=>{e.isNearPickable=!1,e.reservedDataStore?.GUI3D&&(e.reservedDataStore.GUI3D={})}))),this._collisionMesh=e,this._injectGUI3DReservedDataStore(this._collisionMesh).control=this,this._collisionMesh.isNearPickable=!0,this._collisionMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this,e.isNearPickable=!0})),this.collidableFrontDirection=e.forward}set isToggleButton(e){e!==this._isToggleButton&&(this._isToggleButton=e,e?this.onPointerUpObservable.add(this._toggleButtonCallback):(this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this._toggleState&&this._onToggle(!1)))}get isToggleButton(){return this._isToggleButton}set isToggled(e){this._isToggleButton&&this._toggleState!==e&&this._onToggle(e)}get isToggled(){return this._toggleState}_onToggle(e){this._toggleState=e,this.onToggleObservable.notifyObservers(e)}_isInteractionInFrontOfButton(e){return this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition())>0}getPressDepth(e){if(!this._isNearPressed)return 0;const t=this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition());return this._interactionSurfaceHeight-t}_getInteractionHeight(e,t){const i=this.collidableFrontDirection;if(0===i.length())return de.Distance(e,t);const s=de.Dot(t,i);return de.Dot(e,i)-s}_generatePointerEventType(e,t,i){if(e===Ms.POINTERDOWN||e===Ms.POINTERMOVE){if(!this._isInteractionInFrontOfButton(t))return Ms.POINTERMOVE;this._isNearPressed=!0,this._interactionSurfaceHeight=this._getInteractionHeight(t,this._collisionMesh.getAbsolutePosition())}if(e===Ms.POINTERUP){if(0==i)return Ms.POINTERMOVE;this._isNearPressed=!1}return e}_getTypeName(){return"TouchButton3D"}_createNode(e){return super._createNode(e)}dispose(){super.dispose(),this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this.onToggleObservable.clear(),this._collisionMesh&&this._collisionMesh.dispose()}}class Qw extends Yw{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=ta("",{size:1},this._backPlate._scene);const t=ta("",{size:1,sideOrientation:bo.DOUBLESIDE},this._backPlate._scene),i=new yc("",this._backPlate._scene);i.diffuseColor=Ce.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=de.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=de.Up().scale(.7).add(de.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=Cw.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new UD,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new qo,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._isBackplateVisible=!0,this._frontPlateDepth=.5,this._backPlateDepth=.04,this._backplateColor=new Ce(.08,.15,.55),this._backplateToggledColor=new Ce(.25,.4,.95),this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontMaterial.leftBlobEnable=!0,this._frontMaterial.rightBlobEnable=!0},this.pointerOutAnimation=()=>{this._frontMaterial.leftBlobEnable=!1,this._frontMaterial.rightBlobEnable=!1},this.pointerDownAnimation=()=>{this._frontPlate&&!this.isActiveNearInteraction&&(this._frontPlate.scaling.z=.2*this._frontPlateDepth,this._frontPlate.position=de.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-.2*this._frontPlateDepth)/2),this._textPlate.position=de.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+.2*this._frontPlateDepth)/2))},this.pointerUpAnimation=()=>{this._frontPlate&&(this._frontPlate.scaling.z=this._frontPlateDepth,this._frontPlate.position=de.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-this._frontPlateDepth)/2),this._textPlate.position=de.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+this._frontPlateDepth)/2))},this.onPointerMoveObservable.add((e=>{if(this._frontPlate&&this.isActiveNearInteraction){const t=de.Zero();if(this._backPlate.getWorldMatrix().decompose(t,void 0,void 0)){let i=this._getInteractionHeight(e,this._backPlate.getAbsolutePosition())/t.z;i=xe.Clamp(i-this._backPlateDepth/2,.2*this._frontPlateDepth,this._frontPlateDepth),this._frontPlate.scaling.z=i,this._frontPlate.position=de.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-i)/2),this._textPlate.position=de.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+i)/2)}}})),this._pointerHoverObserver=this.onPointerMoveObservable.add((e=>{this._frontMaterial.globalLeftIndexTipPosition=e}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new WD;if(e.isVertical=!0,Vt()&&document.createElement&&this._imageUrl){const t=new GD;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new UD;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this.content=e}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=yu(`${this.name}_collisionMesh`,{width:1,height:1,depth:this._frontPlateDepth},e);t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=de.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),Pa.ImportMeshAsync(void 0,Qw.MODEL_BASE_URL,Qw.MODEL_FILENAME,e).then((i=>{const s=yu("${this.name}_alphaMesh",{width:1,height:1,depth:1},e);s.isPickable=!1,s.material=new yc("${this.name}_alphaMesh_material",e),s.material.alpha=.15;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.z=this._frontPlateDepth,s.parent=r,r.parent=t,this._frontMaterial&&(r.material=this._frontMaterial),this._frontPlate=r})),this._backPlate=yu(`${this.name}_backPlate`,{width:1,height:1,depth:this._backPlateDepth},e),this._backPlate.position=de.Forward(e.useRightHandedSystem).scale(this._backPlateDepth/2),this._backPlate.isPickable=!1,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.position=de.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),this._backPlate.addChild(t),this._backPlate.addChild(this._textPlate);const i=new xn("{this.name}_root",e);return this._backPlate.setParent(i),this.collisionMesh=t,this.collidableFrontDirection=this._backPlate.forward.negate(),i}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=new Ce(.4,.4,.4)}_createBackMaterial(e){this._backMaterial=new Lw(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.albedoColor=this._backplateColor,this._backMaterial.renderBorders=!0,this._backMaterial.renderHoverLight=!1}_createFrontMaterial(e){this._frontMaterial=new Xw(this.name+"Front Material",e.getScene())}_createPlateMaterial(e){this._plateMaterial=new yc(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ce.Black()}_onToggle(e){this._backMaterial&&(this._backMaterial.albedoColor=e?this._backplateToggledColor:this._backplateColor),super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.backFluentMaterial?this._backMaterial=this._host._touchSharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.backFluentMaterial=this._backMaterial),this._host._touchSharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._touchSharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerMoveObservable.remove(this._pointerHoverObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}Qw.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",Qw.MODEL_FILENAME="mrtk-fluent-button.glb";class jw{constructor(){this.followBehaviorEnabled=!1,this.sixDofDragBehaviorEnabled=!0,this.surfaceMagnetismBehaviorEnabled=!0,this._followBehavior=new la,this._sixDofDragBehavior=new oa,this._surfaceMagnetismBehavior=new aa}get name(){return"Default"}get followBehavior(){return this._followBehavior}get sixDofDragBehavior(){return this._sixDofDragBehavior}get surfaceMagnetismBehavior(){return this._surfaceMagnetismBehavior}init(){}attach(e,t,i){this._scene=e.getScene(),this.attachedNode=e,this._addObservables(),this._followBehavior.attach(e),this._sixDofDragBehavior.attach(e),this._sixDofDragBehavior.draggableMeshes=t||null,this._sixDofDragBehavior.faceCameraOnDragStart=!0,this._surfaceMagnetismBehavior.attach(e,this._scene),i&&(this._surfaceMagnetismBehavior.meshes=i),this._surfaceMagnetismBehavior.enabled=!1}detach(){this.attachedNode=null,this._removeObservables(),this._followBehavior.detach(),this._sixDofDragBehavior.detach(),this._surfaceMagnetismBehavior.detach()}_addObservables(){this._onBeforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{this._followBehavior._enabled=!this._sixDofDragBehavior.isMoving&&this.followBehaviorEnabled})),this._onDragObserver=this._sixDofDragBehavior.onDragObservable.add((e=>{this._sixDofDragBehavior.disableMovement=this._surfaceMagnetismBehavior.findAndUpdateTarget(e.pickInfo)}))}_removeObservables(){this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._sixDofDragBehavior.onDragObservable.remove(this._onDragObserver)}}bi.ShadersStore.handleVertexShader="precision highp float;attribute vec3 position;uniform vec3 positionOffset;uniform mat4 worldViewProjection;uniform float scale;void main(void) {vec4 vPos=vec4((vec3(position)+positionOffset)*scale,1.0);gl_Position=worldViewProjection*vPos;}";bi.ShadersStore.handlePixelShader="uniform vec3 color;void main(void) {gl_FragColor=vec4(color,1.0);}";class Kw extends Yu{get hover(){return this._hover}set hover(e){this._hover=e,this._updateInterpolationTarget()}get drag(){return this._drag}set drag(e){this._drag=e,this._updateInterpolationTarget()}constructor(e,t){super(e,t,"handle",{attributes:["position"],uniforms:["worldViewProjection","color","scale","positionOffset"],needAlphaBlending:!1,needAlphaTesting:!1}),this._hover=!1,this._drag=!1,this._color=new Ce,this._scale=1,this._lastTick=-1,this.animationLength=100,this.hoverColor=new Ce(0,.467,.84),this.baseColor=new Ce(1,1,1),this.hoverScale=.75,this.baseScale=.35,this.dragScale=.55,this._positionOffset=de.Zero(),this._updateInterpolationTarget(),this._lastTick=Date.now(),this._onBeforeRender=this.getScene().onBeforeRenderObservable.add((()=>{const e=Date.now(),t=e-this._lastTick,i=this._targetScale-this._scale,s=Ae.Color3[0].copyFrom(this._targetColor).subtractToRef(this._color,Ae.Color3[0]);this._scale=this._scale+i*t/this.animationLength,s.scaleToRef(t/this.animationLength,s),this._color.addToRef(s,this._color),this.setColor3("color",this._color),this.setFloat("scale",this._scale),this.setVector3("positionOffset",this._positionOffset),this._lastTick=e}))}_updateInterpolationTarget(){this.drag?(this._targetColor=this.hoverColor,this._targetScale=this.dragScale):this.hover?(this._targetColor=this.hoverColor,this._targetScale=this.hoverScale):(this._targetColor=this.baseColor,this._targetScale=this.baseScale)}dispose(){super.dispose(),this.getScene().onBeforeRenderObservable.remove(this._onBeforeRender)}}var $w;!function(e){e[e.IDLE=0]="IDLE",e[e.HOVER=1]="HOVER",e[e.DRAG=2]="DRAG"}($w||($w={}));class qw{get state(){return this._state}get gizmo(){return this._gizmo}set hover(e){e?this._state|=$w.HOVER:this._state&=~$w.HOVER,this._updateMaterial()}set drag(e){e?this._state|=$w.DRAG:this._state&=~$w.DRAG,this._updateMaterial()}constructor(e,t){this._state=$w.IDLE,this._materials=[],this._scene=t,this._gizmo=e,this.node=this.createNode(),this.node.reservedDataStore={handle:this}}_createMaterial(e){const t=new Kw("handle",this._scene);return e&&(t._positionOffset=e),t}_updateMaterial(){const e=this._state;for(const e of this._materials)e.hover=!1,e.drag=!1;if(e&$w.DRAG)for(const e of this._materials)e.drag=!0;else if(e&$w.HOVER)for(const e of this._materials)e.hover=!0}setDragBehavior(e,t,i){const s=new na;this._dragBehavior=s,this._dragStartObserver=s.onDragStartObservable.add(e),this._draggingObserver=s.onDragObservable.add(t),this._dragEndObserver=s.onDragEndObservable.add(i),this._dragBehavior.attach(this.node)}dispose(){this._dragBehavior.onDragStartObservable.remove(this._dragStartObserver),this._dragBehavior.onDragObservable.remove(this._draggingObserver),this._dragBehavior.onDragEndObservable.remove(this._dragEndObserver),this._dragBehavior.detach();for(const e of this._materials)e.dispose();this.node.dispose()}}class Zw extends qw{createNode(){const e=yu("sideVert",{width:1,height:10,depth:.1},this._scene),t=new xn("side",this._scene);e.parent=t;const i=this._createMaterial();return e.material=i,e.isNearGrabbable=!0,this._materials.push(i),t}}class Jw extends qw{createNode(){const e=yu("angleHor",{width:3,height:1,depth:.1},this._scene),t=yu("angleVert",{width:1,height:3,depth:.1},this._scene),i=new xn("angle",this._scene);return e.parent=i,t.parent=i,e.material=this._createMaterial(new de(1,0,0)),t.material=this._createMaterial(new de(0,1,0)),t.isNearGrabbable=!0,e.isNearGrabbable=!0,this._materials.push(e.material),this._materials.push(t.material),i}}class eN extends fu{set attachedSlate(e){e?(this.attachedMesh=e.mesh,this.updateBoundingBox(),this._pickedPointObserver=e._host.onPickingObservable.add((e=>{if(!this._handleHovered||e&&e.parent===this._handleHovered.node||(this._handleHovered.hover=!1,this._handleHovered=null),e&&e.parent&&e.parent.reservedDataStore&&e.parent.reservedDataStore.handle){const t=e.parent.reservedDataStore.handle;t.gizmo===this&&(this._handleHovered=t,this._handleHovered.hover=!0)}}))):this._attachedSlate&&this._attachedSlate._host.onPickingObservable.remove(this._pickedPointObserver),this._attachedSlate=e}get attachedSlate(){return this._attachedSlate}constructor(e){super(e),this._boundingDimensions=new de(0,0,0),this._renderObserver=null,this._tmpQuaternion=new pe,this._tmpVector=new de(0,0,0),this._corners=[],this._sides=[],this._boundingBoxGizmo={min:new de,max:new de},this._margin=.35,this._handleSize=.075,this._attachedSlate=null,this._existingSlateScale=new de,this.fixedScreenSize=!1,this.fixedScreenSizeDistanceFactor=10,this._createNode(),this.updateScale=!1,this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingSlateScale.equals(this.attachedMesh.scaling)&&this.updateBoundingBox()}))}_createNode(){this._handlesParent=new xn("handlesParent",this.gizmoLayer.utilityLayerScene),this._handlesParent.rotationQuaternion=pe.Identity();const e=[{dimensions:new de(-1,-1,0),origin:new de(1,0,0)},{dimensions:new de(1,-1,0),origin:new de(0,0,0)},{dimensions:new de(1,1,0),origin:new de(0,1,0)},{dimensions:new de(-1,1,0),origin:new de(1,1,0)}];for(let t=0;t<4;t++){const i=new Jw(this,this.gizmoLayer.utilityLayerScene);this._corners.push(i),i.node.rotation.z=Math.PI/2*t,i.node.parent=this._handlesParent,this._assignDragBehaviorCorners(i,((e,t,i,s)=>this._moveHandle(e,t,i,s,!0)),e[t])}for(let e=0;e<4;e++){const t=new Zw(this,this.gizmoLayer.utilityLayerScene);this._sides.push(t),t.node.rotation.z=Math.PI/2*e,t.node.parent=this._handlesParent,this._assignDragBehaviorSides(t,e%2==0?new de(0,1,0):new de(1,0,0))}this._handlesParent.parent=this._rootMesh}_keepAspectRatio(e,t,i=!1){const s=ge.Vector3[0];s.copyFromFloats(t,1,0).normalize(),i&&(s.y*=-1);const r=de.Dot(e,s);e.copyFrom(s).scaleInPlace(r)}_clampDimensions(e,t,i,s=!1){const r=ge.Vector3[0];r.copyFrom(e).multiplyInPlace(i);const n=ge.Vector3[1];if(n.copyFromFloats(Math.max(this._attachedSlate.minDimensions.x,r.x+t.x),Math.max(this._attachedSlate.minDimensions.y,r.y+t.y),0),s){const e=t.x/t.y;n.x=Math.max(n.x,n.y*e),n.y=Math.max(n.y,n.x/e)}r.copyFrom(n).subtractInPlace(t),e.x=Math.sign(e.x)*Math.abs(r.x),e.y=Math.sign(e.y)*Math.abs(r.y)}_moveHandle(e,t,i,s,r){if(!this._attachedSlate)return;if(r){const e=t.x/t.y;this._keepAspectRatio(i,e,s.dimensions.x*s.dimensions.y<0)}this._clampDimensions(i,t,s.dimensions,r);const n=ge.Vector3[0],o=ge.Vector3[1];n.copyFrom(i).multiplyInPlace(s.origin),o.copyFrom(i).multiplyInPlace(s.dimensions),this._attachedSlate.origin.copyFrom(e).addInPlace(n),this._attachedSlate.dimensions.set(t.x+o.x,t.y+o.y)}_assignDragBehaviorCorners(e,t,i){const s=new de,r=new de,n=new de,o=new fe,a=new de;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(s.set(this.attachedSlate.dimensions.x,this.attachedSlate.dimensions.y,K),r.copyFrom(this.attachedSlate.origin),n.copyFrom(e.position),o.copyFrom(this.attachedMesh.computeWorldMatrix(!0)),o.invert(),this.attachedSlate._followButton.isToggled=!1,de.TransformNormalToRef(de.Forward(),this.attachedMesh.getWorldMatrix(),a),a.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{this.attachedSlate&&this.attachedMesh&&(((e,t,i,s)=>{e.subtractToRef(i,ge.Vector3[0]);const r=de.Dot(ge.Vector3[0],t);ge.Vector3[1].copyFrom(t).scaleInPlace(r),ge.Vector3[0].subtractInPlace(ge.Vector3[1]),ge.Vector3[0].addToRef(i,s)})(e.position,a,n,this._tmpVector),this._tmpVector.subtractInPlace(n),de.TransformNormalToRef(this._tmpVector,o,this._tmpVector),t(r,s,this._tmpVector,i),this.attachedSlate._positionElements(),this.updateBoundingBox())}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_assignDragBehaviorSides(e,t){const i=new pe,s=new de,r=new de,n=new de,o=new de;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(i.copyFrom(this.attachedMesh.rotationQuaternion),s.copyFrom(e.position),n.copyFrom(this.attachedMesh.getAbsolutePivotPoint()),r.copyFrom(s).subtractInPlace(n).normalize(),this.attachedSlate._followButton.isToggled=!1,de.TransformNormalToRef(t,this.attachedMesh.getWorldMatrix(),o),o.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{if(this.attachedSlate&&this.attachedMesh){this._tmpVector.copyFrom(e.position),this._tmpVector.subtractInPlace(n),this._tmpVector.normalize();const s=-de.GetAngleBetweenVectorsOnPlane(this._tmpVector,r,o);pe.RotationAxisToRef(t,s,this._tmpQuaternion),i.multiplyToRef(this._tmpQuaternion,this.attachedMesh.rotationQuaternion)}}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_attachedNodeChanged(e){e&&this.updateBoundingBox()}updateBoundingBox(){if(this.attachedMesh){Jo._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=pe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._boundingBoxGizmo.min=t.min,this._boundingBoxGizmo.max=t.max,this._updateHandlesPosition(),this._updateHandlesScaling(),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),Jo._RestorePivotPoint(this.attachedMesh),this.attachedMesh.setParent(e),this.attachedMesh.computeWorldMatrix(!0),this._existingSlateScale.copyFrom(this.attachedMesh.scaling)}}_updateHandlesPosition(){const e=this._boundingBoxGizmo.min.clone(),t=this._boundingBoxGizmo.max.clone(),i=this._corners[0].node.scaling.length();e.x-=this._margin*i,e.y-=this._margin*i,t.x+=this._margin*i,t.y+=this._margin*i;const s=e.add(t).scaleInPlace(.5);this._corners[0].node.position.copyFromFloats(e.x,e.y,0),this._corners[1].node.position.copyFromFloats(t.x,e.y,0),this._corners[2].node.position.copyFromFloats(t.x,t.y,0),this._corners[3].node.position.copyFromFloats(e.x,t.y,0),this._sides[0].node.position.copyFromFloats(e.x,s.y,0),this._sides[1].node.position.copyFromFloats(s.x,e.y,0),this._sides[2].node.position.copyFromFloats(t.x,s.y,0),this._sides[3].node.position.copyFromFloats(s.x,t.y,0)}_updateHandlesScaling(){if(this._attachedSlate&&this._attachedSlate.mesh){const e=this._attachedSlate.mesh.scaling.x*this._attachedSlate.dimensions.x,t=this._attachedSlate.mesh.scaling.y*this._attachedSlate.dimensions.y,i=Math.min(e,t)*this._handleSize;for(let e=0;ei?this.minDimensions.x/e.x:this.minDimensions.y/e.y}this._dimensions.copyFrom(e).scaleInPlace(t),this._updatePivot(),this._positionElements()}get titleBarHeight(){return this._titleBarHeight}set titleBarHeight(e){this._titleBarHeight=e}set renderingGroupId(e){this._titleBar.renderingGroupId=e,this._titleBarTitle.renderingGroupId=e,this._contentPlate.renderingGroupId=e,this._backPlate.renderingGroupId=e}get renderingGroupId(){return this._titleBar.renderingGroupId}set title(e){this._titleText=e,this._titleTextComponent&&(this._titleTextComponent.text=e)}get title(){return this._titleText}constructor(e){super(e),this.titleBarMargin=.005,this.origin=new de(0,0,0),this._dimensions=new ue(21.875,12.5),this._titleBarHeight=.625,this._titleText="",this._contentScaleRatio=1,this.minDimensions=new ue(15.625,6.25),this.defaultDimensions=this._dimensions.clone(),this._followButton=new Qw("followButton"+this.name),this._followButton.isToggleButton=!0,this._closeButton=new Qw("closeButton"+this.name),this._contentViewport=new jr(0,0,1,1),this._contentDragBehavior=new sa({dragPlaneNormal:new de(0,0,-1)})}_applyFacade(e){this._contentMaterial.albedoTexture=e,this._resetContentPositionAndZoom(),this._applyContentViewport(),e.attachToMesh(this._contentPlate,!0)}_addControl(e){e._host=this._host,this._host.utilityLayer&&e._prepareNode(this._host.utilityLayer.utilityLayerScene)}_getTypeName(){return"HolographicSlate"}_positionElements(){const e=this._followButton,t=this._closeButton,i=this._titleBar,s=this._titleBarTitle,r=this._contentPlate,n=this._backPlate;if(e&&t&&i){t.scaling.setAll(this.titleBarHeight),e.scaling.setAll(this.titleBarHeight),t.position.copyFromFloats(this.dimensions.x-this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin),e.position.copyFromFloats(this.dimensions.x-3*this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin);const o=this.dimensions.y-this.titleBarHeight-this.titleBarMargin,a=r.getScene().useRightHandedSystem;i.scaling.set(this.dimensions.x,this.titleBarHeight,K),s.scaling.set(this.dimensions.x-2*this.titleBarHeight,this.titleBarHeight,K),r.scaling.copyFromFloats(this.dimensions.x,o,K),n.scaling.copyFromFloats(this.dimensions.x,o,K),i.position.copyFromFloats(this.dimensions.x/2,-this.titleBarHeight/2,0).addInPlace(this.origin),s.position.copyFromFloats(this.dimensions.x/2-this.titleBarHeight,-this.titleBarHeight/2,a?K:-K).addInPlace(this.origin),r.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),0).addInPlace(this.origin),n.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),a?-K:K).addInPlace(this.origin),this._titleTextComponent.host.scaleTo(tN._DEFAULT_TEXT_RESOLUTION_Y*s.scaling.x/s.scaling.y,tN._DEFAULT_TEXT_RESOLUTION_Y);const l=this.dimensions.x/o;this._contentViewport.width=this._contentScaleRatio,this._contentViewport.height=this._contentScaleRatio/l,this._applyContentViewport(),this._gizmo&&this._gizmo.updateBoundingBox()}}_applyContentViewport(){if(this._contentPlate?.material&&this._contentPlate.material.albedoTexture){const e=this._contentPlate.material.albedoTexture;e.uScale=this._contentScaleRatio,e.vScale=this._contentScaleRatio/this._contentViewport.width*this._contentViewport.height,e.uOffset=this._contentViewport.x,e.vOffset=this._contentViewport.y}}_resetContentPositionAndZoom(){this._contentViewport.x=0,this._contentViewport.y=1-this._contentViewport.height/this._contentViewport.width,this._contentScaleRatio=1}_updatePivot(){if(!this.mesh)return;const e=new de(.5*this.dimensions.x,.5*-this.dimensions.y,K);e.addInPlace(this.origin),e.z=0;const t=new de(0,0,0);de.TransformCoordinatesToRef(t,this.mesh.computeWorldMatrix(!0),t),this.mesh.setPivotPoint(e);const i=new de(0,0,0);de.TransformCoordinatesToRef(i,this.mesh.computeWorldMatrix(!0),i),this.mesh.position.addInPlace(t).subtractInPlace(i)}_createNode(e){const t=new bo("slate_"+this.name,e);this._titleBar=yu("titleBar_"+this.name,{size:1},e),this._titleBarTitle=ta("titleText_"+this.name,{size:1},e),this._titleBarTitle.parent=t,this._titleBarTitle.isPickable=!1;const i=Cw.CreateForMesh(this._titleBarTitle);if(this._titleTextComponent=new UD("titleText_"+this.name,this._titleText),this._titleTextComponent.textWrapping=VD.Ellipsis,this._titleTextComponent.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._titleTextComponent.color="white",this._titleTextComponent.fontSize=tN._DEFAULT_TEXT_RESOLUTION_Y/2,this._titleTextComponent.paddingLeft=tN._DEFAULT_TEXT_RESOLUTION_Y/4,i.addControl(this._titleTextComponent),e.useRightHandedSystem){const t=new _e(0,0,1,1);this._contentPlate=ta("contentPlate_"+this.name,{size:1,sideOrientation:cn.BACKSIDE,frontUVs:t},e),this._backPlate=ta("backPlate_"+this.name,{size:1,sideOrientation:cn.FRONTSIDE},e)}else{const t=new _e(0,0,1,1);this._contentPlate=ta("contentPlate_"+this.name,{size:1,sideOrientation:cn.FRONTSIDE,frontUVs:t},e),this._backPlate=ta("backPlate_"+this.name,{size:1,sideOrientation:cn.BACKSIDE},e)}this._titleBar.parent=t,this._titleBar.isNearGrabbable=!0,this._contentPlate.parent=t,this._backPlate.parent=t,this._attachContentPlateBehavior(),this._addControl(this._followButton),this._addControl(this._closeButton);const s=this._followButton,r=this._closeButton;return s.node.parent=t,r.node.parent=t,this._positionElements(),this._followButton.imageUrl=tN.ASSETS_BASE_URL+tN.FOLLOW_ICON_FILENAME,this._closeButton.imageUrl=tN.ASSETS_BASE_URL+tN.CLOSE_ICON_FILENAME,this._followButton.isBackplateVisible=!1,this._closeButton.isBackplateVisible=!1,this._followButton.onToggleObservable.add((e=>{this._defaultBehavior.followBehaviorEnabled=e,this._defaultBehavior.followBehaviorEnabled&&this._defaultBehavior.followBehavior.recenter()})),this._closeButton.onPointerClickObservable.add((()=>{this.dispose()})),t.rotationQuaternion=pe.Identity(),t.isVisible=!1,t}_attachContentPlateBehavior(){this._contentDragBehavior.attach(this._contentPlate),this._contentDragBehavior.moveAttached=!1,this._contentDragBehavior.useObjectOrientationForDragging=!0,this._contentDragBehavior.updateDragPlane=!1;const e=new de,t=new de,i=new de,s=new de,r=new ue;let n,o;this._contentDragBehavior.onDragStartObservable.add((r=>{this.node&&(n=this._contentViewport.clone(),o=this.node.computeWorldMatrix(!0),e.copyFrom(r.dragPlanePoint),t.set(this.dimensions.x,this.dimensions.y,K),t.y-=this.titleBarHeight+this.titleBarMargin,de.TransformNormalToRef(t,o,t),i.copyFromFloats(0,1,0),de.TransformNormalToRef(i,o,i),s.copyFromFloats(1,0,0),de.TransformNormalToRef(s,o,s),i.normalize(),i.scaleInPlace(1/de.Dot(i,t)),s.normalize(),s.scaleInPlace(1/de.Dot(s,t)))}));const a=new de;this._contentDragBehavior.onDragObservable.add((t=>{a.copyFrom(t.dragPlanePoint),a.subtractInPlace(e),r.copyFromFloats(de.Dot(a,s),de.Dot(a,i)),this._contentViewport.x=xe.Clamp(n.x-a.x,0,1-this._contentViewport.width*this._contentScaleRatio),this._contentViewport.y=xe.Clamp(n.y-a.y,0,1-this._contentViewport.height*this._contentScaleRatio),this._applyContentViewport()}))}_affectMaterial(e){this._titleBarMaterial=new Gw(`${this.name} plateMaterial`,e.getScene()),this._contentMaterial=new Lw(`${this.name} contentMaterial`,e.getScene()),this._contentMaterial.renderBorders=!0,this._backMaterial=new Gw(`${this.name} backPlate`,e.getScene()),this._backMaterial.lineWidth=K,this._backMaterial.radius=.005,this._backMaterial.backFaceCulling=!0,this._titleBar.material=this._titleBarMaterial,this._contentPlate.material=this._contentMaterial,this._backPlate.material=this._backMaterial,this._resetContent(),this._applyContentViewport()}_prepareNode(e){super._prepareNode(e),this._gizmo=new eN(this._host.utilityLayer),this._gizmo.attachedSlate=this,this._defaultBehavior=new jw,this._defaultBehavior.attach(this.node,[this._titleBar]),this._defaultBehavior.sixDofDragBehavior.onDragStartObservable.add((()=>{this._followButton.isToggled=!1})),this._positionChangedObserver=this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.add((()=>{this._gizmo.updateBoundingBox()})),this._updatePivot(),this.resetDefaultAspectAndPose(!1)}resetDefaultAspectAndPose(e=!0){if(!this._host||!this._host.utilityLayer||!this.node)return;const t=this._host.utilityLayer.utilityLayerScene,i=t.activeCamera;if(i){const s=i.getWorldMatrix(),r=de.TransformNormal(de.Backward(t.useRightHandedSystem),s);this.origin.setAll(0),this._gizmo.updateBoundingBox();const n=this.node.getAbsolutePivotPoint();this.node.position.copyFrom(i.position).subtractInPlace(r).subtractInPlace(n),this.node.rotationQuaternion=pe.FromLookDirectionLH(r,new de(0,1,0)),e&&(this.dimensions=this.defaultDimensions)}}dispose(){super.dispose(),this._titleBarMaterial.dispose(),this._contentMaterial.dispose(),this._titleBar.dispose(),this._titleBarTitle.dispose(),this._contentPlate.dispose(),this._backPlate.dispose(),this._followButton.dispose(),this._closeButton.dispose(),this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.remove(this._positionChangedObserver),this._defaultBehavior.detach(),this._gizmo.dispose(),this._contentDragBehavior.detach()}}tN.ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",tN.CLOSE_ICON_FILENAME="IconClose.png",tN.FOLLOW_ICON_FILENAME="IconFollowMe.png",tN._DEFAULT_TEXT_RESOLUTION_Y=102.4;class iN extends Dw{constructor(e,t){super(t),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"MeshButton3D"}_createNode(e){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}class sN extends kw{get defaultBehavior(){return this._defaultBehavior}get isPinned(){return this._isPinned}set isPinned(e){this._pinButton.isToggled===e?(this._isPinned=e,this._defaultBehavior.followBehaviorEnabled=!e):this._pinButton.isToggled=e}_createPinButton(e){const t=new Qw("pin"+this.name,!1);return t.imageUrl=sN._ASSETS_BASE_URL+sN._PIN_ICON_FILENAME,t.parent=this,t._host=this._host,t.isToggleButton=!0,t.onToggleObservable.add((e=>{this.isPinned=e})),this._host.utilityLayer&&(t._prepareNode(this._host.utilityLayer.utilityLayerScene),t.scaling.scaleInPlace(kw.MENU_BUTTON_SCALE),t.node&&(t.node.parent=e)),t}_createNode(e){const t=super._createNode(e);return this._pinButton=this._createPinButton(t),this.isPinned=!1,this._defaultBehavior.attach(t,[this._backPlate]),this._defaultBehavior.followBehavior.ignoreCameraPitchAndRoll=!0,this._defaultBehavior.followBehavior.pitchOffset=-15,this._defaultBehavior.followBehavior.minimumDistance=.3,this._defaultBehavior.followBehavior.defaultDistance=.4,this._defaultBehavior.followBehavior.maximumDistance=.6,this._backPlate.isNearGrabbable=!0,t.isVisible=!1,t}_finalProcessing(){super._finalProcessing(),this._pinButton.position.copyFromFloats((this._backPlate.scaling.x+kw.MENU_BUTTON_SCALE)/2,this._backPlate.scaling.y/2,0)}constructor(e){super(e),this._isPinned=!1,this._defaultBehavior=new jw,this._dragObserver=this._defaultBehavior.sixDofDragBehavior.onDragObservable.add((()=>{this.isPinned=!0})),this.backPlateMargin=1}dispose(){super.dispose(),this._defaultBehavior.sixDofDragBehavior.onDragObservable.remove(this._dragObserver),this._defaultBehavior.detach()}}sN._ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",sN._PIN_ICON_FILENAME="IconPin.png";class rN extends Nw{_mapGridNode(e,t){const i=e.mesh;if(!i)return;e.position=t.clone();const s=ge.Vector3[0];switch(s.copyFrom(t),this.orientation){case ww.FACEORIGIN_ORIENTATION:case ww.FACEFORWARD_ORIENTATION:s.addInPlace(new de(0,0,1)),i.lookAt(s);break;case ww.FACEFORWARDREVERSED_ORIENTATION:case ww.FACEORIGINREVERSED_ORIENTATION:s.addInPlace(new de(0,0,-1)),i.lookAt(s)}}}class nN extends Nw{constructor(){super(...arguments),this._iteration=100}get iteration(){return this._iteration}set iteration(e){this._iteration!==e&&(this._iteration=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh,s=this._scatterMapping(t);if(i){switch(this.orientation){case ww.FACEORIGIN_ORIENTATION:case ww.FACEFORWARD_ORIENTATION:i.lookAt(new de(0,0,1));break;case ww.FACEFORWARDREVERSED_ORIENTATION:case ww.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new de(0,0,-1))}e.position=s}}_scatterMapping(e){return e.x=(1-2*Math.random())*this._cellWidth,e.y=(1-2*Math.random())*this._cellHeight,e}_finalProcessing(){const e=[];for(const t of this._children)t.mesh&&e.push(t.mesh);for(let t=0;t{const i=e.position.lengthSquared(),s=t.position.lengthSquared();return is?-1:0}));const t=Math.pow(this.margin,2),i=Math.max(this._cellWidth,this._cellHeight),s=ge.Vector2[0],r=ge.Vector3[0];for(let n=0;n0.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B50(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid50(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B65(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B74(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B64(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B108(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B114(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B75(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B36(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B37(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B105(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q85;XY_Q85=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q27;vec3 Tangent_World_N_Q27;float Tangent_Length_Q27;Tangent_World_Q27=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q27=length(Tangent_World_Q27);Tangent_World_N_Q27=Tangent_World_Q27/Tangent_Length_Q27;vec3 Normal_World_Q60;vec3 Normal_World_N_Q60;float Normal_Length_Q60;Object_To_World_Dir_B60(vec3(0,0,1),Normal_World_Q60,Normal_World_N_Q60,Normal_Length_Q60);float X_Q78;float Y_Q78;float Z_Q78;To_XYZ_B78(position,X_Q78,Y_Q78,Z_Q78);vec3 Nrm_World_Q26;Nrm_World_Q26=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q28;vec3 Binormal_World_N_Q28;float Binormal_Length_Q28;Object_To_World_Dir_B28(vec3(0,1,0),Binormal_World_Q28,Binormal_World_N_Q28,Binormal_Length_Q28);float Anisotropy_Q29=Tangent_Length_Q27/Binormal_Length_Q28;float Result_Q69;Pick_Radius_B69(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q69);float Anisotropy_Q53=Binormal_Length_Q28/Normal_Length_Q60;bool Not_Greater_Than_Q37;bool Greater_Than_Q37;Greater_Than_B37(Z_Q78,0.0,Not_Greater_Than_Q37,Greater_Than_Q37);vec4 Linear_Q101;Linear_Q101.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q101.a=_Left_Color_.a;vec4 Linear_Q102;Linear_Q102.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q102.a=_Right_Color_.a;vec3 Difference_Q61=vec3(0,0,0)-Normal_World_N_Q60;vec4 Out_Color_Q34=vec4(X_Q78,Y_Q78,Z_Q78,1);float Result_Q36;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_,_Bevel_Front_,Result_Q36);float Result_Q94;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q94);vec3 New_P_Q130;vec2 New_UV_Q130;float Radial_Gradient_Q130;vec3 Radial_Dir_Q130;vec3 New_Normal_Q130;Move_Verts_B130(Anisotropy_Q29,position,Result_Q69,Result_Q36,normal,Anisotropy_Q53,Result_Q94,New_P_Q130,New_UV_Q130,Radial_Gradient_Q130,Radial_Dir_Q130,New_Normal_Q130);float X_Q98;float Y_Q98;X_Q98=New_UV_Q130.x;Y_Q98=New_UV_Q130.y;vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q130,Pos_World_Q12);vec3 Nrm_World_Q32;Object_To_World_Normal_B32(New_Normal_Q130,Nrm_World_Q32);vec4 Blob_Info_Q23;\n#if BLOB_ENABLE\nBlob_Vertex_B23(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q23);\n#else\nBlob_Info_Q23=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q24;\n#if BLOB_ENABLE_2\nBlob_Vertex_B24(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q24);\n#else\nBlob_Info_Q24=vec4(0,0,0,0);\n#endif\nfloat Out_Q105;Remap_Range_B105(0.0,1.0,0.0,1.0,X_Q98,Out_Q105);float X_Q86;float Y_Q86;float Z_Q86;To_XYZ_B78(Nrm_World_Q32,X_Q86,Y_Q86,Z_Q86);vec4 Color_At_T_Q97=mix(Linear_Q101,Linear_Q102,Out_Q105);float Minus_F_Q87=-Z_Q86;float R_Q99;float G_Q99;float B_Q99;float A_Q99;R_Q99=Color_At_T_Q97.r; G_Q99=Color_At_T_Q97.g; B_Q99=Color_At_T_Q97.b; A_Q99=Color_At_T_Q97.a;float ClampF_Q88=clamp(0.0,Minus_F_Q87,1.0);float Result_Q93;Conditional_Float_B93(_Decal_Front_Only_,ClampF_Q88,1.0,Result_Q93);vec4 Vec4_Q89=vec4(Result_Q93,Radial_Gradient_Q130,G_Q99,B_Q99);vec3 Position=Pos_World_Q12;vec3 Normal=Nrm_World_Q32;vec2 UV=XY_Q85;vec3 Tangent=Tangent_World_N_Q27;vec3 Binormal=Difference_Q61;vec4 Color=Out_Color_Q34;vec4 Extra1=Vec4_Q89;vec4 Extra2=Blob_Info_Q23;vec4 Extra3=Blob_Info_Q24;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class oN extends Oa{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class aN extends Ra{constructor(e,t){super(e,t),this.radius=.6,this.bevelFront=.6,this.bevelFrontStretch=.077,this.bevelBack=0,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=1.102,this.sunTheta=.76,this.sunPhi=.526,this.indirectDiffuse=.658,this.albedo=new Ee(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=0,this.leftGradientColor=new Ee(.0117647,.505882,.996078,1),this.rightGradientColor=new Ee(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.13,this.skyColor=new Ee(.0117647,.964706,.996078,1),this.horizonColor=new Ee(.0117647,.333333,.996078,1),this.groundColor=new Ee(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new de(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new de(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Vo("",this.getScene()),this.leftIndexPosition=new de(0,0,1),this.rightIndexPosition=new de(-1,-1,-1),this.leftIndexMiddlePosition=new de(0,0,0),this.rightIndexMiddlePosition=new de(0,0,0),this.decalScaleXY=new ue(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new _e(.5,0,-.55,1),this.globaRightIndexTipPosition=new _e(0,0,0,1),this.globalLeftThumbTipPosition=new _e(.5,0,-.55,1),this.globalRightThumbTipPosition=new _e(0,0,0,1),this.globalLeftIndexMiddlePosition=new _e(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new _e(0,0,0,1),this.alphaMode=Yd.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Vo(aN.BLUE_GRADIENT_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE),this._decalTexture=new Vo("",this.getScene()),this._reflectionMapTexture=new Vo("",this.getScene()),this._indirectEnvTexture=new Vo("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new oN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlSliderBar",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return yt.Clone((()=>new aN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderBarMaterial",e}getClassName(){return"MRDLSliderBarMaterial"}static Parse(e,t,i){return yt.Parse((()=>new aN(e.name,t)),e,t,i)}}aN.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",qe([st()],aN.prototype,"radius",void 0),qe([st()],aN.prototype,"bevelFront",void 0),qe([st()],aN.prototype,"bevelFrontStretch",void 0),qe([st()],aN.prototype,"bevelBack",void 0),qe([st()],aN.prototype,"bevelBackStretch",void 0),qe([st()],aN.prototype,"radiusTopLeft",void 0),qe([st()],aN.prototype,"radiusTopRight",void 0),qe([st()],aN.prototype,"radiusBottomLeft",void 0),qe([st()],aN.prototype,"radiusBottomRight",void 0),qe([st()],aN.prototype,"bulgeEnabled",void 0),qe([st()],aN.prototype,"bulgeHeight",void 0),qe([st()],aN.prototype,"bulgeRadius",void 0),qe([st()],aN.prototype,"sunIntensity",void 0),qe([st()],aN.prototype,"sunTheta",void 0),qe([st()],aN.prototype,"sunPhi",void 0),qe([st()],aN.prototype,"indirectDiffuse",void 0),qe([st()],aN.prototype,"albedo",void 0),qe([st()],aN.prototype,"specular",void 0),qe([st()],aN.prototype,"shininess",void 0),qe([st()],aN.prototype,"sharpness",void 0),qe([st()],aN.prototype,"subsurface",void 0),qe([st()],aN.prototype,"leftGradientColor",void 0),qe([st()],aN.prototype,"rightGradientColor",void 0),qe([st()],aN.prototype,"reflection",void 0),qe([st()],aN.prototype,"frontReflect",void 0),qe([st()],aN.prototype,"edgeReflect",void 0),qe([st()],aN.prototype,"power",void 0),qe([st()],aN.prototype,"skyColor",void 0),qe([st()],aN.prototype,"horizonColor",void 0),qe([st()],aN.prototype,"groundColor",void 0),qe([st()],aN.prototype,"horizonPower",void 0),qe([st()],aN.prototype,"width",void 0),qe([st()],aN.prototype,"fuzz",void 0),qe([st()],aN.prototype,"minFuzz",void 0),qe([st()],aN.prototype,"clipFade",void 0),qe([st()],aN.prototype,"hueShift",void 0),qe([st()],aN.prototype,"saturationShift",void 0),qe([st()],aN.prototype,"valueShift",void 0),qe([st()],aN.prototype,"blobPosition",void 0),qe([st()],aN.prototype,"blobIntensity",void 0),qe([st()],aN.prototype,"blobNearSize",void 0),qe([st()],aN.prototype,"blobFarSize",void 0),qe([st()],aN.prototype,"blobNearDistance",void 0),qe([st()],aN.prototype,"blobFarDistance",void 0),qe([st()],aN.prototype,"blobFadeLength",void 0),qe([st()],aN.prototype,"blobPulse",void 0),qe([st()],aN.prototype,"blobFade",void 0),qe([st()],aN.prototype,"blobPosition2",void 0),qe([st()],aN.prototype,"blobNearSize2",void 0),qe([st()],aN.prototype,"blobPulse2",void 0),qe([st()],aN.prototype,"blobFade2",void 0),qe([st()],aN.prototype,"blobTexture",void 0),qe([st()],aN.prototype,"leftIndexPosition",void 0),qe([st()],aN.prototype,"rightIndexPosition",void 0),qe([st()],aN.prototype,"leftIndexMiddlePosition",void 0),qe([st()],aN.prototype,"rightIndexMiddlePosition",void 0),qe([st()],aN.prototype,"decalScaleXY",void 0),qe([st()],aN.prototype,"decalFrontOnly",void 0),qe([st()],aN.prototype,"rimIntensity",void 0),qe([st()],aN.prototype,"rimHueShift",void 0),qe([st()],aN.prototype,"rimSaturationShift",void 0),qe([st()],aN.prototype,"rimValueShift",void 0),qe([st()],aN.prototype,"iridescenceIntensity",void 0),ee("BABYLON.GUI.MRDLSliderBarMaterial",aN);bi.ShadersStore.mrdlSliderThumbPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Bevel_Front_;uniform float _Bevel_Front_Stretch_;uniform float _Bevel_Back_;uniform float _Bevel_Back_Stretch_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform bool _Bulge_Enabled_;uniform float _Bulge_Height_;uniform float _Bulge_Radius_;uniform float _Sun_Intensity_;uniform float _Sun_Theta_;uniform float _Sun_Phi_;uniform float _Indirect_Diffuse_;uniform vec4 _Albedo_;uniform float _Specular_;uniform float _Shininess_;uniform float _Sharpness_;uniform float _Subsurface_;uniform vec4 _Left_Color_;uniform vec4 _Right_Color_;uniform float _Reflection_;uniform float _Front_Reflect_;uniform float _Edge_Reflect_;uniform float _Power_;uniform vec4 _Sky_Color_;uniform vec4 _Horizon_Color_;uniform vec4 _Ground_Color_;uniform float _Horizon_Power_;uniform sampler2D _Reflection_Map_;uniform sampler2D _Indirect_Environment_;uniform float _Width_;uniform float _Fuzz_;uniform float _Min_Fuzz_;uniform float _Clip_Fade_;uniform float _Hue_Shift_;uniform float _Saturation_Shift_;uniform float _Value_Shift_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Left_Index_Pos_;uniform vec3 _Right_Index_Pos_;uniform vec3 _Left_Index_Middle_Pos_;uniform vec3 _Right_Index_Middle_Pos_;uniform sampler2D _Decal_;uniform vec2 _Decal_Scale_XY_;uniform bool _Decal_Front_Only_;uniform float _Rim_Intensity_;uniform sampler2D _Rim_Texture_;uniform float _Rim_Hue_Shift_;uniform float _Rim_Saturation_Shift_;uniform float _Rim_Value_Shift_;uniform float _Iridescence_Intensity_;uniform sampler2D _Iridescence_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform vec4 Global_Left_Index_Middle_Position;uniform vec4 Global_Right_Index_Middle_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Blob_Fragment_B180(\nsampler2D Blob_Texture,\nvec4 Blob_Info1,\nvec4 Blob_Info2,\nout vec4 Blob_Color)\n{float k1=dot(Blob_Info1.xy,Blob_Info1.xy);float k2=dot(Blob_Info2.xy,Blob_Info2.xy);vec3 closer=k10.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B200(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid200(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B215(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B224(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B214(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B258(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B264(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B225(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B186(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B187(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B255(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q235;XY_Q235=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q177;vec3 Tangent_World_N_Q177;float Tangent_Length_Q177;Tangent_World_Q177=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q177=length(Tangent_World_Q177);Tangent_World_N_Q177=Tangent_World_Q177/Tangent_Length_Q177;vec3 Normal_World_Q210;vec3 Normal_World_N_Q210;float Normal_Length_Q210;Object_To_World_Dir_B210(vec3(0,0,1),Normal_World_Q210,Normal_World_N_Q210,Normal_Length_Q210);float X_Q228;float Y_Q228;float Z_Q228;To_XYZ_B228(position,X_Q228,Y_Q228,Z_Q228);vec3 Nrm_World_Q176;Nrm_World_Q176=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q178;vec3 Binormal_World_N_Q178;float Binormal_Length_Q178;Object_To_World_Dir_B178(vec3(0,1,0),Binormal_World_Q178,Binormal_World_N_Q178,Binormal_Length_Q178);float Anisotropy_Q179=Tangent_Length_Q177/Binormal_Length_Q178;float Result_Q219;Pick_Radius_B219(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q219);float Anisotropy_Q203=Binormal_Length_Q178/Normal_Length_Q210;bool Not_Greater_Than_Q187;bool Greater_Than_Q187;Greater_Than_B187(Z_Q228,0.0,Not_Greater_Than_Q187,Greater_Than_Q187);vec4 Linear_Q251;Linear_Q251.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q251.a=_Left_Color_.a;vec4 Linear_Q252;Linear_Q252.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q252.a=_Right_Color_.a;vec3 Difference_Q211=vec3(0,0,0)-Normal_World_N_Q210;vec4 Out_Color_Q184=vec4(X_Q228,Y_Q228,Z_Q228,1);float Result_Q186;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_,_Bevel_Front_,Result_Q186);float Result_Q244;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q244);vec3 New_P_Q280;vec2 New_UV_Q280;float Radial_Gradient_Q280;vec3 Radial_Dir_Q280;vec3 New_Normal_Q280;Move_Verts_B280(Anisotropy_Q179,position,Result_Q219,Result_Q186,normal,Anisotropy_Q203,Result_Q244,New_P_Q280,New_UV_Q280,Radial_Gradient_Q280,Radial_Dir_Q280,New_Normal_Q280);float X_Q248;float Y_Q248;X_Q248=New_UV_Q280.x;Y_Q248=New_UV_Q280.y;vec3 Pos_World_Q162;Object_To_World_Pos_B162(New_P_Q280,Pos_World_Q162);vec3 Nrm_World_Q182;Object_To_World_Normal_B182(New_Normal_Q280,Nrm_World_Q182);vec4 Blob_Info_Q173;\n#if BLOB_ENABLE\nBlob_Vertex_B173(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q173);\n#else\nBlob_Info_Q173=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q174;\n#if BLOB_ENABLE_2\nBlob_Vertex_B174(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q174);\n#else\nBlob_Info_Q174=vec4(0,0,0,0);\n#endif\nfloat Out_Q255;Remap_Range_B255(0.0,1.0,0.0,1.0,X_Q248,Out_Q255);float X_Q236;float Y_Q236;float Z_Q236;To_XYZ_B228(Nrm_World_Q182,X_Q236,Y_Q236,Z_Q236);vec4 Color_At_T_Q247=mix(Linear_Q251,Linear_Q252,Out_Q255);float Minus_F_Q237=-Z_Q236;float R_Q249;float G_Q249;float B_Q249;float A_Q249;R_Q249=Color_At_T_Q247.r; G_Q249=Color_At_T_Q247.g; B_Q249=Color_At_T_Q247.b; A_Q249=Color_At_T_Q247.a;float ClampF_Q238=clamp(0.0,Minus_F_Q237,1.0);float Result_Q243;Conditional_Float_B243(_Decal_Front_Only_,ClampF_Q238,1.0,Result_Q243);vec4 Vec4_Q239=vec4(Result_Q243,Radial_Gradient_Q280,G_Q249,B_Q249);vec3 Position=Pos_World_Q162;vec3 Normal=Nrm_World_Q182;vec2 UV=XY_Q235;vec3 Tangent=Tangent_World_N_Q177;vec3 Binormal=Difference_Q211;vec4 Color=Out_Color_Q184;vec4 Extra1=Vec4_Q239;vec4 Extra2=Blob_Info_Q173;vec4 Extra3=Blob_Info_Q174;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class lN extends Oa{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class hN extends Ra{constructor(e,t){super(e,t),this.radius=.157,this.bevelFront=.065,this.bevelFrontStretch=.077,this.bevelBack=.031,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=2,this.sunTheta=.937,this.sunPhi=.555,this.indirectDiffuse=1,this.albedo=new Ee(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=.31,this.leftGradientColor=new Ee(.0117647,.505882,.996078,1),this.rightGradientColor=new Ee(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.1,this.skyColor=new Ee(.0117647,.960784,.996078,1),this.horizonColor=new Ee(.0117647,.333333,.996078,1),this.groundColor=new Ee(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new de(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new de(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Vo("",this.getScene()),this.leftIndexPosition=new de(0,0,1),this.rightIndexPosition=new de(-1,-1,-1),this.leftIndexMiddlePosition=new de(0,0,0),this.rightIndexMiddlePosition=new de(0,0,0),this.decalScaleXY=new ue(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new _e(.5,0,-.55,1),this.globaRightIndexTipPosition=new _e(0,0,0,1),this.globalLeftThumbTipPosition=new _e(.5,0,-.55,1),this.globalRightThumbTipPosition=new _e(0,0,0,1),this.globalLeftIndexMiddlePosition=new _e(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new _e(0,0,0,1),this.alphaMode=Yd.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Vo(hN.BLUE_GRADIENT_TEXTURE_URL,t,!0,!1,Vo.NEAREST_SAMPLINGMODE),this._decalTexture=new Vo("",this.getScene()),this._reflectionMapTexture=new Vo("",this.getScene()),this._indirectEnvTexture=new Vo("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new lN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlSliderThumb",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return yt.Clone((()=>new hN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderThumbMaterial",e}getClassName(){return"MRDLSliderThumbMaterial"}static Parse(e,t,i){return yt.Parse((()=>new hN(e.name,t)),e,t,i)}}hN.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",qe([st()],hN.prototype,"radius",void 0),qe([st()],hN.prototype,"bevelFront",void 0),qe([st()],hN.prototype,"bevelFrontStretch",void 0),qe([st()],hN.prototype,"bevelBack",void 0),qe([st()],hN.prototype,"bevelBackStretch",void 0),qe([st()],hN.prototype,"radiusTopLeft",void 0),qe([st()],hN.prototype,"radiusTopRight",void 0),qe([st()],hN.prototype,"radiusBottomLeft",void 0),qe([st()],hN.prototype,"radiusBottomRight",void 0),qe([st()],hN.prototype,"bulgeEnabled",void 0),qe([st()],hN.prototype,"bulgeHeight",void 0),qe([st()],hN.prototype,"bulgeRadius",void 0),qe([st()],hN.prototype,"sunIntensity",void 0),qe([st()],hN.prototype,"sunTheta",void 0),qe([st()],hN.prototype,"sunPhi",void 0),qe([st()],hN.prototype,"indirectDiffuse",void 0),qe([st()],hN.prototype,"albedo",void 0),qe([st()],hN.prototype,"specular",void 0),qe([st()],hN.prototype,"shininess",void 0),qe([st()],hN.prototype,"sharpness",void 0),qe([st()],hN.prototype,"subsurface",void 0),qe([st()],hN.prototype,"leftGradientColor",void 0),qe([st()],hN.prototype,"rightGradientColor",void 0),qe([st()],hN.prototype,"reflection",void 0),qe([st()],hN.prototype,"frontReflect",void 0),qe([st()],hN.prototype,"edgeReflect",void 0),qe([st()],hN.prototype,"power",void 0),qe([st()],hN.prototype,"skyColor",void 0),qe([st()],hN.prototype,"horizonColor",void 0),qe([st()],hN.prototype,"groundColor",void 0),qe([st()],hN.prototype,"horizonPower",void 0),qe([st()],hN.prototype,"width",void 0),qe([st()],hN.prototype,"fuzz",void 0),qe([st()],hN.prototype,"minFuzz",void 0),qe([st()],hN.prototype,"clipFade",void 0),qe([st()],hN.prototype,"hueShift",void 0),qe([st()],hN.prototype,"saturationShift",void 0),qe([st()],hN.prototype,"valueShift",void 0),qe([st()],hN.prototype,"blobPosition",void 0),qe([st()],hN.prototype,"blobIntensity",void 0),qe([st()],hN.prototype,"blobNearSize",void 0),qe([st()],hN.prototype,"blobFarSize",void 0),qe([st()],hN.prototype,"blobNearDistance",void 0),qe([st()],hN.prototype,"blobFarDistance",void 0),qe([st()],hN.prototype,"blobFadeLength",void 0),qe([st()],hN.prototype,"blobPulse",void 0),qe([st()],hN.prototype,"blobFade",void 0),qe([st()],hN.prototype,"blobPosition2",void 0),qe([st()],hN.prototype,"blobNearSize2",void 0),qe([st()],hN.prototype,"blobPulse2",void 0),qe([st()],hN.prototype,"blobFade2",void 0),qe([st()],hN.prototype,"blobTexture",void 0),qe([st()],hN.prototype,"leftIndexPosition",void 0),qe([st()],hN.prototype,"rightIndexPosition",void 0),qe([st()],hN.prototype,"leftIndexMiddlePosition",void 0),qe([st()],hN.prototype,"rightIndexMiddlePosition",void 0),qe([st()],hN.prototype,"decalScaleXY",void 0),qe([st()],hN.prototype,"decalFrontOnly",void 0),qe([st()],hN.prototype,"rimIntensity",void 0),qe([st()],hN.prototype,"rimHueShift",void 0),qe([st()],hN.prototype,"rimSaturationShift",void 0),qe([st()],hN.prototype,"rimValueShift",void 0),qe([st()],hN.prototype,"iridescenceIntensity",void 0),ee("BABYLON.GUI.MRDLSliderThumbMaterial",hN);bi.ShadersStore.mrdlBackplatePixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;void FastLinearTosRGB_B353(\nvec4 Linear,\nout vec4 sRGB)\n{sRGB.rgb=sqrt(clamp(Linear.rgb,0.0,1.0));sRGB.a=Linear.a;}\nvoid Round_Rect_Fragment_B332(\nfloat Radius,\nfloat Line_Width,\nvec4 Line_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Line_Visibility,\nvec4 Rect_Parms,\nvec4 Fill_Color,\nout vec4 Color)\n{float d=length(max(abs(UV)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);float g=min(Rect_Parms.z,Rect_Parms.w);float dgrad=max(fwidth(g)*Filter_Width,0.00001);float Inside_Rect=clamp(g/dgrad,0.0,1.0);float inner=clamp((d+dx*0.5-max(Radius-Line_Width,d-dx*0.5))/dx,0.0,1.0);Color=clamp(mix(Fill_Color,Line_Color,inner),0.0,1.0)*Inside_Rect;}\nvoid Iridescence_B343(\nvec3 Position,\nvec3 Normal,\nvec2 UV,\nvec3 Axis,\nvec3 Eye,\nvec4 Tint,\nsampler2D Texture,\nbool Reflected,\nfloat Frequency,\nfloat Vertical_Offset,\nout vec4 Color)\n{vec3 i=normalize(Position-Eye);vec3 r=reflect(i,Normal);float idota=dot(i,Axis);float idotr=dot(i,r);float x=Reflected ? idotr : idota;vec2 xy;xy.x=fract((x*Frequency+1.0)*0.5+UV.y*Vertical_Offset);xy.y=0.5;Color=texture(Texture,xy);Color.rgb*=Tint.rgb;}\nvoid Scale_RGB_B346(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Scale_RGB_B344(\nfloat Scalar,\nvec4 Color,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Line_Fragment_B362(\nvec4 Base_Color,\nvec4 Highlight_Color,\nfloat Highlight_Width,\nvec3 Line_Vertex,\nfloat Highlight,\nout vec4 Line_Color)\n{float k2=1.0-clamp(abs(Line_Vertex.y/Highlight_Width),0.0,1.0);Line_Color=mix(Base_Color,Highlight_Color,Highlight*k2);}\nvoid Edge_B356(\nvec4 RectParms,\nfloat Radius,\nfloat Line_Width,\nvec2 UV,\nfloat Edge_Width,\nfloat Edge_Power,\nout float Result)\n{float d=length(max(abs(UV)-RectParms.xy,0.0));float edge=1.0-clamp((1.0-d/(Radius-Line_Width))/Edge_Width,0.0,1.0);Result=pow(edge,Edge_Power);}\nvoid Gradient_B355(\nvec4 Gradient_Color,\nvec4 Top_Left,\nvec4 Top_Right,\nvec4 Bottom_Left,\nvec4 Bottom_Right,\nvec2 UV,\nout vec4 Result)\n{vec3 top=Top_Left.rgb+(Top_Right.rgb-Top_Left.rgb)*UV.x;vec3 bottom=Bottom_Left.rgb+(Bottom_Right.rgb-Bottom_Left.rgb)*UV.x;Result.rgb=Gradient_Color.rgb*(bottom+(top-bottom)*UV.y);Result.a=1.0;}\nvoid main()\n{float X_Q338;float Y_Q338;float Z_Q338;float W_Q338;X_Q338=vExtra2.x;Y_Q338=vExtra2.y;Z_Q338=vExtra2.z;W_Q338=vExtra2.w;vec4 Color_Q343;\n#if IRIDESCENCE_ENABLE\nIridescence_B343(vPosition,vNormal,vUV,vBinormal,cameraPosition,_Iridescence_Tint_,_Iridescent_Map_,_Reflected_,_Frequency_,_Vertical_Offset_,Color_Q343);\n#else\nColor_Q343=vec4(0,0,0,0);\n#endif\nvec4 Result_Q344;Scale_RGB_B344(_Iridescence_Intensity_,Color_Q343,Result_Q344);vec4 Line_Color_Q362;Line_Fragment_B362(_Line_Color_,_Highlight_Color_,_Highlight_Width_,vTangent,_Highlight_,Line_Color_Q362);float Result_Q356;\n#if EDGE_ONLY\nEdge_B356(vExtra1,Z_Q338,W_Q338,vUV,_Edge_Width_,_Edge_Power_,Result_Q356);\n#else\nResult_Q356=1.0;\n#endif\nvec2 Vec2_Q339=vec2(X_Q338,Y_Q338);vec4 Result_Q355;Gradient_B355(_Gradient_Color_,_Top_Left_,_Top_Right_,_Bottom_Left_,_Bottom_Right_,Vec2_Q339,Result_Q355);vec4 Linear_Q348;Linear_Q348.rgb=clamp(Result_Q355.rgb*Result_Q355.rgb,0.0,1.0);Linear_Q348.a=Result_Q355.a;vec4 Result_Q346;Scale_RGB_B346(Linear_Q348,Result_Q356,Result_Q346);vec4 Sum_Q345=Result_Q346+Result_Q344;vec4 Color_At_T_Q347=mix(Line_Color_Q362,Result_Q346,_Line_Gradient_Blend_);vec4 Base_And_Iridescent_Q350;Base_And_Iridescent_Q350=_Base_Color_+vec4(Sum_Q345.rgb,0.0);vec4 Sum_Q349=Color_At_T_Q347+_Iridescence_Edge_Intensity_*Color_Q343;vec4 Result_Q351=Sum_Q349; Result_Q351.a=1.0;vec4 Color_Q332;Round_Rect_Fragment_B332(Z_Q338,W_Q338,Result_Q351,_Filter_Width_,vUV,1.0,vExtra1,Base_And_Iridescent_Q350,Color_Q332);vec4 Result_Q354=_Fade_Out_*Color_Q332;vec4 sRGB_Q353;FastLinearTosRGB_B353(Result_Q354,sRGB_Q353);vec4 Out_Color=sRGB_Q353;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";bi.ShadersStore.mrdlBackplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec3 tangent;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;void Object_To_World_Pos_B314(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Round_Rect_Vertex_B357(\nvec2 UV,\nfloat Radius,\nfloat Margin,\nfloat Anisotropy,\nfloat Gradient1,\nfloat Gradient2,\nvec3 Normal,\nvec4 Color_Scale_Translate,\nout vec2 Rect_UV,\nout vec4 Rect_Parms,\nout vec2 Scale_XY,\nout vec2 Line_UV,\nout vec2 Color_UV_Info)\n{Scale_XY=vec2(Anisotropy,1.0);Line_UV=(UV-vec2(0.5,0.5));Rect_UV=Line_UV*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius)-vec2(Margin,Margin);Rect_Parms.z=Gradient1; \nRect_Parms.w=Gradient2;Color_UV_Info=(Line_UV+vec2(0.5,0.5))*Color_Scale_Translate.xy+Color_Scale_Translate.zw;}\nvoid Line_Vertex_B333(\nvec2 Scale_XY,\nvec2 UV,\nfloat Time,\nfloat Rate,\nvec4 Highlight_Transform,\nout vec3 Line_Vertex)\n{float angle2=(Rate*Time)*2.0*3.1416;float sinAngle2=sin(angle2);float cosAngle2=cos(angle2);vec2 xformUV=UV*Highlight_Transform.xy+Highlight_Transform.zw;Line_Vertex.x=0.0;Line_Vertex.y=cosAngle2*xformUV.x-sinAngle2*xformUV.y;Line_Vertex.z=0.0; }\nvoid PickDir_B334(\nfloat Degrees,\nvec3 DirX,\nvec3 DirY,\nout vec3 Dir)\n{float a=Degrees*3.14159/180.0;Dir=cos(a)*DirX+sin(a)*DirY;}\nvoid Move_Verts_B327(\nfloat Anisotropy,\nvec3 P,\nfloat Radius,\nout vec3 New_P,\nout vec2 New_UV,\nout float Radial_Gradient,\nout vec3 Radial_Dir)\n{vec2 UV=P.xy*2.0+0.5;vec2 center=clamp(UV,0.0,1.0);vec2 delta=UV-center;vec2 r2=2.0*vec2(Radius/Anisotropy,Radius);New_UV=center+r2*(UV-2.0*center+0.5);New_P=vec3(New_UV-0.5,P.z);Radial_Gradient=1.0-length(delta)*2.0;Radial_Dir=vec3(delta*r2,0.0);}\nvoid Pick_Radius_B336(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Edge_AA_Vertex_B328(\nvec3 Position_World,\nvec3 Position_Object,\nvec3 Normal_Object,\nvec3 Eye,\nfloat Radial_Gradient,\nvec3 Radial_Dir,\nvec3 Tangent,\nout float Gradient1,\nout float Gradient2)\n{vec3 I=(Eye-Position_World);vec3 T=(vec4(Tangent,0.0)).xyz;float g=(dot(T,I)<0.0) ? 0.0 : 1.0;if (Normal_Object.z==0.0) { \nGradient1=Position_Object.z>0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Object_To_World_Dir_B330(\nvec3 Dir_Object,\nout vec3 Binormal_World,\nout vec3 Binormal_World_N,\nout float Binormal_Length)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;Binormal_Length=length(Binormal_World);Binormal_World_N=Binormal_World/Binormal_Length;}\nvoid RelativeOrAbsoluteDetail_B341(\nfloat Nominal_Radius,\nfloat Nominal_LineWidth,\nbool Absolute_Measurements,\nfloat Height,\nout float Radius,\nout float Line_Width)\n{float scale=Absolute_Measurements ? 1.0/Height : 1.0;Radius=Nominal_Radius*scale;Line_Width=Nominal_LineWidth*scale;}\nvoid main()\n{vec3 Nrm_World_Q326;Nrm_World_Q326=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q329;vec3 Tangent_World_N_Q329;float Tangent_Length_Q329;Tangent_World_Q329=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q329=length(Tangent_World_Q329);Tangent_World_N_Q329=Tangent_World_Q329/Tangent_Length_Q329;vec3 Binormal_World_Q330;vec3 Binormal_World_N_Q330;float Binormal_Length_Q330;Object_To_World_Dir_B330(vec3(0,1,0),Binormal_World_Q330,Binormal_World_N_Q330,Binormal_Length_Q330);float Radius_Q341;float Line_Width_Q341;RelativeOrAbsoluteDetail_B341(_Radius_,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q330,Radius_Q341,Line_Width_Q341);vec3 Dir_Q334;PickDir_B334(_Angle_,Tangent_World_N_Q329,Binormal_World_N_Q330,Dir_Q334);float Result_Q336;Pick_Radius_B336(Radius_Q341,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q336);float Anisotropy_Q331=Tangent_Length_Q329/Binormal_Length_Q330;vec4 Out_Color_Q337=vec4(Result_Q336,Line_Width_Q341,0,1);vec3 New_P_Q327;vec2 New_UV_Q327;float Radial_Gradient_Q327;vec3 Radial_Dir_Q327;Move_Verts_B327(Anisotropy_Q331,position,Result_Q336,New_P_Q327,New_UV_Q327,Radial_Gradient_Q327,Radial_Dir_Q327);vec3 Pos_World_Q314;Object_To_World_Pos_B314(New_P_Q327,Pos_World_Q314);float Gradient1_Q328;float Gradient2_Q328;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B328(Pos_World_Q314,position,normal,cameraPosition,Radial_Gradient_Q327,Radial_Dir_Q327,tangent,Gradient1_Q328,Gradient2_Q328);\n#else\nGradient1_Q328=1.0;Gradient2_Q328=1.0;\n#endif\nvec2 Rect_UV_Q357;vec4 Rect_Parms_Q357;vec2 Scale_XY_Q357;vec2 Line_UV_Q357;vec2 Color_UV_Info_Q357;Round_Rect_Vertex_B357(New_UV_Q327,Result_Q336,0.0,Anisotropy_Q331,Gradient1_Q328,Gradient2_Q328,normal,vec4(1,1,0,0),Rect_UV_Q357,Rect_Parms_Q357,Scale_XY_Q357,Line_UV_Q357,Color_UV_Info_Q357);vec3 Line_Vertex_Q333;Line_Vertex_B333(Scale_XY_Q357,Line_UV_Q357,(20.0),_Rate_,_Highlight_Transform_,Line_Vertex_Q333);float X_Q359;float Y_Q359;X_Q359=Color_UV_Info_Q357.x;Y_Q359=Color_UV_Info_Q357.y;vec4 Vec4_Q358=vec4(X_Q359,Y_Q359,Result_Q336,Line_Width_Q341);vec3 Position=Pos_World_Q314;vec3 Normal=Nrm_World_Q326;vec2 UV=Rect_UV_Q357;vec3 Tangent=Line_Vertex_Q333;vec3 Binormal=Dir_Q334;vec4 Color=Out_Color_Q337;vec4 Extra1=Rect_Parms_Q357;vec4 Extra2=Vec4_Q358;vec4 Extra3=vec4(0,0,0,0);gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vExtra1=Extra1;vExtra2=Extra2;}";class cN extends Oa{constructor(){super(),this.IRIDESCENCE_ENABLE=!0,this.SMOOTH_EDGES=!0,this._needNormals=!0,this.rebuild()}}class uN extends Ra{constructor(e,t){super(e,t),this.radius=.3,this.lineWidth=.003,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Ee(0,0,0,1),this.lineColor=new Ee(.2,.262745,.4,1),this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this._rate=0,this.highlightColor=new Ee(.239216,.435294,.827451,1),this.highlightWidth=0,this._highlightTransform=new _e(1,1,0,0),this._highlight=1,this.iridescenceIntensity=.45,this.iridescenceEdgeIntensity=1,this.iridescenceTint=new Ee(1,1,1,1),this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.gradientColor=new Ee(.74902,.74902,.74902,1),this.topLeftGradientColor=new Ee(.00784314,.294118,.580392,1),this.topRightGradientColor=new Ee(.305882,0,1,1),this.bottomLeftGradientColor=new Ee(.133333,.258824,.992157,1),this.bottomRightGradientColor=new Ee(.176471,.176471,.619608,1),this.edgeWidth=.5,this.edgePower=1,this.edgeLineGradientBlend=.5,this.alphaMode=Yd.ALPHA_DISABLE,this.backFaceCulling=!1,this._iridescentMapTexture=new Vo(uN.IRIDESCENT_MAP_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new cN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlBackplate",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Iridescence_Tint_","_Iridescent_Map_","_Angle_","_Reflected_","_Frequency_","_Vertical_Offset_","_Gradient_Color_","_Top_Left_","_Top_Right_","_Bottom_Left_","_Bottom_Right_","_Edge_Width_","_Edge_Power_","_Line_Gradient_Blend_","_Fade_Out_"],h=["_Iridescent_Map_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setDirectColor4("_Iridescence_Tint_",this.iridescenceTint),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMapTexture),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setDirectColor4("_Gradient_Color_",this.gradientColor),this._activeEffect.setDirectColor4("_Top_Left_",this.topLeftGradientColor),this._activeEffect.setDirectColor4("_Top_Right_",this.topRightGradientColor),this._activeEffect.setDirectColor4("_Bottom_Left_",this.bottomLeftGradientColor),this._activeEffect.setDirectColor4("_Bottom_Right_",this.bottomRightGradientColor),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setFloat("_Edge_Power_",this.edgePower),this._activeEffect.setFloat("_Line_Gradient_Blend_",this.edgeLineGradientBlend),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new uN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLBackplateMaterial",e}getClassName(){return"MRDLBackplateMaterial"}static Parse(e,t,i){return yt.Parse((()=>new uN(e.name,t)),e,t,i)}}uN.IRIDESCENT_MAP_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-backplate-iridescence.png",qe([st()],uN.prototype,"radius",void 0),qe([st()],uN.prototype,"lineWidth",void 0),qe([st()],uN.prototype,"absoluteSizes",void 0),qe([st()],uN.prototype,"baseColor",void 0),qe([st()],uN.prototype,"lineColor",void 0),qe([st()],uN.prototype,"radiusTopLeft",void 0),qe([st()],uN.prototype,"radiusTopRight",void 0),qe([st()],uN.prototype,"radiusBottomLeft",void 0),qe([st()],uN.prototype,"radiusBottomRight",void 0),qe([st()],uN.prototype,"highlightColor",void 0),qe([st()],uN.prototype,"highlightWidth",void 0),qe([st()],uN.prototype,"iridescenceIntensity",void 0),qe([st()],uN.prototype,"iridescenceEdgeIntensity",void 0),qe([st()],uN.prototype,"iridescenceTint",void 0),qe([st()],uN.prototype,"fadeOut",void 0),qe([st()],uN.prototype,"gradientColor",void 0),qe([st()],uN.prototype,"topLeftGradientColor",void 0),qe([st()],uN.prototype,"topRightGradientColor",void 0),qe([st()],uN.prototype,"bottomLeftGradientColor",void 0),qe([st()],uN.prototype,"bottomRightGradientColor",void 0),qe([st()],uN.prototype,"edgeWidth",void 0),qe([st()],uN.prototype,"edgePower",void 0),qe([st()],uN.prototype,"edgeLineGradientBlend",void 0),ee("BABYLON.GUI.MRDLBackplateMaterial",uN);class dN extends Iw{constructor(e,t){super(e),this.onValueChangedObservable=new X,this._sliderBackplateVisible=t||!1,this._minimum=0,this._maximum=100,this._step=0,this._value=50}get mesh(){return this.node?this._sliderThumb:null}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=Math.max(e,0),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=Math.max(e,this._minimum),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get step(){return this._step}set step(e){this._step!==e&&(this._step=Math.max(Math.min(e,this._maximum-this._minimum),0))}get value(){return this._value}set value(e){this._value!==e&&(this._value=Math.max(Math.min(e,this._maximum),this._minimum),this._sliderThumb&&(this._sliderThumb.position.x=this._convertToPosition(this.value)),this.onValueChangedObservable.notifyObservers(this._value))}get start(){return this.node?this._sliderBar.position.x-this._sliderBar.scaling.x/2:-.5}get end(){return this.node?this._sliderBar.position.x+this._sliderBar.scaling.x/2:.5}get sliderBarMaterial(){return this._sliderBarMaterial}get sliderThumbMaterial(){return this._sliderThumbMaterial}get sliderBackplateMaterial(){return this._sliderBackplateMaterial}get sliderBar(){return this._sliderBar}get sliderThumb(){return this._sliderThumb}get sliderBackplate(){return this._sliderBackplate}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this.node?.setEnabled(e))}_createNode(e){const t=yu(`${this.name}_sliderbackplate`,{width:1,height:1,depth:1},e);return t.isPickable=!1,t.visibility=0,t.scaling=new de(1,.5,.8),Pa.ImportMeshAsync(void 0,dN.MODEL_BASE_URL,dN.MODEL_FILENAME,e).then((e=>{e.meshes.forEach((e=>{e.isPickable=!1}));const i=e.meshes[1],s=e.meshes[1].clone(`${this.name}_sliderbar`,t),r=e.meshes[1].clone(`${this.name}_sliderthumb`,t);i.visibility=0,this._sliderBackplateVisible&&(i.visibility=1,i.name=`${this.name}_sliderbackplate`,i.scaling.x=1,i.scaling.z=.2,i.parent=t,this._sliderBackplateMaterial&&(i.material=this._sliderBackplateMaterial),this._sliderBackplate=i),s&&(s.parent=t,s.position.z=-.1,s.scaling=new de(.8,.04,.3),this._sliderBarMaterial&&(s.material=this._sliderBarMaterial),this._sliderBar=s),r&&(r.parent=t,r.isPickable=!0,r.position.z=-.115,r.scaling=new de(.025,.3,.6),r.position.x=this._convertToPosition(this.value),r.addBehavior(this._createBehavior()),this._sliderThumbMaterial&&(r.material=this._sliderThumbMaterial),this._sliderThumb=r),this._injectGUI3DReservedDataStore(t).control=this,t.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this}))})),this._affectMaterial(t),t}_affectMaterial(e){this._sliderBackplateMaterial=this._sliderBackplateMaterial??new uN(`${this.name}_sliderbackplate_material`,e.getScene()),this._sliderBarMaterial=this._sliderBarMaterial??new aN(`${this.name}_sliderbar_material`,e.getScene()),this._sliderThumbMaterial=this._sliderThumbMaterial??new hN(`${this.name}_sliderthumb_material`,e.getScene())}_createBehavior(){const e=new sa({dragAxis:de.Right()});return e.moveAttached=!1,e.onDragStartObservable.add((()=>{this._draggedPosition=this._sliderThumb.position.x})),e.onDragObservable.add((e=>{this._draggedPosition+=e.dragDistance/this.scaling.x,this.value=this._convertToValue(this._draggedPosition)})),e}_convertToPosition(e){const t=(e-this.minimum)/(this.maximum-this.minimum)*(this.end-this.start)+this.start;return Math.min(Math.max(t,this.start),this.end)}_convertToValue(e){let t=(e-this.start)/(this.end-this.start)*(this.maximum-this.minimum);return t=this.step?Math.round(t/this.step)*this.step:t,Math.max(Math.min(this.minimum+t,this._maximum),this._minimum)}dispose(){super.dispose(),this._sliderBar?.dispose(),this._sliderThumb?.dispose(),this._sliderBarMaterial?.dispose(),this._sliderThumbMaterial?.dispose(),this._sliderBackplate?.dispose(),this._sliderBackplateMaterial?.dispose()}}dN.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",dN.MODEL_FILENAME="mrtk-fluent-backplate.glb";class _N extends Nw{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._sphericalMapping(t);switch(e.position=s,this.orientation){case ww.FACEORIGIN_ORIENTATION:i.lookAt(new de(2*s.x,2*s.y,2*s.z));break;case ww.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new de(-s.x,-s.y,-s.z));break;case ww.FACEFORWARD_ORIENTATION:break;case ww.FACEFORWARDREVERSED_ORIENTATION:i.rotate(_r.Y,Math.PI,lr.LOCAL)}}_sphericalMapping(e){const t=new de(0,0,this._radius),i=e.y/this._radius,s=-e.x/this._radius;return fe.RotationYawPitchRollToRef(s,i,0,ge.Matrix[0]),de.TransformNormal(t,ge.Matrix[0])}}class pN extends ww{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e=!1){super(),this._isVertical=!1,this.margin=.1,this._isVertical=e}_arrangeChildren(){let e=0,t=0,i=0;const s=[],r=fe.Invert(this.node.computeWorldMatrix(!0));for(const n of this._children){if(!n.mesh)continue;i++,n.mesh.computeWorldMatrix(!0),n.mesh.getWorldMatrix().multiplyToRef(r,ge.Matrix[0]);const o=n.mesh.getBoundingInfo().boundingBox,a=de.TransformNormal(o.extendSize,ge.Matrix[0]);s.push(a),this._isVertical?t+=a.y:e+=a.x}let n;this._isVertical?t+=(i-1)*this.margin/2:e+=(i-1)*this.margin/2,n=this._isVertical?-t:-e;let o=0;for(const e of this._children){if(!e.mesh)continue;i--;const t=s[o++];this._isVertical?(e.position.y=n+t.y,e.position.x=0,n+=2*t.y):(e.position.x=n+t.x,e.position.y=0,n+=2*t.x),n+=i>0?this.margin:0}}}class fN extends Yw{constructor(e,t){super(t,e),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"TouchMeshButton3D"}_createNode(){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}bi.ShadersStore.mrdlBackglowPixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;float BiasFunc(float b,float v) {return pow(v,log(clamp(b,0.001,0.999))/log(0.5));}\nvoid Fuzzy_Round_Rect_B33(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius_X,\nfloat Radius_Y,\nfloat Line_Width,\nvec2 UV,\nfloat Outer_Fuzz,\nfloat Max_Outer_Fuzz,\nout float Rect_Distance,\nout float Inner_Distance)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius_X,Radius_Y),halfSize),vec2(0.001,0.001));float radius=min(r.x,r.y)-Max_Outer_Fuzz;vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);float d=distance(nearestp,v);Inner_Distance=clamp(1.0-(radius-d)/Line_Width,0.0,1.0);Rect_Distance=clamp(1.0-(d-radius)/Outer_Fuzz,0.0,1.0)*Inner_Distance;}\nvoid main()\n{float X_Q42;float Y_Q42;X_Q42=vNormal.x;Y_Q42=vNormal.y;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Sqrt_F_Q27=sqrt(MaxAB_Q24);float Power_Q43=pow(MaxAB_Q24,_Intensity_Fade_In_Exponent_);float Value_At_T_Q26=mix(_Outer_Fuzz_Start_,_Outer_Fuzz_End_,Sqrt_F_Q27);float Product_Q23=_Max_Intensity_*Power_Q43;float Rect_Distance_Q33;float Inner_Distance_Q33;Fuzzy_Round_Rect_B33(X_Q42,Y_Q42,_Bevel_Radius_,_Bevel_Radius_,_Line_Width_,vUV,Value_At_T_Q26,_Outer_Fuzz_Start_,Rect_Distance_Q33,Inner_Distance_Q33);float Power_Q44=pow(Inner_Distance_Q33,_Blend_Exponent_);float Result_Q45=pow(BiasFunc(_Bias_,Rect_Distance_Q33),_Falloff_);vec4 Color_At_T_Q25=mix(_Inner_Color_,_Color_,Power_Q44);float Product_Q22=Result_Q45*Product_Q23;vec4 Result_Q28=Product_Q22*Color_At_T_Q25;vec4 Out_Color=Result_Q28;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}";bi.ShadersStore.mrdlBackglowVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;varying vec3 vNormal;varying vec2 vUV;void main()\n{vec3 Dir_World_Q41=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q40=(world*vec4((cross(normal,tangent)),0.0)).xyz;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Length_Q16=length(Dir_World_Q41);float Length_Q17=length(Dir_World_Q40);bool Greater_Than_Q37=MaxAB_Q24>0.0;vec3 Sizes_Q35;vec2 XY_Q35;Sizes_Q35=(_Absolute_Sizes_ ? vec3(Length_Q16,Length_Q17,0) : vec3(Length_Q16/Length_Q17,1,0));XY_Q35=(uv-vec2(0.5,0.5))*Sizes_Q35.xy;vec3 Result_Q38=Greater_Than_Q37 ? position : vec3(0,0,0);vec3 Pos_World_Q39=(world*vec4(Result_Q38,1.0)).xyz;vec3 Position=Pos_World_Q39;vec3 Normal=Sizes_Q35;vec2 UV=XY_Q35;vec3 Tangent=vec3(0,0,0);vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;}";class mN extends Oa{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class gN extends Ra{constructor(e,t){super(e,t),this.bevelRadius=.16,this.lineWidth=.16,this.absoluteSizes=!1,this.tuningMotion=0,this.motion=1,this.maxIntensity=.7,this.intensityFadeInExponent=2,this.outerFuzzStart=.04,this.outerFuzzEnd=.04,this.color=new Ee(.682353,.698039,1,1),this.innerColor=new Ee(.356863,.392157,.796078,1),this.blendExponent=1.5,this.falloff=2,this.bias=.5,this.alphaMode=Yd.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new mN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlBackglow",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Bevel_Radius_","_Line_Width_","_Absolute_Sizes_","_Tuning_Motion_","_Motion_","_Max_Intensity_","_Intensity_Fade_In_Exponent_","_Outer_Fuzz_Start_","_Outer_Fuzz_End_","_Color_","_Inner_Color_","_Blend_Exponent_","_Falloff_","_Bias_"],h=[],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Bevel_Radius_",this.bevelRadius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Tuning_Motion_",this.tuningMotion),this._activeEffect.setFloat("_Motion_",this.motion),this._activeEffect.setFloat("_Max_Intensity_",this.maxIntensity),this._activeEffect.setFloat("_Intensity_Fade_In_Exponent_",this.intensityFadeInExponent),this._activeEffect.setFloat("_Outer_Fuzz_Start_",this.outerFuzzStart),this._activeEffect.setFloat("_Outer_Fuzz_End_",this.outerFuzzEnd),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setDirectColor4("_Inner_Color_",this.innerColor),this._activeEffect.setFloat("_Blend_Exponent_",this.blendExponent),this._activeEffect.setFloat("_Falloff_",this.falloff),this._activeEffect.setFloat("_Bias_",this.bias),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new gN(e,this.getScene())),this)}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.MRDLBackglowMaterial",e}getClassName(){return"MRDLBackglowMaterial"}static Parse(e,t,i){return yt.Parse((()=>new gN(e.name,t)),e,t,i)}}qe([st()],gN.prototype,"bevelRadius",void 0),qe([st()],gN.prototype,"lineWidth",void 0),qe([st()],gN.prototype,"absoluteSizes",void 0),qe([st()],gN.prototype,"tuningMotion",void 0),qe([st()],gN.prototype,"motion",void 0),qe([st()],gN.prototype,"maxIntensity",void 0),qe([st()],gN.prototype,"intensityFadeInExponent",void 0),qe([st()],gN.prototype,"outerFuzzStart",void 0),qe([st()],gN.prototype,"outerFuzzEnd",void 0),qe([st()],gN.prototype,"color",void 0),qe([st()],gN.prototype,"innerColor",void 0),qe([st()],gN.prototype,"blendExponent",void 0),qe([st()],gN.prototype,"falloff",void 0),qe([st()],gN.prototype,"bias",void 0),ee("BABYLON.GUI.MRDLBackglowMaterial",gN);bi.ShadersStore.mrdlFrontplatePixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;void Scale_Color_B54(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=Scalar*Color;}\nvoid Scale_RGB_B50(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Proximity_Fragment_B51(\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec4 Deltas,\nfloat Show_Selection,\nfloat Distance_Fade1,\nfloat Distance_Fade2,\nfloat Strength,\nout float Proximity)\n{float proximity1=(1.0-clamp(length(Deltas.xy)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade1;float proximity2=(1.0-clamp(length(Deltas.zw)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade2;Proximity=Strength*(Proximity_Max_Intensity*max(proximity1,proximity2) *(1.0-Show_Selection)+Show_Selection);}\nvoid Blob_Fragment_B56(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvoid Round_Rect_Fragment_B61(\nfloat Radius,\nvec4 Line_Color,\nfloat Filter_Width,\nfloat Line_Visibility,\nvec4 Fill_Color,\nbool Smooth_Edges,\nvec4 Rect_Parms,\nout float Inside_Rect)\n{float d=length(max(abs(Rect_Parms.zw)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);Inside_Rect=Smooth_Edges ? clamp((Radius-d)/dx,0.0,1.0) : 1.0-step(Radius,d);}\nvoid main()\n{float Is_Quad_Q53;Is_Quad_Q53=vNormal.z;vec4 Blob_Color_Q56;Blob_Fragment_B56(vUV,vTangent,_Blob_Texture_,Blob_Color_Q56);float X_Q52;float Y_Q52;float Z_Q52;float W_Q52;X_Q52=vExtra3.x;Y_Q52=vExtra3.y;Z_Q52=vExtra3.z;W_Q52=vExtra3.w;float Proximity_Q51;Proximity_Fragment_B51(_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vExtra2,X_Q52,Y_Q52,Z_Q52,1.0,Proximity_Q51);float Inside_Rect_Q61;Round_Rect_Fragment_B61(W_Q52,vec4(1,1,1,1),_Filter_Width_,1.0,vec4(0,0,0,0),_Smooth_Edges_,vExtra1,Inside_Rect_Q61);vec4 Result_Q50;Scale_RGB_B50(_Edge_Color_,Proximity_Q51,Result_Q50);vec4 Result_Q47=Inside_Rect_Q61*Blob_Color_Q56;vec4 Color_At_T_Q48=mix(Result_Q50,Result_Q47,Is_Quad_Q53);vec4 Result_Q54;Scale_Color_B54(Color_At_T_Q48,_Fade_Out_,Result_Q54);vec4 Out_Color=Result_Q54;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";bi.ShadersStore.mrdlFrontplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;void Blob_Vertex_B40(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nfloat DistanceOffset,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info,\nout vec2 Blob_Relative_UV)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal)+DistanceOffset*Blob_Far_Distance;Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);Blob_Relative_UV=blobClipped/Face_Size.y;}\nvoid Round_Rect_Vertex_B36(\nvec2 UV,\nvec3 Tangent,\nvec3 Binormal,\nfloat Radius,\nfloat Anisotropy,\nvec2 Blob_Center_UV,\nout vec2 Rect_UV,\nout vec2 Scale_XY,\nout vec4 Rect_Parms)\n{Scale_XY=vec2(Anisotropy,1.0);Rect_UV=(UV-vec2(0.5,0.5))*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius);Rect_Parms.zw=Blob_Center_UV;}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B33(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Normal,\nvec3 Tangent,\nvec3 Binormal,\nout vec4 Extra,\nout float Distance_To_Face,\nout float Distance_Fade1,\nout float Distance_Fade2)\n{float distz1,distz2;Extra.xy=ProjectProximity(Blob_Position,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz1)/Relative_Scale;Extra.zw=ProjectProximity(Blob_Position_2,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz2)/Relative_Scale;Distance_To_Face=dot(Normal,Position-Face_Center);Distance_Fade1=1.0-clamp(distz1/Proximity_Far_Distance,0.0,1.0);Distance_Fade2=1.0-clamp(distz2/Proximity_Far_Distance,0.0,1.0);}\nvoid Object_To_World_Pos_B12(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B27(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=Blob_Enable_1 ? 1.0 : 0.0;float b2=Blob_Enable_2 ? 1.0 : 0.0;Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Move_Verts_B32(\nvec2 UV,\nfloat Radius,\nfloat Anisotropy,\nfloat Line_Width,\nfloat Visible,\nout vec3 New_P,\nout vec2 New_UV)\n{vec2 xy=2.0*UV-vec2(0.5,0.5);vec2 center=clamp(xy,0.0,1.0);vec2 delta=2.0*(xy-center);float deltaLength=length(delta);vec2 aniso=vec2(1.0/Anisotropy,1.0);center=(center-vec2(0.5,0.5))*(1.0-2.0*Radius*aniso);New_UV=vec2((2.0-2.0*deltaLength)*Visible,0.0);float deltaRadius= (Radius-Line_Width*New_UV.x);New_P.xy=(center+deltaRadius/deltaLength *aniso*delta);New_P.z=0.0;}\nvoid Object_To_World_Dir_B14(\nvec3 Dir_Object,\nout vec3 Binormal_World)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid Proximity_Visibility_B55(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Face_Center,\nvec3 Normal,\nvec2 Face_Size,\nfloat Gaze,\nout float Width)\n{float boxMaxSize=length(Face_Size)*0.5;float d1=dot(Proximity_Center-Face_Center,Normal);vec3 blob1=Proximity_Center-d1*Normal;float d2=dot(Proximity_Center_2-Face_Center,Normal);vec3 blob2=Proximity_Center_2-d2*Normal;vec3 delta1=blob1-Face_Center;vec3 delta2=blob2-Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));Width=max(Gaze,Width);}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B31(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);Show_Selection=mix(max(select1,select2),1.0,Selected);}\nvoid main()\n{vec3 Vec3_Q29=vec3(vec2(0,0).x,vec2(0,0).y,color.r);vec3 Nrm_World_Q24;Nrm_World_Q24=normalize((world*vec4(normal,0.0)).xyz);vec3 Face_Center_Q30;Face_Center_Q30=(world*vec4(vec3(0,0,0),1.0)).xyz;vec3 Tangent_World_Q13;Tangent_World_Q13=(world*vec4(tangent,0.0)).xyz;vec3 Result_Q42;Result_Q42=_Use_Global_Left_Index_ ? Global_Left_Index_Tip_Position.xyz : _Blob_Position_;vec3 Result_Q43;Result_Q43=_Use_Global_Right_Index_ ? Global_Right_Index_Tip_Position.xyz : _Blob_Position_2_;float Value_At_T_Q58=mix(_Blob_Near_Size_,_Blob_Pulse_Max_Size_,_Blob_Pulse_);float Value_At_T_Q59=mix(_Blob_Near_Size_2_,_Blob_Pulse_Max_Size_,_Blob_Pulse_2_);vec3 Cross_Q70=cross(normal,tangent);float Product_Q45=_Gaze_Intensity_*_Gaze_Focus_;float Step_Q46=step(0.0001,Product_Q45);vec3 Tangent_World_N_Q15=normalize(Tangent_World_Q13);vec3 Position_Q27;float Near_Size_Q27;float Inner_Fade_Q27;float Blob_Enable_Q27;float Fade_Q27;float Pulse_Q27;Choose_Blob_B27(color,Result_Q42,Result_Q43,_Blob_Enable_,_Blob_Enable_2_,Value_At_T_Q58,Value_At_T_Q59,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q27,Near_Size_Q27,Inner_Fade_Q27,Blob_Enable_Q27,Fade_Q27,Pulse_Q27);vec3 Binormal_World_Q14;Object_To_World_Dir_B14(Cross_Q70,Binormal_World_Q14);float Anisotropy_Q21=length(Tangent_World_Q13)/length(Binormal_World_Q14);vec3 Binormal_World_N_Q16=normalize(Binormal_World_Q14);vec2 Face_Size_Q35;float ScaleY_Q35;Face_Size_Q35=vec2(length(Tangent_World_Q13),length(Binormal_World_Q14));ScaleY_Q35=Face_Size_Q35.y;float Out_Radius_Q38;float Out_Line_Width_Q38;Out_Radius_Q38=_Relative_To_Height_ ? _Radius_ : _Radius_/ScaleY_Q35;Out_Line_Width_Q38=_Relative_To_Height_ ? _Line_Width_ : _Line_Width_/ScaleY_Q35;float Show_Selection_Q31;Selection_Vertex_B31(Result_Q42,Result_Q43,Face_Center_Q30,Face_Size_Q35,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,vec3(0,0,-1),Show_Selection_Q31);float MaxAB_Q41=max(Show_Selection_Q31,Product_Q45);float Width_Q55;Proximity_Visibility_B55(Show_Selection_Q31,Result_Q42,Result_Q43,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Face_Center_Q30,Nrm_World_Q24,Face_Size_Q35,Step_Q46,Width_Q55);vec3 New_P_Q32;vec2 New_UV_Q32;Move_Verts_B32(uv,Out_Radius_Q38,Anisotropy_Q21,Out_Line_Width_Q38,Width_Q55,New_P_Q32,New_UV_Q32);vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q32,Pos_World_Q12);vec3 Out_Position_Q40;vec2 Out_UV_Q40;vec3 Blob_Info_Q40;vec2 Blob_Relative_UV_Q40;Blob_Vertex_B40(Pos_World_Q12,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Position_Q27,_Blob_Intensity_,Near_Size_Q27,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q30,Face_Size_Q35,New_UV_Q32,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q27,Pulse_Q27,Fade_Q27,Blob_Enable_Q27,0.0,Out_Position_Q40,Out_UV_Q40,Blob_Info_Q40,Blob_Relative_UV_Q40);vec2 Rect_UV_Q36;vec2 Scale_XY_Q36;vec4 Rect_Parms_Q36;Round_Rect_Vertex_B36(New_UV_Q32,Tangent_World_Q13,Binormal_World_Q14,Out_Radius_Q38,Anisotropy_Q21,Blob_Relative_UV_Q40,Rect_UV_Q36,Scale_XY_Q36,Rect_Parms_Q36);vec4 Extra_Q33;float Distance_To_Face_Q33;float Distance_Fade1_Q33;float Distance_Fade2_Q33;Proximity_Vertex_B33(Result_Q42,Result_Q43,Face_Center_Q30,Pos_World_Q12,_Proximity_Far_Distance_,1.0,_Proximity_Anisotropy_,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Extra_Q33,Distance_To_Face_Q33,Distance_Fade1_Q33,Distance_Fade2_Q33);vec4 Vec4_Q37=vec4(MaxAB_Q41,Distance_Fade1_Q33,Distance_Fade2_Q33,Out_Radius_Q38);vec3 Position=Out_Position_Q40;vec3 Normal=Vec3_Q29;vec2 UV=Out_UV_Q40;vec3 Tangent=Blob_Info_Q40;vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);vec4 Extra1=Rect_Parms_Q36;vec4 Extra2=Extra_Q33;vec4 Extra3=Vec4_Q37;gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;vTangent=Tangent;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class vN extends Oa{constructor(){super(),this.SMOOTH_EDGES=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class xN extends Ra{constructor(e,t){super(e,t),this.radius=.12,this.lineWidth=.01,this.relativeToHeight=!1,this._filterWidth=1,this.edgeColor=new Ee(.53,.53,.53,1),this.blobEnable=!0,this.blobPosition=new de(100,100,100),this.blobIntensity=.5,this.blobNearSize=.032,this.blobFarSize=.048,this.blobNearDistance=.008,this.blobFarDistance=.064,this.blobFadeLength=.04,this.blobInnerFade=.01,this.blobPulse=0,this.blobFade=1,this.blobPulseMaxSize=.05,this.blobEnable2=!0,this.blobPosition2=new de(10,10.1,-.6),this.blobNearSize2=.008,this.blobInnerFade2=.1,this.blobPulse2=0,this.blobFade2=1,this.gazeIntensity=.8,this.gazeFocus=0,this.selectionFuzz=.5,this.selected=1,this.selectionFade=.2,this.selectionFadeSize=0,this.selectedDistance=.08,this.selectedFadeLength=.08,this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=.016,this.proximityAnisotropy=1,this.useGlobalLeftIndex=!0,this.useGlobalRightIndex=!0,this.fadeOut=1,this.alphaMode=Yd.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Vo(xN.BLOB_TEXTURE_URL,t,!0,!1,Vo.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new vN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlFrontplate",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Relative_To_Height_","_Filter_Width_","_Edge_Color_","_Fade_Out_","_Smooth_Edges_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Pulse_Max_Size_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Gaze_Intensity_","_Gaze_Focus_","_Blob_Texture_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","_Use_Global_Left_Index_","_Use_Global_Right_Index_"],h=[],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Relative_To_Height_",this.relativeToHeight?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Edge_Color_",this.edgeColor),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Blob_Enable_",this.blobEnable?1:0),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.blobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setFloat("_Blob_Pulse_Max_Size_",this.blobPulseMaxSize),this._activeEffect.setFloat("_Blob_Enable_2_",this.blobEnable2?1:0),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.blobInnerFade2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Gaze_Intensity_",this.gazeIntensity),this._activeEffect.setFloat("_Gaze_Focus_",this.gazeFocus),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Use_Global_Left_Index_",this.useGlobalLeftIndex?1:0),this._activeEffect.setFloat("_Use_Global_Right_Index_",this.useGlobalRightIndex?1:0),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new xN(e,this.getScene())),this)}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.MRDLFrontplateMaterial",e}getClassName(){return"MRDLFrontplateMaterial"}static Parse(e,t,i){return yt.Parse((()=>new xN(e.name,t)),e,t,i)}}xN.BLOB_TEXTURE_URL="",qe([st()],xN.prototype,"radius",void 0),qe([st()],xN.prototype,"lineWidth",void 0),qe([st()],xN.prototype,"relativeToHeight",void 0),qe([st()],xN.prototype,"edgeColor",void 0),qe([st()],xN.prototype,"blobEnable",void 0),qe([st()],xN.prototype,"blobPosition",void 0),qe([st()],xN.prototype,"blobIntensity",void 0),qe([st()],xN.prototype,"blobNearSize",void 0),qe([st()],xN.prototype,"blobFarSize",void 0),qe([st()],xN.prototype,"blobNearDistance",void 0),qe([st()],xN.prototype,"blobFarDistance",void 0),qe([st()],xN.prototype,"blobFadeLength",void 0),qe([st()],xN.prototype,"blobInnerFade",void 0),qe([st()],xN.prototype,"blobPulse",void 0),qe([st()],xN.prototype,"blobFade",void 0),qe([st()],xN.prototype,"blobPulseMaxSize",void 0),qe([st()],xN.prototype,"blobEnable2",void 0),qe([st()],xN.prototype,"blobPosition2",void 0),qe([st()],xN.prototype,"blobNearSize2",void 0),qe([st()],xN.prototype,"blobInnerFade2",void 0),qe([st()],xN.prototype,"blobPulse2",void 0),qe([st()],xN.prototype,"blobFade2",void 0),qe([st()],xN.prototype,"gazeIntensity",void 0),qe([st()],xN.prototype,"gazeFocus",void 0),qe([st()],xN.prototype,"selectionFuzz",void 0),qe([st()],xN.prototype,"selected",void 0),qe([st()],xN.prototype,"selectionFade",void 0),qe([st()],xN.prototype,"selectionFadeSize",void 0),qe([st()],xN.prototype,"selectedDistance",void 0),qe([st()],xN.prototype,"selectedFadeLength",void 0),qe([st()],xN.prototype,"proximityMaxIntensity",void 0),qe([st()],xN.prototype,"proximityFarDistance",void 0),qe([st()],xN.prototype,"proximityNearRadius",void 0),qe([st()],xN.prototype,"proximityAnisotropy",void 0),qe([st()],xN.prototype,"useGlobalLeftIndex",void 0),qe([st()],xN.prototype,"useGlobalRightIndex",void 0),ee("BABYLON.GUI.MRDLFrontplateMaterial",xN);bi.ShadersStore.mrdlInnerquadPixelShader="uniform vec3 cameraPosition;varying vec2 vUV;varying vec3 vTangent;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;float FilterStep_Bid194(float edge,float x,float filterWidth)\n{float dx=max(1.0E-5,fwidth(x)*filterWidth);return max((x+dx*0.5-max(edge,x-dx*0.5))/dx,0.0);}\nvoid Round_Rect_B194(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius,\nvec4 Rect_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Glow_Fraction,\nfloat Glow_Max,\nfloat Glow_Falloff,\nout vec4 Color)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius,Radius),halfSize),vec2(0.01,0.01));vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);vec2 delta=(v-nearestp)/max(vec2(0.01,0.01),r);float Distance=length(delta);float insideRect=1.0-FilterStep_Bid194(1.0-Glow_Fraction,Distance,Filter_Width);float glow=clamp((1.0-Distance)/Glow_Fraction,0.0,1.0);glow=pow(glow,Glow_Falloff);Color=Rect_Color*max(insideRect,glow*Glow_Max);}\nvoid main()\n{float X_Q192;float Y_Q192;float Z_Q192;X_Q192=vTangent.x;Y_Q192=vTangent.y;Z_Q192=vTangent.z;vec4 Color_Q194;Round_Rect_B194(X_Q192,1.0,Y_Q192,_Color_,_Filter_Width_,vUV,_Glow_Fraction_,_Glow_Max_,_Glow_Falloff_,Color_Q194);vec4 Out_Color=Color_Q194;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}\n";bi.ShadersStore.mrdlInnerquadVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;varying vec2 vUV;varying vec3 vTangent;void main()\n{vec3 Pos_World_Q189;Pos_World_Q189=(world*vec4(position,1.0)).xyz;vec3 Dir_World_Q190;Dir_World_Q190=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q191;Dir_World_Q191=(world*vec4((cross(normal,tangent)),0.0)).xyz;float Length_Q180=length(Dir_World_Q190);float Length_Q181=length(Dir_World_Q191);float Quotient_Q184=Length_Q180/Length_Q181;float Quotient_Q195=_Radius_/Length_Q181;vec2 Result_Q193;Result_Q193=vec2((uv.x-0.5)*Length_Q180/Length_Q181,(uv.y-0.5));float Result_Q198=_Fixed_Radius_ ? Quotient_Q195 : _Radius_;vec3 Vec3_Q183=vec3(Quotient_Q184,Result_Q198,0);vec3 Position=Pos_World_Q189;vec3 Normal=vec3(0,0,0);vec2 UV=Result_Q193;vec3 Tangent=Vec3_Q183;vec3 Binormal=vec3(0,0,0);vec4 Color=color;gl_Position=viewProjection*vec4(Position,1);vUV=UV;vTangent=Tangent;}\n";class bN extends Oa{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class TN extends Ra{constructor(e,t){super(e,t),this.color=new Ee(1,1,1,.05),this.radius=.12,this.fixedRadius=!0,this._filterWidth=1,this.glowFraction=0,this.glowMax=.5,this.glowFalloff=2,this.alphaMode=Yd.ALPHA_COMBINE,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new bN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!0,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlInnerquad",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Color_","_Radius_","_Fixed_Radius_","_Filter_Width_","_Glow_Fraction_","_Glow_Max_","_Glow_Falloff_"],h=[],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Fixed_Radius_",this.fixedRadius?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setFloat("_Glow_Fraction_",this.glowFraction),this._activeEffect.setFloat("_Glow_Max_",this.glowMax),this._activeEffect.setFloat("_Glow_Falloff_",this.glowFalloff),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new TN(e,this.getScene())),this)}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.MRDLInnerquadMaterial",e}getClassName(){return"MRDLInnerquadMaterial"}static Parse(e,t,i){return yt.Parse((()=>new TN(e.name,t)),e,t,i)}}qe([st()],TN.prototype,"color",void 0),qe([st()],TN.prototype,"radius",void 0),qe([st()],TN.prototype,"fixedRadius",void 0),qe([st()],TN.prototype,"glowFraction",void 0),qe([st()],TN.prototype,"glowMax",void 0),qe([st()],TN.prototype,"glowFalloff",void 0),ee("BABYLON.GUI.MRDLInnerquadMaterial",TN);class yN extends Yw{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._backGlow.renderingGroupId=e,this._innerQuad.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=ta("",{size:1},this._backPlate._scene),this._tooltipMesh.position=de.Down().scale(.7).add(de.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._frontPlateCollisionMesh,this._tooltipTexture=Cw.CreateForMesh(this._tooltipMesh);const t=new kD;t.height=.25,t.width=.8,t.cornerRadius=25,t.color="#ffffff",t.thickness=20,t.background="#060668",this._tooltipTexture.addControl(t),this._tooltipTextBlock=new UD,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=100,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new qo,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?.text||null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get subtext(){return this._subtext}set subtext(e){this._subtext!==e&&(this._subtext=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get backGlowMaterial(){return this._backGlowMaterial}get innerQuadMaterial(){return this._innerQuadMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this.width=1,this.height=1,this.radius=.14,this.textSizeInPixels=18,this.imageSizeInPixels=40,this.plateMaterialColor=new Ce(.4,.4,.4),this.frontPlateDepth=.2,this.backPlateDepth=.04,this.backGlowOffset=.1,this.flatPlaneDepth=.001,this.innerQuadRadius=this.radius-.04,this.innerQuadColor=new Ee(0,0,0,0),this.innerQuadToggledColor=new Ee(.5197843,.6485234,.9607843,.6),this.innerQuadHoverColor=new Ee(1,1,1,.05),this.innerQuadToggledHoverColor=new Ee(.5197843,.6485234,.9607843,1),this._isBackplateVisible=!0,this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(1),this.isToggleButton&&this._innerQuadMaterial&&(this.isToggled?this._innerQuadMaterial.color=this.innerQuadToggledHoverColor:this._innerQuadMaterial.color=this.innerQuadHoverColor)},this.pointerOutAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(-.8),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)},this.pointerDownAnimation=()=>{},this.pointerUpAnimation=()=>{},this._pointerClickObserver=this.onPointerClickObservable.add((()=>{this._frontPlate&&this._backGlow&&!this.isActiveNearInteraction&&this._performClickAnimation(),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)})),this._pointerEnterObserver=this.onPointerEnterObservable.add((()=>{this.pointerEnterAnimation()})),this._pointerOutObserver=this.onPointerOutObservable.add((()=>{this.pointerOutAnimation()})),this._toggleObserver=this.onToggleObservable.add((e=>{this._innerQuadMaterial.color=e?this.innerQuadToggledColor:this.innerQuadColor}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){let e;e=this._getAspectRatio()<=1?this._alignContentVertically():this._alignContentHorizontally(),this.content=e}_getAspectRatio(){return this.width/this.height}_alignContentVertically(){const e=new WD;if(e.isVertical=!0,Vt()&&document.createElement&&this._imageUrl){const t=new GD;t.source=this._imageUrl,t.heightInPixels=180,t.widthInPixels=100,t.paddingTopInPixels=40,t.paddingBottomInPixels=40,e.addControl(t)}if(this._text){const t=new UD;t.text=this._text,t.color="white",t.heightInPixels=30,t.fontSize=24,e.addControl(t)}return e}_alignContentHorizontally(){let e=240;const t=15,i=new kD;i.widthInPixels=e,i.heightInPixels=e,i.color="transparent",i.setPaddingInPixels(t,t,t,t),e-=30;const s=new WD;if(s.isVertical=!1,s.scaleY=this._getAspectRatio(),Vt()&&document.createElement&&this._imageUrl){const t=new kD(`${this.name}_image`);t.widthInPixels=this.imageSizeInPixels,t.heightInPixels=this.imageSizeInPixels,t.color="transparent",e-=this.imageSizeInPixels;const i=new GD;i.source=this._imageUrl,t.addControl(i),s.addControl(t)}if(this._text){const i=new UD(`${this.name}_text`);if(i.text=this._text,i.color="white",i.fontSize=this.textSizeInPixels,i.widthInPixels=e,this._imageUrl&&(i.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,i.paddingLeftInPixels=t),this._subtext){const r=new QD;r.addColumnDefinition(1),r.addRowDefinition(.5),r.addRowDefinition(.5),r.widthInPixels=e,r.heightInPixels=45;const n=new UD(`${this.name}_subtext`);n.text=this._subtext,n.color="#EEEEEEAB",n.fontSize=.75*this.textSizeInPixels,n.fontWeight="600",this._imageUrl&&(n.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,n.paddingLeftInPixels=t),r.addControl(i,0),r.addControl(n,1),s.addControl(r)}else s.addControl(i)}return i.addControl(s),i}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=this._createBackPlate(e),i=this._createFrontPlate(e),s=this._createInnerQuad(e),r=this._createBackGlow(e);this._frontPlateCollisionMesh=i,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.scaling.x=this.width,this._textPlate.parent=i,this._backPlate=t,this._backPlate.position=de.Forward(e.useRightHandedSystem).scale(this.backPlateDepth/2),this._backPlate.isPickable=!1,this._backPlate.addChild(i),this._backPlate.addChild(s),r&&this._backPlate.addChild(r);const n=new xn(`${this.name}_root`,e);return this._backPlate.setParent(n),this.collisionMesh=i,this.collidableFrontDirection=this._backPlate.forward.negate(),n}_createBackPlate(e){const t=yu(`${this.name}_backPlate`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=.2,Pa.ImportMeshAsync(void 0,yN.MRTK_ASSET_BASE_URL,yN.BACKPLATE_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.visibility=0,this._isBackplateVisible&&(i.visibility=1,i.name=`${this.name}_backPlate`,i.isPickable=!1,i.scaling.x=this.width,i.scaling.y=this.height,i.parent=t),this._backMaterial&&(i.material=this._backMaterial),this._backPlate=i})),t}_createFrontPlate(e){const t=yu(`${this.name}_frontPlate`,{width:this.width,height:this.height,depth:this.frontPlateDepth},e);return t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=de.Forward(e.useRightHandedSystem).scale((this.backPlateDepth-this.frontPlateDepth)/2),Pa.ImportMeshAsync(void 0,yN.MRTK_ASSET_BASE_URL,yN.FRONTPLATE_MODEL_FILENAME,e).then((i=>{const s=yu(`${this.name}_collisionPlate`,{width:this.width,height:this.height},e);s.isPickable=!1,s.scaling.z=this.frontPlateDepth,s.visibility=0,s.parent=t,this._collisionPlate=s;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.x=this.width-this.backGlowOffset,r.scaling.y=this.height-this.backGlowOffset,r.position=de.Forward(e.useRightHandedSystem).scale(-.5),r.parent=s,this.isToggleButton&&(r.visibility=0),this._frontMaterial&&(r.material=this._frontMaterial),this._textPlate.scaling.x=1,this._textPlate.parent=r,this._frontPlate=r})),t}_createInnerQuad(e){const t=yu(`${this.name}_innerQuad`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-this.flatPlaneDepth,Pa.ImportMeshAsync(void 0,yN.MRTK_ASSET_BASE_URL,yN.INNERQUAD_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_innerQuad`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._innerQuadMaterial&&(i.material=this._innerQuadMaterial),this._innerQuad=i})),t}_createBackGlow(e){if(this.isToggleButton)return;const t=yu(`${this.name}_backGlow`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-2*this.flatPlaneDepth,Pa.ImportMeshAsync(void 0,yN.MRTK_ASSET_BASE_URL,yN.BACKGLOW_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_backGlow`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._backGlowMaterial&&(i.material=this._backGlowMaterial),this._backGlow=i})),t}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=this.plateMaterialColor}_performClickAnimation(){const e=new kr("Click Animation Group"),t=[{name:"backGlowMotion",mesh:this._backGlow,property:"material.motion",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[1,.0144,.0144]},{frame:40,values:[.0027713229489760476,0,0]},{frame:45,values:[.0027713229489760476]}]},{name:"_collisionPlateZSlide",mesh:this._collisionPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[de.Forward(this._collisionPlate._scene.useRightHandedSystem).scale(this.frontPlateDepth/2).z,0,0]},{frame:40,values:[0,.005403332496794331]},{frame:45,values:[0]}]},{name:"_collisionPlateZScale",mesh:this._collisionPlate,property:"scaling.z",keys:[{frame:0,values:[this.frontPlateDepth,0,0]},{frame:20,values:[this.backPlateDepth,0,0]},{frame:40,values:[this.frontPlateDepth,.0054]},{frame:45,values:[this.frontPlateDepth]}]}];for(const i of t){const t=new Nt(i.name,i.property,60,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CYCLE),s=[];for(const e of i.keys)s.push({frame:e.frame,value:e.values[0],inTangent:e.values[1],outTangent:e.values[2],interpolation:e.values[3]});t.setKeys(s),i.mesh&&e.addTargetedAnimation(t,i.mesh)}e.normalize(0,45),e.speedRatio=1,e.play()}_performEnterExitAnimation(e){const t=new kr("Enter Exit Animation Group"),i=[{name:"frontPlateFadeOut",mesh:this._frontPlate,property:"material.fadeOut",keys:[{frame:0,values:[0,0,.025045314830017686,0]},{frame:40,values:[1.00205599570012,.025045314830017686,0,0]}]},{name:"textPlateZSlide",mesh:this._textPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:40,values:[de.Forward(this._textPlate._scene.useRightHandedSystem).scale(-.15).z,0,0]}]}];for(const e of i){const i=new Nt(e.name,e.property,60,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CYCLE),s=[];for(const t of e.keys)s.push({frame:t.frame,value:t.values[0],inTangent:t.values[1],outTangent:t.values[2],interpolation:t.values[3]});i.setKeys(s),e.mesh&&t.addTargetedAnimation(i,e.mesh)}t.normalize(0,45),t.speedRatio=e,t.play()}_createBackMaterial(e){this._backMaterial=this._backMaterial??new uN(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.absoluteSizes=!0,this._backMaterial.radius=this.radius,this._backMaterial.lineWidth=.02}_createFrontMaterial(e){this._frontMaterial=this._frontMaterial??new xN(this.name+"Front Material",e.getScene()),this.frontMaterial.radius=this.innerQuadRadius,this.frontMaterial.fadeOut=0}_createBackGlowMaterial(e){const t=this.radius+.04;this._backGlowMaterial=this._backGlowMaterial??new gN(this.name+"Back Glow Material",e.getScene()),this._backGlowMaterial.bevelRadius=t,this._backGlowMaterial.lineWidth=t,this._backGlowMaterial.motion=0}_createInnerQuadMaterial(e){this._innerQuadMaterial=this._innerQuadMaterial??new TN("inner_quad",e.getScene()),this._innerQuadMaterial.radius=this.innerQuadRadius,this.isToggleButton&&(this._innerQuadMaterial.color=this.innerQuadColor)}_createPlateMaterial(e){this._plateMaterial=this._plateMaterial??new yc(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ce.Black()}_onToggle(e){super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.mrdlBackplateMaterial?this._backMaterial=this._host._touchSharedMaterials.mrdlBackplateMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.mrdlBackplateMaterial=this._backMaterial),this._host._touchSharedMaterials.mrdlFrontplateMaterial?this._frontMaterial=this._host._touchSharedMaterials.mrdlFrontplateMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.mrdlFrontplateMaterial=this._frontMaterial),this._host._touchSharedMaterials.mrdlBackglowMaterial?this._backGlowMaterial=this._host._touchSharedMaterials.mrdlBackglowMaterial:(this._createBackGlowMaterial(e),this._host._touchSharedMaterials.mrdlBackglowMaterial=this._backGlowMaterial),this._host._touchSharedMaterials.mrdlInnerQuadMaterial?this._innerQuadMaterial=this._host._touchSharedMaterials.mrdlInnerQuadMaterial:(this._createInnerQuadMaterial(e),this._host._touchSharedMaterials.mrdlInnerQuadMaterial=this._innerQuadMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e),this._createBackGlowMaterial(e),this._createInnerQuadMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._backGlow&&(this._backGlow.material=this._backGlowMaterial),this._innerQuad&&(this._innerQuad.material=this._innerQuadMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerClickObservable.remove(this._pointerClickObserver),this.onPointerEnterObservable.remove(this._pointerEnterObserver),this.onPointerOutObservable.remove(this._pointerOutObserver),this.onToggleObservable.remove(this._toggleObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._backGlowMaterial.dispose(),this._innerQuadMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}yN.MRTK_ASSET_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",yN.FRONTPLATE_MODEL_FILENAME="mrtk-fluent-frontplate.glb",yN.BACKPLATE_MODEL_FILENAME="mrtk-fluent-backplate.glb",yN.BACKGLOW_MODEL_FILENAME="mrtk-fluent-button.glb",yN.INNERQUAD_MODEL_FILENAME="SlateProximity.glb";class SN{get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get controlScaling(){return this._customControlScaling}set controlScaling(e){if(this._customControlScaling!==e&&e>0){const t=e/this._customControlScaling;this._customControlScaling=e,this._rootContainer.children.forEach((i=>{i.scaling.scaleInPlace(t),1!==e&&(i._isScaledByManager=!0)}))}}get useRealisticScaling(){return this.controlScaling===SN.MRTK_REALISTIC_SCALING}set useRealisticScaling(e){this.controlScaling=e?SN.MRTK_REALISTIC_SCALING:1}constructor(e){this._customControlScaling=1,this._lastControlOver={},this._lastControlDown={},this.onPickedPointChangedObservable=new X,this.onPickingObservable=new X,this._sharedMaterials={},this._touchSharedMaterials={},this._scene=e||se.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>{this._sceneDisposeObserver=null,this._utilityLayer=null,this.dispose()})),this._utilityLayer=uu._CreateDefaultUtilityLayerFromScene(this._scene),this._utilityLayer.onlyCheckPointerDownEvents=!1,this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.mainSceneTrackerPredicate=e=>e&&e.reservedDataStore?.GUI3D?.control?._node,this._rootContainer=new ww("RootContainer"),this._rootContainer._host=this;const t=this._utilityLayer.utilityLayerScene;this._pointerOutObserver=this._utilityLayer.onPointerOutObservable.add((e=>{this._handlePointerOut(e,!0)})),this._pointerObserver=t.onPointerObservable.add((e=>{this._doPicking(e)})),this._utilityLayer.utilityLayerScene.autoClear=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,new cu("hemi",de.Up(),this._utilityLayer.utilityLayerScene)}_handlePointerOut(e,t){const i=this._lastControlOver[e];i&&(i._onPointerOut(i),delete this._lastControlOver[e]),t&&this._lastControlDown[e]&&(this._lastControlDown[e].forcePointerUp(),delete this._lastControlDown[e]),this.onPickedPointChangedObservable.notifyObservers(null)}_doPicking(e){if(!this._utilityLayer||!this._utilityLayer.shouldRender||!this._utilityLayer.utilityLayerScene.activeCamera)return!1;const t=e.event,i=t.pointerId||0,s=t.button,r=e.pickInfo;if(r&&this.onPickingObservable.notifyObservers(r.pickedMesh),!r||!r.hit)return this._handlePointerOut(i,e.type===Ms.POINTERUP),!1;r.pickedPoint&&this.onPickedPointChangedObservable.notifyObservers(r.pickedPoint);const n=r.pickedMesh.reservedDataStore?.GUI3D?.control;return n&&!n._processObservables(e.type,r.pickedPoint,r.originMesh?.position||null,i,s)&&e.type===Ms.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i]),delete this._lastControlOver[i]),e.type===Ms.POINTERUP&&(this._lastControlDown[t.pointerId]&&(this._lastControlDown[t.pointerId].forcePointerUp(),delete this._lastControlDown[t.pointerId]),("touch"===t.pointerType||"xr"===t.pointerType&&this._scene.getEngine().hostInformation.isMobile)&&this._handlePointerOut(i,!1)),!0}get rootContainer(){return this._rootContainer}containsControl(e){return this._rootContainer.containsControl(e)}addControl(e){return this._rootContainer.addControl(e),1!==this._customControlScaling&&(e.scaling.scaleInPlace(this._customControlScaling),e._isScaledByManager=!0),this}removeControl(e){return this._rootContainer.removeControl(e),e._isScaledByManager&&(e.scaling.scaleInPlace(1/this._customControlScaling),e._isScaledByManager=!1),this}dispose(){this._rootContainer.dispose();for(const e in this._sharedMaterials)Object.prototype.hasOwnProperty.call(this._sharedMaterials,e)&&this._sharedMaterials[e].dispose();this._sharedMaterials={};for(const e in this._touchSharedMaterials)Object.prototype.hasOwnProperty.call(this._touchSharedMaterials,e)&&this._touchSharedMaterials[e].dispose();this._touchSharedMaterials={},this._pointerOutObserver&&this._utilityLayer&&(this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver),this._pointerOutObserver=null),this.onPickedPointChangedObservable.clear(),this.onPickingObservable.clear();const e=this._utilityLayer?this._utilityLayer.utilityLayerScene:null;e&&this._pointerObserver&&(e.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=null),this._scene&&this._sceneDisposeObserver&&(this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null),this._utilityLayer&&this._utilityLayer.dispose()}}function CN(e,t,i,s){const r={externalResourceFunction:s};return i&&(r.uri="file:"===t?i:t+i),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,r):GLTFValidator.validateString(e,r)}function EN(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":CN(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,s)=>{const r=e.length;e.push({resolve:i,reject:s}),postMessage({id:"getExternalResource",index:r,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}SN.MRTK_REALISTIC_SCALING=.032;class AN{static ValidateAsync(e,t,i,s){return"function"==typeof Worker?new Promise(((r,n)=>{const o=`${CN}(${EN})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),n(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":s(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),r(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),n(t.reason),l.terminate()}};if(l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:hs.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const s=e.slice();l.postMessage({id:"validate",data:s,rootUrl:t,fileName:i},[s.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=hs.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>CN(e,t,i,s))))}}function PN(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}var RN,IN,MN,ON,DN,wN,NN,FN,BN,LN,kN,VN;AN.Configuration={url:`${hs._DefaultCdnUrl}/gltf_validator.js`},function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(RN||(RN={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(IN||(IN={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(MN||(MN={}));class UN{constructor(){this.onParsedObservable=new X,this.coordinateSystemMode=RN.AUTO,this.animationStartMode=IN.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new X,this.onSkinLoadedObservable=new X,this.onTextureLoadedObservable=new X,this.onMaterialLoadedObservable=new X,this.onCameraLoadedObservable=new X,this.onCompleteObservable=new X,this.onErrorObservable=new X,this.onDisposeObservable=new X,this.onExtensionLoadedObservable=new X,this.validate=!1,this.onValidatedObservable=new X,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new X,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,s,r,n,o,a){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,s,o,a),null;this._progressCallback=r;const l=t.name||hs.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&we.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new X},r={readAsync:(i,s)=>new Promise(((r,n)=>{this._loadFile(e,t,(e=>{r(new Uint8Array(e))}),!0,(e=>{n(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+s-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new TR(r)).then((e=>{i.onCompleteObservable.notifyObservers(i),s(e)}),o?e=>o(void 0,e):void 0),i}return this._loadFile(e,t,(t=>{this._validate(e,new Uint8Array(t,0,t.byteLength),i,l),this._unpackBinaryAsync(new TR({readAsync:(e,i)=>PN(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),o?e=>o(void 0,e):void 0)}),!0,o)}return this._loadFile(e,t,(t=>{this._validate(e,t,i,l),s({json:this._parseJson(t)})}),!1,o)}_loadBinary(e,t,i,s,r,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new TR({readAsync:(e,i)=>function(e,t,i){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+i>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(e){return Promise.reject(e)}}(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,i,s,r,n){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,s,r,n))))}loadAsync(e,t,i,s,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,s,r))))}loadAssetContainerAsync(e,t,i,s,r){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const n=new Eo(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,n,t,i,s,r).then((e=>(Array.prototype.push.apply(n.geometries,e.geometries),Array.prototype.push.apply(n.meshes,e.meshes),Array.prototype.push.apply(n.particleSystems,e.particleSystems),Array.prototype.push.apply(n.skeletons,e.skeletons),Array.prototype.push.apply(n.animationGroups,e.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,a),Array.prototype.push.apply(n.lights,e.lights),Array.prototype.push.apply(n.transformNodes,e.transformNodes),Array.prototype.push.apply(n.cameras,l),Array.prototype.push.apply(n.morphTargetManagers,h),n)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+UN._MagicBase64Encoded)||e.startsWith("data:;base64,"+UN._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+UN._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+UN._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+UN._MagicBase64Encoded)||t.startsWith(";base64,"+UN._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+UN._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+UN._MagicBase64Encoded)){const i=es(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new TR({readAsync:(e,t)=>PN(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new UN}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(MN[this._state]))}_loadFile(e,t,i,s,r,n){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,s,r,n);return o.onCompleteObservable.add((e=>{this._requests.splice(this._requests.indexOf(e),1)})),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,s=0,r=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;i=i&&e._lengthComputable,s+=e._loaded,r+=e._total}this._progressCallback({lengthComputable:i,loaded:s,total:i?r:0})}_validate(e,t,i="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),AN.ValidateAsync(t,i,s,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0).then((e=>new Uint8Array(e,0,e.byteLength))))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),hs.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()})))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const i=UN._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=UN._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(UN._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:UN._CreateGLTF1Loader,2:UN._CreateGLTF2Loader}[i.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then((()=>{const t=e.readUint32();if(1179937895!==t)throw new Qt("Unexpected magic: "+t,Yt.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const s=e.readUint32();let r;switch(this.useRangeRequests||s===e.buffer.byteLength||we.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`),i){case 1:r=this._unpackBinaryV1Async(e,s);break;case 2:r=this._unpackBinaryV2Async(e,s);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),r}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),s=e.readUint32();if(0!==s)throw new Error(`Unexpected content format: ${s}`);const r=t-e.byteOffset,n={json:this._parseJson(e.readString(i)),bin:null};if(0!==r){const t=e.byteOffset;n.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:r}}return Promise.resolve(n)}_unpackBinaryV2Async(e,t){const i=1313821514,s=e.readUint32();if(e.readUint32()!==i)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then((()=>({json:this._parseJson(e.readString(s)),bin:null}))):e.loadAsync(s+8).then((()=>{const r={json:this._parseJson(e.readString(s)),bin:null},n=()=>{const s=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;r.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:s},e.skipBytes(s);break}default:e.skipBytes(s)}return e.byteOffset!==t?e.loadAsync(8).then(n):Promise.resolve(r)};return n()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minorn.byteLength)throw new Error("Buffer access is out of range");const o=n.buffer;switch(i+=n.byteOffset,r){case ON.BYTE:return new Int8Array(o,i,s);case ON.UNSIGNED_BYTE:return new Uint8Array(o,i,s);case ON.SHORT:return new Int16Array(o,i,s);case ON.UNSIGNED_SHORT:return new Uint16Array(o,i,s);default:return new Float32Array(o,i,s)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],s=t.count*GN.GetByteStrideFromType(t);return GN.GetBufferFromBufferView(e,i,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let s=0;s=this._maxPos}}const WN=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],HN=["world","view","projection","worldView","worldViewProjection","mBones"],XN=["translation","rotation","scale"],YN=["position","rotationQuaternion","scaling"],QN=(e,t,i)=>{for(const s in e){const r=e[s];i[t][s]=r}},jN=e=>{if(e)for(let t=0;t{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},$N=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=de.FromArray(e.scale||[1,1,1]),s=pe.FromArray(e.rotation||[0,0,0,1]),r=de.FromArray(e.translation||[0,0,0]);t=fe.Compose(i,s,r)}else t=fe.FromArray(e.matrix);return t},qN=(e,t,i,s)=>{for(let e=0;e{for(let i=0;i{const i=e.nodes;let s=i[t];if(s)return{node:s,id:t};for(const e in i)if(s=i[e],s.jointName===t)return{node:s,id:e};return null},eF=(e,t)=>{for(let i=0;i{if(r||(e.scene._blockEntityCollection=!!e.assetContainer,(r=new bo(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.id=s),!t.babylonNode)return r;const n=[];let o=null;const a=[],l=[],h=[],c=[];for(let t=0;t1?(u=new _o("multimat"+s,e.scene),u.subMaterials=n):u=new yc("multimat"+s,e.scene),1===n.length&&(u=n[0]),u._parentContainer=e.assetContainer,r.material||(r.material=u),new _n(s,e.scene,o,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let d=0;for(let t=0;t{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=s)},sF=(e,t,i)=>{let s=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const r=e.skins[t.skin],n=tF(e,t,t.meshes,i,t.babylonNode);n.skeleton=e.scene.getLastSkeletonById(t.skin),null===n.skeleton&&(n.skeleton=((e,t,i,s)=>{if(s||(s=new Ho(t.name||"","",e.scene)),!t.babylonSkeleton)return s;const r=[],n=[];((e,t,i,s)=>{for(const r in e.nodes){const n=e.nodes[r],o=r;if(!n.jointName||eF(i,n.jointName))continue;const a=$N(n),l=new pr(n.name||"",t,null,a);l.id=o,s.push({bone:l,node:n,id:o})}for(let e=0;e0&&(u=ZN(r,l),u&&-1===n.indexOf(u)&&n.push(u)),new pr(a.jointName||"",s,u,d).id=l}const o=s.bones;s.bones=[];for(let i=0;i{if(t.matrix){const i=new de(0,0,0),s=new pe,r=new de(0,0,0);fe.FromArray(t.matrix).decompose(r,s,i),iF(e,i,s,r)}else t.translation&&t.rotation&&t.scale&&iF(e,de.FromArray(t.translation),pe.FromArray(t.rotation),de.FromArray(t.scale));e.computeWorldMatrix(!0)})(s,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],r=t.scale||[1,1,1];iF(s,de.FromArray(e),pe.FromArray(i),de.FromArray(r))}s.updateCache(!0),t.babylonNode=s}return s},rF=(e,t,i,s=!1)=>{const r=e.nodes[t];let n=null;if(s=!(e.importOnlyMeshes&&!s&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(r.name||"")||0===e.importMeshesNames.length,!r.jointName&&s&&(n=sF(e,r,t),null!==n&&(n.id=t,n.parent=i)),r.children)for(let t=0;t{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let s=null;for(let r=0;r{for(const s in t.uniforms){const r=t.uniforms[s],n=t.parameters[r];if(e.currentIdentifier===s&&n.semantic&&!n.source&&!n.node){const e=WN.indexOf(n.semantic);if(-1!==e)return delete i[s],HN[e]}}return e.currentIdentifier},aF=e=>{for(const t in e.materials)cF.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class lF{static CreateRuntime(e,t,i){const s={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&QN(e.extensions,"extensions",s),e.extensionsUsed&&QN(e.extensionsUsed,"extensionsUsed",s),e.buffers&&((e,t)=>{for(const i in e){const s=e[i];t.buffers[i]=s,t.buffersCount++}})(e.buffers,s),e.bufferViews&&QN(e.bufferViews,"bufferViews",s),e.accessors&&QN(e.accessors,"accessors",s),e.meshes&&QN(e.meshes,"meshes",s),e.lights&&QN(e.lights,"lights",s),e.cameras&&QN(e.cameras,"cameras",s),e.nodes&&QN(e.nodes,"nodes",s),e.images&&QN(e.images,"images",s),e.textures&&QN(e.textures,"textures",s),e.shaders&&((e,t)=>{for(const i in e){const s=e[i];t.shaders[i]=s,t.shaderscount++}})(e.shaders,s),e.programs&&QN(e.programs,"programs",s),e.samplers&&QN(e.samplers,"samplers",s),e.techniques&&QN(e.techniques,"techniques",s),e.materials&&QN(e.materials,"materials",s),e.animations&&QN(e.animations,"animations",s),e.skins&&QN(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];hs.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(hs.DecodeBase64(n.uri))))):hs.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),r,void 0,!0,(e=>{e&&s(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source)return void s("");if(r.babylonTexture)return void i(null);const n=e.images[r.source];hs.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(hs.DecodeBase64(n.uri))))):hs.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&s(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture)return void s(r.babylonTexture);const n=e.samplers[r.sampler],o=n.minFilter===FN.NEAREST_MIPMAP_NEAREST||n.minFilter===FN.NEAREST_MIPMAP_LINEAR||n.minFilter===FN.LINEAR_MIPMAP_NEAREST||n.minFilter===FN.LINEAR_MIPMAP_LINEAR,a=Vo.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),u=new Vo(h,e.scene,!o,!0,a,c,c);void 0!==n.wrapS&&(u.wrapU=GN.GetWrapMode(n.wrapS)),void 0!==n.wrapT&&(u.wrapV=GN.GetWrapMode(n.wrapT)),u.name=t,r.babylonTexture=u,s(u)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(hs.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);i&&i(e)}else hs.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,(e=>{e&&s&&s(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique)return void(s&&s("No technique found."));const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const s=new yc(t,e.scene);return s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.diffuseColor=new Ce(.5,.5,.5),s.sideOrientation=uo.CounterClockWiseSideOrientation,void i(s)}const o=e.programs[n.program],a=n.states,l=Ti.ShadersStore[o.vertexShader+"VertexShader"],h=Ti.ShadersStore[o.fragmentShader+"PixelShader"];let c="",u="";const d=new zN(l),_=new zN(h),p={},f=[],m=[],g=[];for(const e in n.uniforms){const t=n.uniforms[e],i=n.parameters[t];if(p[e]=i,!i.semantic||i.node||i.source)i.type===wN.SAMPLER_2D?g.push(e):f.push(e);else{const t=WN.indexOf(i.semantic);-1!==t?(f.push(HN[t]),delete p[e]):f.push(e)}}for(const e in n.attributes){const t=n.attributes[e],i=n.parameters[t];if(i.semantic){const e=KN(i);e&&m.push(e)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==VN.IDENTIFIER){c+=d.currentString;continue}let e=!1;for(const t in n.attributes){const i=n.attributes[t],s=n.parameters[i];if(d.currentIdentifier===t&&s.semantic){c+=KN(s),e=!0;break}}e||(c+=oF(d,n,p))}for(;!_.isEnd()&&_.getNextToken();)_.currentToken===VN.IDENTIFIER?u+=oF(_,n,p):u+=_.currentString;const v={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},x={attributes:m,uniforms:f,samplers:g,needAlphaBlending:a&&a.enable&&-1!==a.enable.indexOf(3042)};Ti.ShadersStore[o.vertexShader+t+"VertexShader"]=c,Ti.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const b=new Yu(t,e.scene,v,x);if(b.onError=((e,t,i)=>(s,r)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+r+". Default material will be applied")})(o,b,s),b.onCompiled=((e,t,i,s,r,n)=>o=>{((e,t,i,s,r)=>{const n=s.values||i.parameters,o=i.uniforms;for(const i in r){const a=r[i],l=a.type;let h=n[o[i]];if(void 0===h&&(h=a.value),!h)continue;const c=e=>i=>{a.value&&e&&(t.setTexture(e,i),delete r[e])};l===wN.SAMPLER_2D?cF.LoadTextureAsync(e,s.values?h:a.value,c(i),(()=>c(null))):a.value&&GN.SetUniform(t,i,s.values?h:a.value,l)&&delete r[i]}})(e,t,i,s,r),t.onBind=o=>{((e,t,i,s,r,n,o)=>{const a=n.values||r.parameters;for(const o in i){const l=i[o],h=l.type;if(h===wN.FLOAT_MAT2||h===wN.FLOAT_MAT3||h===wN.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;GN.SetMatrix(t.scene,e,l,o,s.getEffect())}}else GN.SetMatrix(t.scene,e,l,o,s.getEffect());else{const e=a[r.uniforms[o]];if(!e)continue;if(h===wN.SAMPLER_2D){const i=t.textures[n.values?e:l.value].babylonTexture;if(null==i)continue;s.getEffect().setTexture(o,i)}else GN.SetUniform(s.getEffect(),o,e,h)}}o(s)})(o,e,r,t,i,s,n)}})(e,b,n,r,p,i),b.sideOrientation=uo.CounterClockWiseSideOrientation,a&&a.functions){const e=a.functions;e.cullFace&&e.cullFace[0]!==LN.BACK&&(b.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===kN.SRC_ALPHA&&t[1]===kN.ONE_MINUS_SRC_ALPHA&&t[2]===kN.ONE&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_COMBINE:t[0]===kN.ONE&&t[1]===kN.ONE&&t[2]===kN.ZERO&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_ONEONE:t[0]===kN.SRC_ALPHA&&t[1]===kN.ONE&&t[2]===kN.ZERO&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_ADD:t[0]===kN.ZERO&&t[1]===kN.ONE_MINUS_SRC_COLOR&&t[2]===kN.ONE&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_SUBTRACT:t[0]===kN.DST_COLOR&&t[1]===kN.ZERO&&t[2]===kN.ONE&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_MULTIPLY:t[0]===kN.SRC_ALPHA&&t[1]===kN.ONE_MINUS_SRC_COLOR&&t[2]===kN.ONE&&t[3]===kN.ONE&&(b.alphaMode=Yd.ALPHA_MAXIMIZED))}}}class hF{static RegisterExtension(e){hF.Extensions[e.name]?hs.Error('Tool with the same name "'+e.name+'" already exists'):hF.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,o,a){return t.useRightHandedSystem=!0,cF.LoadRuntimeAsync(t,i,s,(t=>{t.assetContainer=r,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],hs.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=[],s=[];for(const e in t.nodes){const s=t.nodes[e];s.babylonNode instanceof Sn&&i.push(s.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof Ho&&s.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{aF(t),nF(t),!UN.IncrementalLoading&&n&&n(i,s)}))})),UN.IncrementalLoading&&n&&n(i,s)}),a),!0}importMeshAsync(e,t,i,s,r,n){return new Promise(((o,a)=>{this._importMeshAsync(e,t,s,r,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})}),n,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,cF.LoadRuntimeAsync(e,t,i,(e=>{cF.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{aF(e),nF(e),UN.IncrementalLoading||s()}))})),UN.IncrementalLoading&&s()}),n)}),n)}loadAsync(e,t,i,s){return new Promise(((r,n)=>{this._loadAsync(e,t,i,(()=>{r()}),s,(e=>{n(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const s=(i,s)=>{cF.LoadShaderStringAsync(e,i,(r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(Ti.ShadersStore[i+(s.type===DN.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{hs.Error("Error when loading shader program named "+i+" located at "+s.uri)}))};for(const t in e.shaders){i=!0;const r=e.shaders[t];r?s.bind(this,t,r)():hs.Error("No shader named: "+t)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(i,s)=>{cF.LoadBufferAsync(e,i,(r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[i].byteLength&&hs.Error("Buffer named "+i+" is length "+r.byteLength+". Expected: "+s.byteLength),e.loadedBufferViews[i]=r),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{hs.Error("Error when loading buffer named "+i+" located at "+s.uri)}))};for(const t in e.buffers){i=!0;const r=e.buffers[t];r?s.bind(this,t,r)():hs.Error("No buffer named: "+t)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,s,r)),(()=>{setTimeout((()=>{s&&s(lF.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){cF._ApplyExtensions((s=>s.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,s,r){cF._ApplyExtensions((n=>n.loadBufferAsync(e,t,i,s,r)),(()=>{lF.LoadBufferAsync(e,t,i,s,r)}))}static LoadTextureAsync(e,t,i,s){cF._LoadTextureBufferAsync(e,t,(r=>{r&&cF._CreateTextureAsync(e,t,r,i,s)}),s)}static LoadShaderStringAsync(e,t,i,s){cF._ApplyExtensions((r=>r.loadShaderStringAsync(e,t,i,s)),(()=>{lF.LoadShaderStringAsync(e,t,i,s)}))}static LoadMaterialAsync(e,t,i,s){cF._ApplyExtensions((r=>r.loadMaterialAsync(e,t,i,s)),(()=>{lF.LoadMaterialAsync(e,t,i,s)}))}static _LoadTextureBufferAsync(e,t,i,s){cF._ApplyExtensions((r=>r.loadTextureBufferAsync(e,t,i,s)),(()=>{lF.LoadTextureBufferAsync(e,t,i,s)}))}static _CreateTextureAsync(e,t,i,s,r){cF._ApplyExtensions((n=>n.createTextureAsync(e,t,i,s,r)),(()=>{lF.CreateTextureAsync(e,t,i,s)}))}static _ApplyExtensions(e,t){for(const t in hF.Extensions)if(e(hF.Extensions[t]))return;t()}}function uF(e,t,i,s){return de.FromArray(t,i).scaleInPlace(s)}UN._CreateGLTF1Loader=()=>new hF,hF.RegisterExtension(new class extends cF{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!(!r||-1===r.indexOf(this.name)||!t.bin||(this._bin=t.bin,s(lF.CreateRuntime(t.json,e,i)),0))}loadBufferAsync(e,t,i,s){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>s(e.message))),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],o=e.bufferViews[n.bufferView];return i(GN.GetBufferFromBufferView(e,o,0,o.byteLength,ON.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],o=GN.GetBufferFromBufferView(e,n,0,n.byteLength,ON.UNSIGNED_BYTE);return setTimeout((()=>{const e=GN.DecodeBufferToText(o);i(e)})),!0}}),hF.RegisterExtension(new class extends cF{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const t in i){const s=i[t];switch(s.type){case"ambient":{const t=new cu(s.name,new de(0,1,0),e.scene),i=s.ambient;i&&(t.diffuse=Ce.FromArray(i.color||[1,1,1]));break}case"point":{const t=new ov(s.name,new de(10,10,10),e.scene),i=s.point;i&&(t.diffuse=Ce.FromArray(i.color||[1,1,1]));break}case"directional":{const t=new lm(s.name,new de(0,-1,0),e.scene),i=s.directional;i&&(t.diffuse=Ce.FromArray(i.color||[1,1,1]));break}case"spot":{const t=s.spot;t&&(new um(s.name,new de(0,10,0),new de(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene).diffuse=Ce.FromArray(t.color||[1,1,1]));break}default:hs.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const o=new yc(t,e.scene);return o.sideOrientation=uo.CounterClockWiseSideOrientation,"CONSTANT"===n.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==n.doubleSided&&!n.doubleSided,o.alpha=void 0===n.values.transparency?1:n.values.transparency,o.specularPower=void 0===n.values.shininess?0:n.values.shininess,"string"==typeof n.values.ambient?this._loadTexture(e,n.values.ambient,o,"ambientTexture",s):o.ambientColor=Ce.FromArray(n.values.ambient||[0,0,0]),"string"==typeof n.values.diffuse?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",s):o.diffuseColor=Ce.FromArray(n.values.diffuse||[0,0,0]),"string"==typeof n.values.emission?this._loadTexture(e,n.values.emission,o,"emissiveTexture",s):o.emissiveColor=Ce.FromArray(n.values.emission||[0,0,0]),"string"==typeof n.values.specular?this._loadTexture(e,n.values.specular,o,"specularTexture",s):o.specularColor=Ce.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){lF.LoadTextureBufferAsync(e,t,(r=>{lF.CreateTextureAsync(e,t,r,(e=>i[s]=e))}),r)}});class dF{constructor(e,t,i,s){this.type=e,this.name=t,this.getValue=i,this.getStride=s}_buildAnimation(e,t,i){const s=new Nt(e,this.name,t,this.type);return s.setKeys(i),s}}class _F extends dF{buildAnimations(e,t,i,s,r){r(e._babylonTransformNode,this._buildAnimation(t,i,s))}}const pF={translation:[new _F(Nt.ANIMATIONTYPE_VECTOR3,"position",uF,(()=>3))],rotation:[new _F(Nt.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,s){return pe.FromArray(t,i).scaleInPlace(s)}),(()=>4))],scale:[new _F(Nt.ANIMATIONTYPE_VECTOR3,"scaling",uF,(()=>3))],weights:[new class extends dF{buildAnimations(e,t,i,s,r){if(e._numMorphTargets)for(let n=0;n({frame:e.frame,inTangent:e.inTangent?e.inTangent[n]:void 0,value:e.value[n],outTangent:e.outTangent?e.outTangent[n]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(n),i=o.clone();e.animations.push(i),r(e,i)}}}}(Nt.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,s){const r=new Array(e._numMorphTargets);for(let e=0;ee._numMorphTargets))]};function fF(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((s=>{const r=e[s],n=i[s];Array.isArray(r)&&Array.isArray(n)?e[s]=r.concat(...n):t(r)&&t(n)?e[s]=fF(r,n):e[s]=n})),e)),{})}class mF{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,r,n,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let n=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);n=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(r,o,n,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,i,s,r=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,(()=>{})))))}_loadAsync(e,t,i,s){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${MN[MN.LOADING]} => ${MN[MN.READY]}`,n=`${MN[MN.LOADING]} => ${MN[MN.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(MN.LOADING),this._extensionsOnLoading();const o=new Array,a=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=mF.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e{})))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=a:this._babylonScene._forceBlockMaterialDirtyMechanism(a),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(MN.READY),this._startAnimations(),s()))).then((e=>(this._parent._endPerformanceCounter(r),hs.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(n),this._parent._setState(MN.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&we.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else we.Warn("Unexpected BIN chunk")}}_setupData(){if(mF.Assign(this._gltf.accessors),mF.Assign(this._gltf.animations),mF.Assign(this._gltf.buffers),mF.Assign(this._gltf.bufferViews),mF.Assign(this._gltf.cameras),mF.Assign(this._gltf.images),mF.Assign(this._gltf.materials),mF.Assign(this._gltf.meshes),mF.Assign(this._gltf.nodes),mF.Assign(this._gltf.samplers),mF.Assign(this._gltf.scenes),mF.Assign(this._gltf.skins),mF.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const i of t.children)e[i]=t.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=void 0===s?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in gF._RegisteredExtensions){const t=gF._RegisteredExtensions[e].factory(this);t.name!==e&&we.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired)if(!this._extensions.some((t=>t.name===e&&t.enabled)))throw new Error(`Required extension ${e} is not available`)}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new bo("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case RN.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],gF._LoadTransform(t,this._rootBabylonMesh));break;case RN.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=mF.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then((()=>{}))}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{const i=t.geometry;i&&-1===e.indexOf(i)&&e.push(i)}));return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof Sn&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&"TransformNode"===i._babylonTransformNode.getClassName()&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case IN.NONE:break;case IN.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case IN.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void we.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=(()=>{})){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=s=>{if(gF.AddPointerMetadata(s,e),gF._LoadTransform(t,s),null!=t.camera){const i=mF.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=s})))}if(t.children)for(const i of t.children){const t=mF.Get(`${e}/children/${i}`,this._gltf.nodes,i);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=s})))}i(s)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new xn(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,n(i)}if(null!=t.mesh)if(null==t.skin){const i=mF.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,n))}else{const i=mF.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const s=t._babylonTransformNodeForSkin;i.metadata=fF(s.metadata,i.metadata||{});const n=mF.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${n.index}`,t,n,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=n.skeleton){const e=mF.Get(`/skins/${n.index}/skeleton`,this._gltf.nodes,n.skeleton).parent;t.index===e.index?i.parent=s.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:s,skinnedNode:i})}))})))})))}return this.logClose(),Promise.all(r).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,s){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&mF.Assign(r);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===r.length){const s=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,o,t,i,s,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new xn(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const s of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,`${o}_primitive${s.index}`,t,i,s,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return s(t._babylonTransformNode),this.logClose(),Promise.all(n).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,s,r,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!s.primitives[0].targets;let l,h;if(a&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=r._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=r._instanceData.promise;else{const n=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new bo(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?uo.CounterClockWiseSideOrientation:uo.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,r,o),n.push(this._loadVertexDataAsync(e,r,o).then((t=>this._loadMorphTargetsAsync(e,r,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=gF._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=mF.Get(`${e}/material`,this._gltf.materials,r.material);n.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(n),a&&(r._instanceData={babylonSourceMesh:o,promise:h}),l=o}return gF.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),n(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new _n(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=mF.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{o.setIndices(e)})))}const a=(t,s,a)=>{if(null==r[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s);const l=mF.Get(`${e}/attributes/${t}`,this._gltf.accessors,r[t]);n.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,s).then((e=>{if(e.getKind()===ys.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=ge.Vector3[0].copyFromFloats(...l.min),t=ge.Vector3[1].copyFromFloats(...l.max);if(l.normalized&&5126!==l.componentType){let i=1;switch(l.componentType){case 5120:i=127;break;case 5121:i=255;break;case 5122:i=32767;break;case 5123:i=65535}const s=1/i;e.scaleInPlace(s),t.scaleInPlace(s)}o._boundingInfo=new rn(e,t),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(e,l.count)}))),s==ys.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),a&&a(l)};return a("POSITION",ys.PositionKind),a("NORMAL",ys.NormalKind),a("TANGENT",ys.TangentKind),a("TEXCOORD_0",ys.UVKind),a("TEXCOORD_1",ys.UV2Kind),a("TEXCOORD_2",ys.UV3Kind),a("TEXCOORD_3",ys.UV4Kind),a("TEXCOORD_4",ys.UV5Kind),a("TEXCOORD_5",ys.UV6Kind),a("JOINTS_0",ys.MatricesIndicesKind),a("WEIGHTS_0",ys.MatricesWeightsKind),a("JOINTS_1",ys.MatricesIndicesExtraKind),a("WEIGHTS_1",ys.MatricesWeightsExtraKind),a("COLOR_0",ys.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(n).then((()=>o))}_createMorphTargets(e,t,i,s,r){if(!s.targets)return;if(null==t._numMorphTargets)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new pv(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e{n.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,s){const r=new Array,n=(s,n,o)=>{if(null==i[s])return;const a=t.getVertexBuffer(n);if(!a)return;const l=mF.Get(`${e}/${s}`,this._gltf.accessors,i[s]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return n("POSITION",ys.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,s)=>{i[s]=t[s]+e})),s.setPositions(i)})),n("NORMAL",ys.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,s)=>{i[s]=t[s]+e})),s.setNormals(i)})),n("TANGENT",ys.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let r=0;e.forEach(t.length/3*4,((e,s)=>{(s+1)%4!=0&&(i[r]=t[r]+e,r++)})),s.setTangents(i)})),Promise.all(r).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=de.Zero(),s=pe.Identity(),r=de.One();e.matrix?fe.FromArray(e.matrix).decompose(r,s,i):(e.translation&&(i=de.FromArray(e.translation)),e.rotation&&(s=pe.FromArray(e.rotation)),e.scale&&(r=de.FromArray(e.scale))),t.position=i,t.rotationQuaternion=s,t.scaling=r}_loadSkinAsync(e,t,i,s){const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Ho(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},s(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const s=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=mF.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);r===i||s(r,i)||(we.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else we.Warn(`${e}: Failed to find common root`)}const s={};for(const r of t.joints){const n=mF.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,i,s)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const s of t){const t=[];let r=mF.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==r.index;)t.unshift(r),r=r.parent;i[s]=t}let s=null;for(let e=0;;++e){let r=i[t[0]];if(e>=r.length)return s;const n=r[e];for(let o=1;o=r.length||n!==r[e])return s;s=n}}_loadBone(e,t,i,s){let r=s[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?n=this._loadBone(e.parent,t,i,s):void 0!==t.skeleton&&we.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return r=new pr(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),s[e.index]=r,this._postSceneLoadActions.push((()=>{r.linkTransformNode(e._babylonTransformNode)})),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=mF.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const e=fe.Identity(),s=i._index;t&&-1!==s&&(fe.FromArrayToRef(t,16*s,e),e.invertToRef(e));const r=i.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?fe.FromArray(e.matrix):fe.Compose(e.scale?de.FromArray(e.scale):de.One(),e.rotation?pe.FromArray(e.rotation):pe.Identity(),e.translation?de.FromArray(e.translation):de.Zero())}loadCameraAsync(e,t,i=(()=>{})){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new xh(t.name||`camera${t.index}`,de.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=i.yfov,n.minZ=i.znear,n.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=Kr.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return gF.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(r).then((()=>n))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new kr(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const r=new Array;mF.Assign(t.channels),mF.Assign(t.samplers);for(const i of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),s.addTargetedAnimation(t,e)})));return Promise.all(r).then((()=>(s.normalize(0),s)))}_loadAnimationChannelAsync(e,t,i,s,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,s,r);if(n)return n;if(null==s.target.node)return Promise.resolve();const o=mF.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if("weights"===s.target.path&&!o._numMorphTargets||"weights"!==s.target.path&&!o._babylonTransformNode)return Promise.resolve();let a;switch(s.target.path){case"translation":a=pF.translation;break;case"rotation":a=pF.rotation;break;case"scale":a=pF.scale;break;case"weights":a=pF.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const l={object:o,info:a};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,l,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n){const o=this.parent.targetFps,a=1/o,l=mF.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,l).then((e=>{let t=0;const l=r.object,h=r.info;for(const r of h){const h=r.getStride(l),c=e.input,u=e.output,d=new Array(c.length);let _=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${s.index}_${t}`;r.buildAnimations(l,e,o,d,((e,i)=>{++t,n(e,i)}))}}}))}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=mF.Get(`${e}/input`,this._gltf.accessors,t.input),r=mF.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,s){const r=this._extensionsLoadBufferAsync(e,t,i,s);if(r)return r;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,s)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=mF.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const s=gF._GetNumComponents(e,t.type),r=s*ys.GetTypeByteLength(t.componentType),n=s*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(n));else{const o=mF.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==r){const e=new i(n);return ys.ForEach(a,t.byteOffset||0,o.byteStride||r,s,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return gF._GetTypedArray(e,t.componentType,a,t.byteOffset,n)}))}if(t.sparse){const n=t.sparse;t._data=t._data.then((o=>{const a=o,l=mF.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,n.indices.bufferView),h=mF.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,n.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=gF._GetTypedArray(`${e}/sparse/indices`,n.indices.componentType,o,n.indices.byteOffset,n.count),c=s*n.count;let u;if(5126!==t.componentType||t.normalized){const o=gF._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);u=new i(c),ys.ForEach(o,0,r,s,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=gF._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);let d=0;for(let e=0;egF._GetTypedArray(e,t.componentType,i,t.byteOffset,t.count)))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then((e=>new Ts(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){if(t._babylonVertexBuffer?.[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new ys(s,e,i,!1)));else{const r=mF.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(r).then((n=>{const o=gF._GetNumComponents(e,t.type);return new ys(s,n,i,!1,void 0,r.byteStride,void 0,t.byteOffset,o,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=Ce.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=Ce.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=e}))),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then((()=>{}))}_loadMaterialAsync(e,t,i,s,r=(()=>{})){const n=this._extensionsLoadMaterialAsync(e,t,i,s,r);if(n)return n;t._data=t._data||{};let o=t._data[s];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,s);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[s]=o,gF.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),r(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Um(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=Um.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?Ce.FromArray(t.emissiveFactor):new Ce(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${i.name} (Normal)`,i.bumpTexture=e}))),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${i.name} (Occlusion)`,i.ambientTexture=e}))),i.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(s).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=Um.PBRMATERIAL_OPAQUE,i.alpha=1;break;case"MASK":i.transparencyMode=Um.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=Um.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=(()=>{})){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=mF.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,(s=>{s.coordinatesIndex=t.texCoord||0,gF.AddPointerMetadata(s,e),this._parent.onTextureLoadedObservable.notifyObservers(s),i(s)}));return this.logClose(),n}_loadTextureAsync(e,t,i=(()=>{})){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=null==t.sampler?gF.DefaultSampler:mF.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=mF.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,r,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,s=(()=>{}),r,n){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new HP;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},c=new Vo(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,s=`data:${this._uniqueRootUrl}${t}`;c.updateURL(s,e)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,s(c),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:gF._GetTextureSamplingMode(e,t),wrapU:gF._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:gF._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=mF.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!gF._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(Zi(i)){const t=new Uint8Array(es(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((s,r)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),s(new Uint8Array(t)))}),!0,(t=>{r(new Gi(`${e}: Failed to load '${i}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return Vo.CLAMP_ADDRESSMODE;case 33648:return Vo.MIRROR_ADDRESSMODE;case 10497:return Vo.WRAP_ADDRESSMODE;default:return we.Warn(`${e}: Invalid value (${t})`),Vo.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,s=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(s){case 9728:return Vo.LINEAR_NEAREST;case 9729:return Vo.LINEAR_LINEAR;case 9984:return Vo.LINEAR_NEAREST_MIPNEAREST;case 9985:return Vo.LINEAR_LINEAR_MIPNEAREST;case 9986:return Vo.LINEAR_NEAREST_MIPLINEAR;case 9987:return Vo.LINEAR_LINEAR_MIPLINEAR;default:return we.Warn(`${e}/minFilter: Invalid value (${s})`),Vo.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&we.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return Vo.NEAREST_NEAREST;case 9729:return Vo.NEAREST_LINEAR;case 9984:return Vo.NEAREST_NEAREST_MIPNEAREST;case 9985:return Vo.NEAREST_LINEAR_MIPNEAREST;case 9986:return Vo.NEAREST_NEAREST_MIPLINEAR;case 9987:return Vo.NEAREST_LINEAR_MIPLINEAR;default:return we.Warn(`${e}/minFilter: Invalid value (${s})`),Vo.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,r){const n=i.buffer;s=i.byteOffset+(s||0);const o=gF._GetTypedArrayConstructor(`${e}/componentType`,t),a=ys.GetTypeByteLength(t);return s%a!=0?(we.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${a})`),new o(n.slice(s,s+r*a),0)):new o(n,s,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return hs.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return uo.PointListDrawMode;case 1:return uo.LineListDrawMode;case 2:return uo.LineLoopDrawMode;case 3:return uo.LineStripDrawMode;case 4:return uo.TriangleFillMode;case 5:return uo.TriangleStripDrawMode;case 6:return uo.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const s=t._data[i];for(const t of s.babylonMeshes){t.computeWorldMatrix(!0);const i=s.babylonMaterial;e.push(i.forceCompilationAsync(t)),e.push(i.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(i.forceCompilationAsync(t,{clipPlane:!0})),e.push(i.forceCompilationAsync(t,{clipPlane:!0,useInstances:!0})))}}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile materials")}))}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const t=i.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile shadow generators")}))}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const s of this._extensions)if(s.enabled){const r=`${s.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[r]){o[r]=!0;try{const e=i(s);if(e)return e}finally{delete o[r]}}}return null}_extensionsOnLoading(){this._forEachExtensions((e=>e.onLoading&&e.onLoading()))}_extensionsOnReady(){this._forEachExtensions((e=>e.onReady&&e.onReady()))}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n){return this._applyExtensions(r,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,s,r,n)))}_extensionsLoadMaterialAsync(e,t,i,s,r){return this._applyExtensions(t,"loadMaterial",(n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,s,r)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(s=>s.createMaterial&&s.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,s,r){return this._applyExtensions(i,"loadAnimationChannel",(n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,s,r)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(s=>s._loadUriAsync&&s._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",(r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,s)))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const r=t.extensions[i];return r?s(`${e}/extensions/${i}`,r):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const r=t.extras[i];return r?s(`${e}/extras/${i}`,r):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}gF._RegisteredExtensions={},gF.DefaultSampler={index:-1},UN._CreateGLTF2Loader=e=>new gF(e);const vF="EXT_lights_image_based";class xF{constructor(e){this.name=vF,this._loader=e,this.enabled=this._loader.isExtensionUsed(vF)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return gF.LoadExtensionAsync(e,t,this.name,((i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=mF.Get(`${i}/light`,this._lights,s.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,n).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(r).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let r=0;r{s[r][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new Mx(this._loader.babylonScene,null,t.specularImageSize);if(i.name=t.name||"environment",t._babylonTexture=i,null!=t.intensity&&(i.level=t.intensity),t.rotation){let e=pe.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=pe.Inverse(e)),fe.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=a_.FromArray(t.irradianceCoefficients);r.scaleInPlace(t.intensity),r.convertIrradianceToLambertianRadiance();const n=l_.FromHarmonics(r),o=(s.length-1)/xe.Log2(t.specularImageSize);return i.updateRGBDAsync(s,n,o)}))}return t._loaded.then((()=>t._babylonTexture))}}gF.RegisterExtension(vF,(e=>new xF(e)));const bF="EXT_mesh_gpu_instancing";class TF{constructor(e){this.name=bF,this._loader=e,this.enabled=this._loader.isExtensionUsed(bF)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((e,s)=>{this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return r;const n=new Array;let o=0;const a=t=>{if(null==s.attributes[t])return void n.push(Promise.resolve(null));const i=mF.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,s.attributes[t]);if(n.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===o)o=i.count;else if(o!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return a("TRANSLATION"),a("ROTATION"),a("SCALE"),r.then((e=>Promise.all(n).then((([i,s,r])=>{const n=new Float32Array(16*o);ge.Vector3[0].copyFromFloats(0,0,0),ge.Quaternion[0].copyFromFloats(0,0,0,1),ge.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew TF(e)));const yF="EXT_meshopt_compression";class SF{constructor(e){this.name=yF,this.enabled=e.isExtensionUsed(yF),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return gF.LoadExtensionAsync(e,t,this.name,((i,s)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=mF.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,s.byteOffset||0,s.byteLength).then((e=>ty.Default.decodeGltfBufferAsync(e,s.count,s.byteStride,s.mode,s.filter))),r._meshOptData}))}}gF.RegisterExtension(yF,(e=>new SF(e)));const CF="EXT_texture_webp";class EF{constructor(e){this.name=CF,this._loader=e,this.enabled=e.isExtensionUsed(CF)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?gF.DefaultSampler:mF.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mF.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}gF.RegisterExtension(CF,(e=>new EF(e)));const AF="EXT_texture_avif";class PF{constructor(e){this.name=AF,this._loader=e,this.enabled=e.isExtensionUsed(AF)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?gF.DefaultSampler:mF.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mF.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}gF.RegisterExtension(AF,(e=>new PF(e)));const RF="KHR_draco_mesh_compression";class IF{constructor(e){this.name=RF,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=ey.DecoderAvailable&&this._loader.isExtensionUsed(RF)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},a=(e,s)=>{const a=r.attributes[e];if(null!=a&&(i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s),n[s]=a,this.useNormalizedFlagFromAccessor)){const i=mF.TryGet(this._loader.gltf.accessors,t.attributes[e]);i&&(o[s]=i.normalized||!1)}};a("POSITION",ys.PositionKind),a("NORMAL",ys.NormalKind),a("TANGENT",ys.TangentKind),a("TEXCOORD_0",ys.UVKind),a("TEXCOORD_1",ys.UV2Kind),a("TEXCOORD_2",ys.UV3Kind),a("TEXCOORD_3",ys.UV4Kind),a("TEXCOORD_4",ys.UV5Kind),a("TEXCOORD_5",ys.UV6Kind),a("JOINTS_0",ys.MatricesIndicesKind),a("WEIGHTS_0",ys.MatricesWeightsKind),a("COLOR_0",ys.ColorKind);const l=mF.Get(s,this._loader.gltf.bufferViews,r.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||ey.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,t,n,o).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}gF.RegisterExtension(RF,(e=>new IF(e)));const MF="KHR_lights_punctual";class OF{constructor(e){this.name=MF,this._loader=e,this.enabled=this._loader.isExtensionUsed(MF)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,mF.Assign(this._lights)}}loadNodeAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const n=mF.Get(s,this._lights,r.light),o=n.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,n.type){case"directional":{const e=new lm(o,de.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new ov(o,de.Zero(),this._loader.babylonScene);break;case"spot":{const e=new um(o,de.Zero(),de.Backward(),0,1,this._loader.babylonScene);e.angle=2*(n.spot&&n.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(n.spot&&n.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${n.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,n._babylonLight=t,t.falloffType=yo.FALLOFF_GLTF,t.diffuse=n.color?Ce.FromArray(n.color):Ce.White(),t.intensity=null==n.intensity?1:n.intensity,t.range=null==n.range?Number.MAX_VALUE:n.range,t.parent=e,this._loader._babylonLights.push(t),gF.AddPointerMetadata(t,s),i(e)})))))}}gF.RegisterExtension(MF,(e=>new OF(e)));const DF="KHR_materials_pbrSpecularGlossiness";class wF{constructor(e){this.name=DF,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(DF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(s,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=Ce.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=Ce.White(),i.reflectivityColor=t.specularFactor?Ce.FromArray(t.specularFactor):Ce.White(),i.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${i.name} (Diffuse)`,i.albedoTexture=e}))),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,(e=>{e.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=e,i.reflectivityTexture.hasAlpha=!0}))),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(DF,(e=>new wF(e)));const NF="KHR_materials_unlit";class FF{constructor(e){this.name=NF,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(NF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=Ce.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=Ce.White(),r.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(NF,(e=>new FF(e)));const BF="KHR_materials_clearcoat";class LF{constructor(e){this.name=BF,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(BF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=e}))),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(BF,(e=>new LF(e)));const kF="KHR_materials_iridescence";class VF{constructor(e){this.name=kF,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(kF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(kF,(e=>new VF(e)));const UF="KHR_materials_anisotropy";class GF{constructor(e){this.name=UF,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(UF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e}))),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(UF,(e=>new GF(e)));const zF="KHR_materials_emissive_strength";class WF{constructor(e){this.name=zF,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(zF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(s,r,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(i.emissiveIntensity=t.emissiveStrength)}}gF.RegisterExtension(zF,(e=>new WF(e)));const HF="KHR_materials_sheen";class XF{constructor(e){this.name=HF,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(HF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=Ce.FromArray(t.sheenColorFactor):i.sheen.color=Ce.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${i.name} (Sheen Color)`,i.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=e})))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then((()=>{}))}}gF.RegisterExtension(HF,(e=>new XF(e)));const YF="KHR_materials_specular";class QF{constructor(e){this.name=YF,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(YF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=Ce.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=e}))),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(YF,(e=>new QF(e)));const jF="KHR_materials_ior";class KF{constructor(e){this.name=jF,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(jF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=KF._DEFAULT_IOR,Promise.resolve()}}KF._DEFAULT_IOR=1.5,gF.RegisterExtension(jF,(e=>new KF(e)));const $F="KHR_materials_variants";class qF{constructor(e){this.name=$F,this._loader=e,this.enabled=this._loader.isExtensionUsed($F)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return qF.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${$F} extension`);const s=e=>{const t=i.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)s(e);else s(t);i.lastSelected=t}selectVariant(e,t){qF.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${$F} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){qF.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${$F} extension`);return t.lastSelected}getLastSelectedVariant(e){return qF.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[$F]||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,r,n){return gF.LoadExtensionAsync(e,r,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,r,(t=>{if(n(t),t instanceof bo){const i=gF._GetDrawMode(e,r.mode),s=this._loader.rootBabylonMesh,n=s?s._internalMetadata=s._internalMetadata||{}:{},h=n.gltf=n.gltf||{},c=h[$F]=h[$F]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let r=null,n=i;do{if(n=n.parent,!n)return;r=qF._GetExtensionMetadata(n)}while(null===r);if(s&&r===qF._GetExtensionMetadata(s)){n._internalMetadata={};for(const e in s._internalMetadata)n._internalMetadata[e]=s._internalMetadata[e];n._internalMetadata.gltf=[];for(const e in s._internalMetadata.gltf)n._internalMetadata.gltf[e]=s._internalMetadata.gltf[e];n._internalMetadata.gltf[$F]={lastSelected:null,original:[],variants:{}};for(const e of r.original)n._internalMetadata.gltf[$F].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){n._internalMetadata.gltf[$F].variants[e]=[];for(const t of r.variants[e])n._internalMetadata.gltf[$F].variants[e].push({mesh:t.mesh,material:t.material})}r=n._internalMetadata.gltf[$F]}for(const e of r.original)e.mesh===t&&(e.mesh=i);for(const e of r.variants[o.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}gF.RegisterExtension($F,(e=>new qF(e)));class ZF{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Yd.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...ZF._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new X,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},i=this._options;this._options=t,t.renderSize===i.renderSize&&t.renderTargetTextureType===i.renderTargetTextureType&&t.generateMipmaps===i.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof Um&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),hs.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e)):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e)}))}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof Um&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==i?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===i&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){return null!==this._opaqueRenderTarget?.getInternalTexture()}_setupRenderTargets(){let e,t;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new pl("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=this._options.clearColor?.clone()??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0,this._opaqueRenderTarget.onBeforeBindObservable.add((i=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?i.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(i.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e})),this._transparentMeshesCache.forEach((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const JF="KHR_materials_transmission";class eB{constructor(e){this.name=JF,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(JF),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,s){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,void 0===s.transmissionFactor)return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();{r.subSurface.refractionIntensity=s.transmissionFactor;const e=r.getScene();r.subSurface.refractionIntensity&&!e._transmissionHelper?new ZF({},r.getScene()):r.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then((e=>{r.subSurface.refractionIntensityTexture=e,r.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}gF.RegisterExtension(JF,(e=>new eB(e)));const tB="KHR_materials_translucency";class iB{constructor(e){this.name=tB,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(tB),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const r=i;return r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!0,void 0===s.translucencyFactor?(r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve()):(r.subSurface.translucencyIntensity=s.translucencyFactor,s.translucencyTexture?(s.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/translucencyTexture`,s.translucencyTexture).then((e=>{r.subSurface.translucencyIntensityTexture=e}))):Promise.resolve())}}gF.RegisterExtension(tB,(e=>new iB(e)));const sB="KHR_materials_volume";class rB{constructor(e){this.name=sB,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(sB),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=void 0!==s.attenuationDistance?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,void 0!==s.attenuationColor&&3==s.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then((e=>{i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}gF.RegisterExtension(sB,(e=>new rB(e)));const nB="KHR_materials_dispersion";class oB{constructor(e){this.name=nB,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(nB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);return i.subSurface.isRefractionEnabled&&s.dispersion?(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion,Promise.resolve()):Promise.resolve()}}gF.RegisterExtension(nB,(e=>new oB(e)));const aB="KHR_mesh_quantization";class lB{constructor(e){this.name=aB,this.enabled=e.isExtensionUsed(aB)}dispose(){}}gF.RegisterExtension(aB,(e=>new lB(e)));const hB="KHR_texture_basisu";class cB{constructor(e){this.name=hB,this._loader=e,this.enabled=e.isExtensionUsed(hB)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?gF.DefaultSampler:mF.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mF.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}gF.RegisterExtension(hB,(e=>new cB(e)));const uB="KHR_texture_transform";class dB{constructor(e){this.name=uB,this._loader=e,this.enabled=this._loader.isExtensionUsed(uB)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Vo))throw new Error(`${s}: Texture type not supported`);r.offset&&(e.uOffset=r.offset[0],e.vOffset=r.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,r.rotation&&(e.wAng=-r.rotation),r.scale&&(e.uScale=r.scale[0],e.vScale=r.scale[1]),null!=r.texCoord&&(e.coordinatesIndex=r.texCoord),i(e)}))))}}gF.RegisterExtension(uB,(e=>new dB(e)));const _B="KHR_xmp_json_ld";class pB{constructor(e){this.name=_B,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(_B)}dispose(){this._loader=null}onLoading(){if(null===this._loader.rootBabylonMesh)return;const e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){const i=+t.packet;e.packets&&i2)),new yB(Nt.ANIMATIONTYPE_FLOAT,`${e}.vScale`,vB,(()=>2))],offset:[new yB(Nt.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,mB,(()=>2)),new yB(Nt.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,vB,(()=>2))],rotation:[new yB(Nt.ANIMATIONTYPE_FLOAT,`${e}.wAng`,gB,(()=>1))]}}gF.RegisterExtension(_B,(e=>new pB(e)));class TB extends dF{buildAnimations(e,t,i,s,r){r(e._babylonCamera,this._buildAnimation(t,i,s))}}class yB extends dF{buildAnimations(e,t,i,s,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,i,s))}}class SB extends dF{buildAnimations(e,t,i,s,r){r(e._babylonLight,this._buildAnimation(t,i,s))}}const CB={__array__:{__target__:!0,...pF}},EB={__array__:{__target__:!0,orthographic:{xmag:[new TB(Nt.ANIMATIONTYPE_FLOAT,"orthoLeft",gB,(()=>1)),new TB(Nt.ANIMATIONTYPE_FLOAT,"orthoRight",vB,(()=>1))],ymag:[new TB(Nt.ANIMATIONTYPE_FLOAT,"orthoBottom",gB,(()=>1)),new TB(Nt.ANIMATIONTYPE_FLOAT,"orthoTop",vB,(()=>1))],zfar:[new TB(Nt.ANIMATIONTYPE_FLOAT,"maxZ",mB,(()=>1))],znear:[new TB(Nt.ANIMATIONTYPE_FLOAT,"minZ",mB,(()=>1))]},perspective:{yfov:[new TB(Nt.ANIMATIONTYPE_FLOAT,"fov",mB,(()=>1))],zfar:[new TB(Nt.ANIMATIONTYPE_FLOAT,"maxZ",mB,(()=>1))],znear:[new TB(Nt.ANIMATIONTYPE_FLOAT,"minZ",mB,(()=>1))]}}},AB={nodes:CB,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"albedoColor",fB,(()=>4)),new yB(Nt.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,s){return t[i+3]*s}),(()=>4))],metallicFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"metallic",mB,(()=>1))],roughnessFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"roughness",mB,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:bB("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:bB("metallicTexture")}}},emissiveFactor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"emissiveColor",fB,(()=>3))],normalTexture:{scale:[new yB(Nt.ANIMATIONTYPE_FLOAT,"bumpTexture.level",mB,(()=>1))],extensions:{KHR_texture_transform:bB("bumpTexture")}},occlusionTexture:{strength:[new yB(Nt.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",mB,(()=>1))],extensions:{KHR_texture_transform:bB("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:bB("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new yB(Nt.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",mB,(()=>1))],anisotropyRotation:[new yB(Nt.ANIMATIONTYPE_FLOAT,"anisotropy.angle",mB,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:bB("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",mB,(()=>1))],clearcoatRoughnessFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",mB,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:bB("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new yB(Nt.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",mB,(()=>1))],extensions:{KHR_texture_transform:bB("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:bB("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new yB(Nt.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",mB,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new yB(Nt.ANIMATIONTYPE_FLOAT,"emissiveIntensity",mB,(()=>1))]},KHR_materials_ior:{ior:[new yB(Nt.ANIMATIONTYPE_FLOAT,"indexOfRefraction",mB,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"iridescence.intensity",mB,(()=>1))],iridescenceIor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",mB,(()=>1))],iridescenceThicknessMinimum:[new yB(Nt.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",mB,(()=>1))],iridescenceThicknessMaximum:[new yB(Nt.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",mB,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:bB("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:bB("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"sheen.color",fB,(()=>3))],sheenRoughnessFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"sheen.roughness",mB,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:bB("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:bB("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"metallicF0Factor",mB,(()=>1))],specularColorFactor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",fB,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:bB("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:bB("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",mB,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:bB("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",fB,(()=>3))],attenuationDistance:[new yB(Nt.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",mB,(()=>1))],thicknessFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",mB,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:bB("subSurface.thicknessTexture")}}}}}},cameras:EB,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new SB(Nt.ANIMATIONTYPE_COLOR3,"diffuse",fB,(()=>3))],intensity:[new SB(Nt.ANIMATIONTYPE_FLOAT,"intensity",mB,(()=>1))],range:[new SB(Nt.ANIMATIONTYPE_FLOAT,"range",mB,(()=>1))],spot:{innerConeAngle:[new SB(Nt.ANIMATIONTYPE_FLOAT,"innerAngle",xB,(()=>1))],outerConeAngle:[new SB(Nt.ANIMATIONTYPE_FLOAT,"angle",xB,(()=>1))]}}}}}};class PB{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,i=this._gltf,s=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(s.__array__)s=s.__array__;else if(s=s[n],!s)throw new Error(`Path ${e} is invalid`);if(void 0===i)throw new Error(`Path ${e} is invalid`);i=i[n],s.__target__&&(t=i)}return{object:t,info:s}}}const RB="KHR_animation_pointer";class IB extends PB{constructor(e){super(e,AB)}}class MB{constructor(e){this.name=RB,this._loader=e,this._pathToObjectConverter=new IB(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(RB)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,r){const n=s.target.extensions?.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;"pointer"!==s.target.path&&we.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),null!=s.target.node&&we.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,a=n.pointer;if(!a)throw new Error(`${o}: Pointer is missing`);try{const n=this._pathToObjectConverter.convert(a);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,n,r)}catch(e){return we.Warn(`${o}/pointer: Invalid pointer (${a}) skipped`),null}}}gF.RegisterExtension(RB,(e=>new MB(e)));const OB="MSFT_audio_emitter";class DB{constructor(e){this.name=OB,this._loader=e,this.enabled=this._loader.isExtensionUsed(OB)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,mF.Assign(this._clips),mF.Assign(this._emitters)}}loadSceneAsync(e,t){return gF.LoadExtensionAsync(e,t,this.name,((i,s)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const e of s.emitters){const t=mF.Get(`${i}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(r).then((()=>{}))}))}loadNodeAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((e,s)=>{const r=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of s.emitters){const s=mF.Get(`${e}/emitters`,this._emitters,i);r.push(this._loadEmitterAsync(`${e}/emitters/${s.index}`,s).then((()=>{for(const e of s._babylonSounds)e.attachToMesh(t),null==s.innerAngle&&null==s.outerAngle||(e.setLocalDirectionToMesh(de.Forward()),e.setDirectionalCone(2*hs.ToDegrees(null==s.innerAngle?Math.PI:s.innerAngle),2*hs.ToDegrees(null==s.outerAngle?Math.PI:s.outerAngle),0))})))}i(t)})).then((e=>Promise.all(r).then((()=>e))))}))}loadAnimationAsync(e,t){return gF.LoadExtensionAsync(e,t,this.name,((i,s)=>this._loader.loadAnimationAsync(e,t).then((r=>{const n=new Array;mF.Assign(s.events);for(const o of s.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,r));return Promise.all(n).then((()=>r))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=mF.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,i=t.name||`emitter${t.index}`,s={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let r=0;r{const n=t._babylonSounds[r]=new Ro(i,e,this._loader.babylonScene,null,s);n.refDistance=t.refDistance||1,n.maxDistance=t.maxDistance||256,n.rolloffFactor=t.rolloffFactor||1,n.distanceModel=t.distanceModel||"exponential"})))}const r=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new Oo(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*hs.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*hs.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:r}}return t._babylonData.loaded}_getEventAction(e,t,i,s,r){switch(i){case"play":return e=>{const i=(r||0)+(e-s);t.play(i)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,r){if(0==r.targetedAnimations.length)return Promise.resolve();const n=r.targetedAnimations[0],o=s.emitter,a=mF.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new Br(s.time,this._getEventAction(e,t,s.action,s.time,s.startOffset));n.animation.addEvent(i),r.onAnimationGroupEndObservable.add((()=>{t.stop()})),r.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}gF.RegisterExtension(OB,(e=>new DB(e)));const wB="MSFT_lod";class NB{constructor(e){this.name=wB,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new X,this.onMaterialLODsLoadedObservable=new X,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(wB)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}for(let e=0;e{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((e,s)=>{let r;const n=this._getLODs(e,t,this._loader.gltf.nodes,s.ids);this._loader.logOpen(`${e}`);for(let e=0;e{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,s).then((t=>{if(0!==e){const t=n[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t}));this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?r=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(o))}return this._loader.logClose(),r}))}_loadMaterialAsync(e,t,i,s,r){return this._nodeIndexLOD?null:gF.LoadExtensionAsync(e,t,this.name,((e,n)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e{0===e&&r(t)})).then((t=>{if(0!==e){r(t);const i=a[e-1]._data;i[s]&&(this._disposeMaterials([i[s].babylonMaterial]),delete i[s])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?o=n:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(n))}return this._loader.logClose(),o}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new HP,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new HP,this._materialSignalLODs[s].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const t=(e,t)=>{const r=i,n=r+s-1;let o=e[t];return o?(o.start=Math.min(o.start,r),o.end=Math.max(o.end,n)):(o={start:r,end:n,loaded:new HP},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.start,s)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then((e=>{i.loaded.resolve(e)}),(e=>{i.loaded.reject(e)})))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let t=s.length-1;t>=0;t--)if(r.push(mF.Get(`${e}/ids/${s[t]}`,i,s[t])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.material);e.dispose();const s=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const i of e){for(const e of i.getActiveTextures())t[e.uniqueId]=e;i.dispose()}for(const e in t)for(const i of this._loader.babylonScene.materials)i.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}gF.RegisterExtension(wB,(e=>new NB(e)));const FB="MSFT_minecraftMesh";class BB{constructor(e){this.name=FB,this._loader=e,this.enabled=this._loader.isExtensionUsed(FB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtraAsync(e,t,this.name,((s,r)=>{if(r){if(!(i instanceof Um))throw new Error(`${s}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,r}return null}))}}gF.RegisterExtension(FB,(e=>new BB(e)));const LB="MSFT_sRGBFactors";class kB{constructor(e){this.name=LB,this._loader=e,this.enabled=this._loader.isExtensionUsed(LB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtraAsync(e,t,this.name,((s,r)=>{if(r){if(!(i instanceof Um))throw new Error(`${s}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i),n=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,n),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,n),r}return null}))}}gF.RegisterExtension(LB,(e=>new kB(e)));const VB={"lifecycle/onStart":CD.ClassName,"lifecycle/onTick":AD.ClassName,log:uM.ClassName,"flow/delay":TM.ClassName,"customEvent/send":mM.ClassName,"customEvent/receive":ED.ClassName,"flow/sequence":IM.ClassName,"world/get":LM.ClassName,"world/set":fM.ClassName,"flow/doN":vM.ClassName,"variable/get":NM.ClassName,"variable/set":dM.ClassName,"flow/whileLoop":AM.ClassName,"math/random":oO.ClassName,"math/e":lO.ClassName,"math/pi":hO.ClassName,"math/inf":cO.ClassName,"math/nan":uO.ClassName,"math/abs":_O.ClassName,"math/sign":pO.ClassName,"math/trunc":fO.ClassName,"math/floor":mO.ClassName,"math/ceil":gO.ClassName,"math/fract":vO.ClassName,"math/neg":xO.ClassName,"math/add":iO.ClassName,"math/sub":sO.ClassName,"math/mul":rO.ClassName,"math/div":nO.ClassName,"math/rem":TO.ClassName,"math/min":yO.ClassName,"math/max":SO.ClassName,"math/clamp":AO.ClassName,"math/saturate":RO.ClassName,"math/mix":IO.ClassName,"math/eq":MO.ClassName,"math/lt":DO.ClassName,"math/le":wO.ClassName,"math/gt":NO.ClassName,"math/ge":FO.ClassName,"math/isnan":BO.ClassName,"math/isinf":LO.ClassName,"math/rad":kO.ClassName,"math/deg":VO.ClassName,"math/sin":UO.ClassName,"math/cos":GO.ClassName,"math/tan":zO.ClassName,"math/asin":WO.ClassName,"math/acos":HO.ClassName,"math/atan":XO.ClassName,"math/atan2":YO.ClassName,"math/sinh":QO.ClassName,"math/cosh":jO.ClassName,"math/tanh":KO.ClassName,"math/asinh":$O.ClassName,"math/acosh":qO.ClassName,"math/atanh":ZO.ClassName,"math/exp":JO.ClassName,"math/log":eD.ClassName,"math/log2":tD.ClassName,"math/log10":iD.ClassName,"math/sqrt":sD.ClassName,"math/cbrt":rD.ClassName,"math/pow":nD.ClassName,"math/length":oD.ClassName,"math/normalize":aD.ClassName,"math/dot":aO.ClassName,"math/cross":lD.ClassName,"math/rotate2d":hD.ClassName,"math/rotate3d":cD.ClassName,"math/transpose":uD.ClassName,"math/determinant":dD.ClassName,"math/inverse":_D.ClassName,"math/matmul":pD.ClassName,"math/not":fD.ClassName,"math/and":mD.ClassName,"math/or":gD.ClassName,"math/xor":vD.ClassName,"math/asr":bD.ClassName,"math/lsl":xD.ClassName,"math/clz":TD.ClassName,"math/ctz":yD.ClassName,"math/popcnt":SD.ClassName},UB={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function GB(e,t,i){if(void 0!==e.type){const s=t.types&&t.types[e.type];if(!s)throw new Error(`${i}: Unknown type: ${e.type}`);const r=s.signature;if(!r)throw new Error(`${i}: Type ${e.type} has no signature`);const n=UB[r];return{value:e.value,className:n}}return e.value}function zB(e,t,i){const s=VB[t.type];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const r=e.toString(),n=function(e,t,i){const s={},r=e.configuration??[];for(const e of r)if("customEvent"===e.id){const r=t.customEvents&&t.customEvents[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown custom event: ${e.value}`);s.eventId=r.id,s.eventData=r.values.map((e=>e.id))}else if("variable"===e.id){const r=t.variables&&t.variables[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown variable: ${e.value}`);s.variableName=r.id}else if("path"===e.id){const t=e.value;s.path=t}else s[e.id]=GB(e,t,`/extensions/KHR_interactivity/nodes/${i}`);return s}(t,i,r);return{className:s,config:n,uniqueId:r,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class WB extends PB{constructor(e){super(e,HB)}}const HB={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},XB="KHR_interactivity";class YB{constructor(e){this._loader=e,this.name=XB,this.enabled=this._loader.isExtensionUsed(XB),this._pathConverter=new WB(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=this._loader.gltf.extensions?.KHR_interactivity,i=function(e){const t={uniqueId:ns(),_userVariables:{},_connectionValues:{}},i=[t],s=[];for(let t=0;te.name===a));h||(h={uniqueId:ns(),name:a,_connectionType:MI.Input,connectedPointIds:[]},l.signalInputs.push(h)),h.connectedPointIds.push(r.uniqueId),r.connectedPointIds.push(h.uniqueId)}const a=r.values??[];for(const r of a){const o=r.id,a={uniqueId:ns(),name:o,_connectionType:MI.Input,connectedPointIds:[]};if(n.dataInputs.push(a),void 0!==r.value){const s=GB(r,e,`/extensions/KHR_interactivity/nodes/${i}`);t._connectionValues[a.uniqueId]=s}else{if(void 0===r.node||void 0===r.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Invalid socket ${o} in node ${i}`);{const e=r.node,t=r.socket,n=s[e];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${e} that connects its output with node${i}'s input ${o}`);let l=n.dataOutputs.find((e=>e.name===t));l||(l={uniqueId:ns(),name:t,_connectionType:MI.Output,connectedPointIds:[]},n.dataOutputs.push(l)),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}}}}const r=e.variables??[];for(let i=0;inew YB(e)));const QB="ExtrasAsMetadata";class jB{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{};(i.gltf=i.gltf||{}).extras=t.extras}}constructor(e){this.name=QB,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}gF.RegisterExtension(QB,(e=>new jB(e)));class KB{constructor(){this.materials=[]}parseMTL(e,t,i,s){if(t instanceof ArrayBuffer)return;const r=t.split("\n"),n=/\s+/;let o,a=null;for(let t=0;t=0?l.substring(0,h):l;c=c.toLowerCase();const u=h>=0?l.substring(h+1).trim():"";if("newmtl"===c)a&&this.materials.push(a),e._blockEntityCollection=!!s,a=new yc(u,e),a._parentContainer=s,e._blockEntityCollection=!1;else if("kd"===c&&a)o=u.split(n,3).map(parseFloat),a.diffuseColor=Ce.FromArray(o);else if("ka"===c&&a)o=u.split(n,3).map(parseFloat),a.ambientColor=Ce.FromArray(o);else if("ks"===c&&a)o=u.split(n,3).map(parseFloat),a.specularColor=Ce.FromArray(o);else if("ke"===c&&a)o=u.split(n,3).map(parseFloat),a.emissiveColor=Ce.FromArray(o);else if("ns"===c&&a)a.specularPower=parseFloat(u);else if("d"===c&&a)a.alpha=parseFloat(u);else if("map_ka"===c&&a)a.ambientTexture=KB._GetTexture(i,u,e);else if("map_kd"===c&&a)a.diffuseTexture=KB._GetTexture(i,u,e);else if("map_ks"===c&&a)a.specularTexture=KB._GetTexture(i,u,e);else if("map_ns"===c);else if("map_bump"===c&&a){const t=u.split(n),s=t.indexOf("-bm");let r=null;s>=0&&(r=t[s+1],t.splice(s,2)),a.bumpTexture=KB._GetTexture(i,t.join(" "),e),a.bumpTexture&&null!==r&&(a.bumpTexture.level=parseFloat(r))}else"map_d"===c&&a&&(a.opacityTexture=KB._GetTexture(i,u,e))}a&&this.materials.push(a)}static _GetTexture(e,t,i){if(!t)return null;let s=e;if("file:"===e){let e=t.lastIndexOf("\\");-1===e&&(e=t.lastIndexOf("/")),s+=e>-1?t.substr(e+1):t}else s+=t;return new Vo(s,i,!1,KB.INVERT_TEXTURE_Y)}}KB.INVERT_TEXTURE_Y=!0;class $B{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new Ee(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return-1===i?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return 1!=i&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,s,r,n,o){let a;a=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e,i,t]):this._isInArray(this._tuplePosNorm,[e,i]),-1===a?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(r),this._wrappedNormalsForBabylon.push(n),void 0!==o&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(a)}_unwrapData(){for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(ys.PositionKind),i=e.getVerticesData(ys.NormalKind),s={};if(!t||!i)return;for(let e=0;ethis._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t+1],e[t]),this._handednessSign=1):(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=-1);const n=t.split("\n");for(let e=0;e=7){const e=parseFloat(i[4]),t=parseFloat(i[5]),s=parseFloat(i[6]);this._colors.push(new Ee(e>1?e/255:e,t>1?t/255:t,s>1?s/255:s,7===i.length||void 0===i[7]?1:parseFloat(i[7])))}else this._colors.push(this._grayColor)}else if(null!==(i=$B.NormalPattern.exec(t)))this._normals.push(new de(parseFloat(i[1]),parseFloat(i[2]),parseFloat(i[3])));else if(null!==(i=$B.UVPattern.exec(t)))this._uvs.push(new ue(parseFloat(i[1])*this._loadingOptions.UVScaling.x,parseFloat(i[2])*this._loadingOptions.UVScaling.y));else if(null!==(i=$B.FacePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),1);else if(null!==(i=$B.FacePattern4.exec(t)))this._setDataForCurrentFaceWithPattern4(i[1].trim().split(" "),1);else if(null!==(i=$B.FacePattern5.exec(t)))this._setDataForCurrentFaceWithPattern5(i[1].trim().split(" "),1);else if(null!==(i=$B.FacePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),1);else if(null!==(i=$B.FacePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),1);else if(null!==(i=$B.LinePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),0);else if(null!==(i=$B.LinePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),0);else if(null!==(i=$B.LinePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),0);else if($B.GroupDescriptor.test(t)||$B.ObjectDescriptor.test(t)){const e={name:t.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:$B.ObjectDescriptor.test(t)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if($B.UseMtlDescriptor.test(t)){if(this._materialNameFromObj=t.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const e={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(e),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else $B.MtlLibGroupDescriptor.test(t)?r(t.substring(7).trim()):$B.SmoothDescriptor.test(t)||we.Log("Unhandled expression at line : "+t)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let e=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new yc(_n.RandomId(),i),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=Ce.White()))}this._meshesFromObj.push({name:_n.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0})}for(let t=0;t=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){r.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[t].materialName),0===this._handledMesh.positions?.length){this._babylonMeshesArray.push(r);continue}const n=new cn;if(n.uvs=this._handledMesh.uvs,n.indices=this._handledMesh.indices,n.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const e=new Array;cn.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),n.normals=e}else n.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(n.colors=this._handledMesh.colors),n.applyToMesh(r),this._loadingOptions.invertY&&(r.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(r),this._babylonMeshesArray.push(r),this._handledMesh.directMaterial&&(r.material=this._handledMesh.directMaterial)}}}$B.ObjectDescriptor=/^o/,$B.GroupDescriptor=/^g/,$B.MtlLibGroupDescriptor=/^mtllib /,$B.UseMtlDescriptor=/^usemtl /,$B.SmoothDescriptor=/^s /,$B.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,$B.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,$B.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,$B.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,$B.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,$B.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,$B.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,$B.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,$B.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,$B.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,$B.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class qB{static get INVERT_TEXTURE_Y(){return KB.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){KB.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||qB._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:qB.COMPUTE_NORMALS,optimizeNormals:qB.OPTIMIZE_NORMALS,importVertexColors:qB.IMPORT_VERTEX_COLORS,invertY:qB.INVERT_Y,invertTextureY:qB.INVERT_TEXTURE_Y,UVScaling:qB.UV_SCALING,materialLoadingFailsSilently:qB.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:qB.OPTIMIZE_WITH_UV,skipMaterials:qB.SKIP_MATERIALS,useLegacyBehavior:qB.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,s){const r=t+e;hs.LoadFile(r,i,void 0,void 0,!1,((e,t)=>{s(r,t)}))}createPlugin(){return new qB(qB._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,s){return this._parseSolid(e,t,i,s).then((e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}loadAssetContainerAsync(e,t,i){const s=new Eo(e);return this._assetContainer=s,this.importMeshAsync(null,e,t,i).then((e=>(e.meshes.forEach((e=>s.meshes.push(e))),e.meshes.forEach((e=>{const t=e.material;t&&-1==s.materials.indexOf(t)&&(s.materials.push(t),t.getActiveTextures().forEach((e=>{-1==s.textures.indexOf(e)&&s.textures.push(e)})))})),this._assetContainer=null,s))).catch((e=>{throw this._assetContainer=null,e}))}_parseSolid(e,t,i,s){let r="";const n=new KB,o=[],a=[];new $B(o,a,this._loadingOptions).parse(e,i,t,this._assetContainer,(e=>{r=e}));const l=[];return""===r||this._loadingOptions.skipMaterials||l.push(new Promise(((e,i)=>{this._loadMTL(r,s,(l=>{try{n.parseMTL(t,l,s,this._assetContainer);for(let e=0;e-1;)i.push(s),t=s+1;if(-1===s&&0===i.length)n.materials[e].dispose();else for(let t=0;t{hs.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():i(s)}))}))),Promise.all(l).then((()=>a))}}qB.OPTIMIZE_WITH_UV=!0,qB.INVERT_Y=!1,qB.IMPORT_VERTEX_COLORS=!1,qB.COMPUTE_NORMALS=!1,qB.OPTIMIZE_NORMALS=!1,qB.UV_SCALING=new ue(1,1),qB.SKIP_MATERIALS=!1,qB.MATERIAL_LOADING_FAILS_SILENTLY=!0,qB.USE_LEGACY_BEHAVIOR=!1,Pa&&Pa.RegisterPlugin(new qB);class ZB{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name="stl",this.extensions={".stl":{isBinary:!0}}}importMesh(e,t,i,s,r){let n;if("string"!=typeof i){if(this._isBinary(i)){const e=new bo("stlmesh",t);return this._parseBinary(e,i),r&&r.push(e),!0}i=(new TextDecoder).decode(new Uint8Array(i))}for(;n=this.solidPattern.exec(i);){let i=n[1];const s=n[3];if(s&&i!=s)return hs.Error("Error in STL, solid name != endsolid name"),!1;if(e&&i)if(e instanceof Array){if(!e.indexOf(i))continue}else if(i!==e)continue;i=i||"stlmesh";const o=new bo(i,t);this._parseASCII(o,n[2]),r&&r.push(o)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const s=new Eo(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,s.meshes),e._blockEntityCollection=!1,s}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==i[e])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),s=i.getUint32(80,!0);let r=0;const n=new Float32Array(3*s*3),o=new Float32Array(3*s*3),a=new Uint32Array(3*s);let l=0;for(let e=0;e{if(e.tryDownload&&document){const i=new Blob([t],{type:"text/plain"}),s=URL.createObjectURL(i),r=e.fileName?e.fileName:"bitbybit-dev.step",n=document.createElement("a");n.href=s,n.target="_self",n.download=r,n.click(),n.remove()}return t}))}}class iL{constructor(e){this.occWorkerManager=e}makeCompound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.compound.makeCompound",e)}}class sL{constructor(e){this.occWorkerManager=e}line(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.line",e)}arcThroughThreePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughThreePoints",e)}arcThroughTwoPointsAndTangent(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughTwoPointsAndTangent",e)}arcFromCircleAndTwoPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoPoints",e)}arcFromCircleAndTwoAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoAngles",e)}arcFromCirclePointAndAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCirclePointAndAngle",e)}createCircleEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createCircleEdge",e)}createEllipseEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createEllipseEdge",e)}removeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.removeInternalEdges",e)}makeEdgeFromGeom2dCurveAndSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.makeEdgeFromGeom2dCurveAndSurface",e)}getEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdge",e)}getEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdges",e)}getEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesAlongWire",e)}getCircularEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgesAlongWire",e)}getLinearEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getLinearEdgesAlongWire",e)}getCornerPointsOfEdgesForShape(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCornerPointsOfEdgesForShape",e)}getEdgeLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeLength",e)}getEdgesLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesLengths",e)}getEdgeCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeCenterOfMass",e)}getEdgesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesCentersOfMass",e)}getCircularEdgeCenterPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeCenterPoint",e)}getCircularEdgeRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeRadius",e)}getCircularEdgePlaneDirection(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgePlaneDirection",e)}pointOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtParam",e)}edgesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.edgesToPoints",e)}reversedEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.reversedEdge",e)}tangentOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtParam",e)}pointOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtLength",e)}tangentOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtLength",e)}startPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.startPointOnEdge",e)}endPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.endPointOnEdge",e)}divideEdgeByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByParamsToPoints",e)}divideEdgeByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByEqualDistanceToPoints",e)}constraintTanLinesFromTwoPtsToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromTwoPtsToCircle",e)}constraintTanLinesFromPtToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromPtToCircle",e)}constraintTanLinesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesOnTwoCircles",e)}constraintTanCirclesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnTwoCircles",e)}constraintTanCirclesOnCircleAndPnt(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnCircleAndPnt",e)}}class rL{constructor(e){this.occWorkerManager=e}createFaceFromWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWire",e)}createFaceFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWires",e)}createFacesFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFacesFromWires",e)}createFaceFromMultipleCircleTanWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWires",e)}createFaceFromMultipleCircleTanWireCollections(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWireCollections",e)}faceFromSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurface",e)}faceFromSurfaceAndWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurfaceAndWire",e)}createPolygonFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createPolygonFace",e)}createCircleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createCircleFace",e)}createEllipseFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createEllipseFace",e)}createSquareFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createSquareFace",e)}createRectangleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createRectangleFace",e)}getFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFace",e)}getFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaces",e)}reversedFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.reversedFace",e)}subdivideToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPoints",e)}subdivideToPointsControlled(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsControlled",e)}subdivideToNormals(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToNormals",e)}subdivideToUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToUV",e)}pointOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointOnUV",e)}normalOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalOnUV",e)}pointsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointsOnUVs",e)}normalsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalsOnUVs",e)}subdivideToPointsOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsOnParam",e)}getUMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMinBound",e)}getUMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMaxBound",e)}getVMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMinBound",e)}getVMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMaxBound",e)}getFaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceArea",e)}getFacesAreas(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesAreas",e)}getFaceCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceCenterOfMass",e)}getFacesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesCentersOfMass",e)}filterFacePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.filterFacePoints",e)}}class nL{constructor(e){this.occWorkerManager=e}fromClosedShell(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.fromClosedShell",e)}createBox(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBox",e)}createCube(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCube",e)}createBoxFromCorner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBoxFromCorner",e)}createCylinder(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylinder",e)}createCylindersOnLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylindersOnLines",e)}createSphere(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createSphere",e)}createCone(e){return e.angle=e.angle*(Math.PI/180),this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCone",e)}getSolidSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidSurfaceArea",e)}getSolidVolume(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidVolume",e)}getSolidsVolumes(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsVolumes",e)}getSolidCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidCenterOfMass",e)}getSolidsCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsCentersOfMass",e)}getSolids(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolids",e)}filterSolidPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.filterSolidPoints",e)}}class oL{constructor(e){this.occWorkerManager=e}createPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygonWire",e)}createPolygons(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygons",e)}createLineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLineWire",e)}createLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLines",e)}splitOnPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.splitOnPoints",e)}wiresToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.wiresToPoints",e)}createPolylineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylineWire",e)}createZigZagBetweenTwoWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createZigZagBetweenTwoWires",e)}createWireFromTwoCirclesTan(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromTwoCirclesTan",e)}createPolylines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylines",e)}createBezier(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezier",e)}createBezierWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWires",e)}interpolatePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolatePoints",e)}interpolateWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolateWires",e)}createBSpline(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSpline",e)}createBSplines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSplines",e)}combineEdgesAndWiresIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.combineEdgesAndWiresIntoAWire",e)}createWireFromEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromEdge",e)}addEdgesAndWiresToWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.addEdgesAndWiresToWire",e)}divideWireByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByParamsToPoints",e)}divideWiresByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByParamsToPoints",e)}divideWireByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByEqualDistanceToPoints",e)}divideWiresByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByEqualDistanceToPoints",e)}pointOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtParam",e)}pointOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtLength",e)}tangentOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtParam",e)}tangentOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtLength",e)}derivativesOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtLength",e)}derivativesOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtParam",e)}startPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.startPointOnWire",e)}endPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.endPointOnWire",e)}createCircleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createCircleWire",e)}createSquareWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createSquareWire",e)}createStarWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createStarWire",e)}createChristmasTreeWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createChristmasTreeWire",e)}createNGonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createNGonWire",e)}createParallelogramWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createParallelogramWire",e)}createHeartWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createHeartWire",e)}createRectangleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createRectangleWire",e)}createLPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLPolygonWire",e)}createEllipseWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createEllipseWire",e)}getWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWire",e)}getWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWires",e)}getWireCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireCenterOfMass",e)}getWiresCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresCentersOfMass",e)}reversedWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWire",e)}reversedWireFromReversedEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWireFromReversedEdges",e)}getWireLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireLength",e)}getWiresLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresLengths",e)}placeWireOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWireOnFace",e)}placeWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWiresOnFace",e)}closeOpenWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.closeOpenWire",e)}project(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.project",e)}projectWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.projectWires",e)}}class aL{constructor(e){this.occWorkerManager=e}sewFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.sewFaces",e)}getShellSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.getShellSurfaceArea",e)}}class lL{constructor(e){this.occWorkerManager=e}purgeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.purgeInternalEdges",e)}unifySameDomain(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.unifySameDomain",e)}isClosed(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isClosed",e)}isConvex(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isConvex",e)}isChecked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isChecked",e)}isFree(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isFree",e)}isInfinite(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isInfinite",e)}isModified(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isModified",e)}isLocked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isLocked",e)}isNull(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNull",e)}isEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isEqual",e)}isNotEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNotEqual",e)}isPartner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isPartner",e)}isSame(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isSame",e)}getOrientation(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getOrientation",e)}getShapeType(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getShapeType",e)}}class hL{constructor(e){this.occWorkerManager=e}vertexFromPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexFromPoint",e)}verticesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesFromPoints",e)}verticesCompoundFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesCompoundFromPoints",e)}getVertices(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVertices",e)}getVerticesAsPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVerticesAsPoints",e)}verticesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesToPoints",e)}vertexToPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexToPoint",e)}}class cL{constructor(e){this.vertex=new hL(e),this.edge=new sL(e),this.wire=new oL(e),this.face=new rL(e),this.shell=new aL(e),this.solid=new nL(e),this.compound=new iL(e),this.shape=new lL(e)}}class uL{constructor(e){this.occWorkerManager=e}transform(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transform",e)}rotate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotate",e)}rotateAroundCenter(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenter",e)}align(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.align",e)}alignAndTranslate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslate",e)}translate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translate",e)}scale(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale",e)}scale3d(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3d",e)}mirror(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirror",e)}mirrorAlongNormal(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormal",e)}transformShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transformShapes",e)}rotateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateShapes",e)}rotateAroundCenterShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenterShapes",e)}alignShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignShapes",e)}alignAndTranslateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslateShapes",e)}translateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translateShapes",e)}scaleShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scaleShapes",e)}scale3dShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3dShapes",e)}mirrorShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorShapes",e)}mirrorAlongNormalShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormalShapes",e)}}class dL{constructor(e){this.occWorkerManager=e}loft(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loft",e)}loftAdvanced(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loftAdvanced",e)}closestPointsBetweenTwoShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsBetweenTwoShapes",e)}closestPointsOnShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapeFromPoints",e)}closestPointsOnShapesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapesFromPoints",e)}distancesToShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.distancesToShapeFromPoints",e)}extrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrude",e)}extrudeShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrudeShapes",e)}splitShapeWithShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.splitShapeWithShapes",e)}revolve(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.revolve",e)}rotatedExtrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.rotatedExtrude",e)}pipe(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipe",e)}pipePolylineWireNGon(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipePolylineWireNGon",e)}pipeWiresCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWiresCylindrical",e)}pipeWireCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWireCylindrical",e)}offset(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset",e)}offsetAdv(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offsetAdv",e)}makeThickSolidSimple(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidSimple",e)}makeThickSolidByJoin(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidByJoin",e)}slice(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.slice",e)}sliceInStepPattern(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.sliceInStepPattern",e)}offset3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset3DWire",e)}}class _L{constructor(e){this.occWorkerManager=e}union(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.union",e)}difference(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.difference",e)}intersection(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.intersection",e)}}class pL{constructor(e){this.occWorkerManager=e}geom2dEllipse(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dEllipse",e)}geom2dTrimmedCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dTrimmedCurve",e)}geom2dSegment(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dSegment",e)}get2dPointFrom2dCurveOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.get2dPointFrom2dCurveOnParam",e)}geomCircleCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomCircleCurve",e)}geomEllipseCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomEllipseCurve",e)}}class fL{constructor(e){this.occWorkerManager=e}cylindricalSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.cylindricalSurface",e)}surfaceFromFace(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.surfaceFromFace",e)}}class mL{constructor(e){this.curves=new pL(e),this.surfaces=new fL(e)}}class gL{constructor(e){this.occWorkerManager=e}filletEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdges",e)}filletEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesList",e)}filletEdgesListOneRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesListOneRadius",e)}filletEdgeVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgeVariableRadius",e)}filletEdgesSameVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesSameVariableRadius",e)}filletEdgesVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesVariableRadius",e)}fillet3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet3DWire",e)}chamferEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdges",e)}chamferEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesList",e)}chamferEdgeTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeTwoDistances",e)}chamferEdgesTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistances",e)}chamferEdgesTwoDistancesLists(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistancesLists",e)}chamferEdgeDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeDistAngle",e)}chamferEdgesDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistAngle",e)}chamferEdgesDistsAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistsAngles",e)}fillet2d(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet2d",e)}filletTwoEdgesInPlaneIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletTwoEdgesInPlaneIntoAWire",e)}}class vL{constructor(e){this.occWorkerManager=e}basicShapeRepair(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.basicShapeRepair",e)}fixSmallEdgeOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixSmallEdgeOnWire",e)}fixEdgeOrientationsAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixEdgeOrientationsAlongWire",e)}}var xL=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class bL{constructor(e){this.occWorkerManager=e,this.shapes=new cL(e),this.geom=new mL(e),this.transforms=new uL(e),this.operations=new dL(e),this.booleans=new _L(e),this.fillets=new gL(e),this.shapeFix=new vL(e),this.io=new tL(e)}shapeToMesh(e){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e)}))}shapesToMeshes(e){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e)}))}deleteShape(e){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShape",e)}))}deleteShapes(e){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShapes",e)}))}cleanAllCache(){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("cleanAllCache",{})}))}}var TL=function(e,t){return TL=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},TL(e,t)};function yL(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}TL(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function SL(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],s=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function CL(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var s,r,n=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return o}function EL(e,t,i){if(i||2===arguments.length)for(var s,r=0,n=t.length;r0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,s=i.hasError,r=i.isStopped,n=i.observers;return s||r?OL:(this.currentObservers=null,n.push(e),new ML((function(){t.currentObservers=null,IL(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,s=t.thrownError,r=t.isStopped;i?e.error(s):r&&e.complete()},t.prototype.asObservable=function(){var e=new tk;return e.source=this,e},t.create=function(e,t){return new lk(e,t)},t}(tk),lk=function(e){function t(t,i){var s=e.call(this)||this;return s.destination=t,s.source=i,s}return yL(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:OL},t}(ak);!function(e){e.loading="loading",e.loaded="loaded",e.initialised="initialised",e.computing="computing"}(sk||(sk={}));class hk{constructor(){this.occWorkerState$=new ak,this.promisesMade=[]}occWorkerAlreadyInitialised(){return!!this.occWorker}setOccWorker(e){this.occWorker=e,this.occWorker.onmessage=({data:e})=>{if("occ-initialised"===e)this.occWorkerState$.next({state:sk.initialised});else if("busy"===e)this.occWorkerState$.next({state:sk.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&void 0!==e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.occWorkerState$.next({state:sk.loaded}):this.occWorkerState$.next({state:sk.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,s={uid:i},r=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=r,this.promisesMade.push(s),this.occWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),r}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}!function(e){let t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(i=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(s=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(r=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(n=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(l=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(c=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(_=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(p=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(f=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(m=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainder=r)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,i,s,r,n){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==i&&(this.point1=i),void 0!==s&&(this.tolerance=s),void 0!==r&&(this.positionResult=r),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainders=r)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,i,s,r,n){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==i&&(this.planeOrigin=i),void 0!==s&&(this.planeDirection=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.solution=n)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==i&&(this.inside=i)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdgeIndexes=_),void 0!==p&&(this.edgeIndexHeight=p),void 0!==f&&(this.edgeIndexColour=f),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.DrawShapesDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdgeIndexes=_),void 0!==p&&(this.edgeIndexHeight=p),void 0!==f&&(this.edgeIndexColour=f),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.FaceSubdivisionDto=class{constructor(e,t,i,s,r,n,o,a,l){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepU=s),void 0!==r&&(this.removeStartEdgeU=r),void 0!==n&&(this.removeEndEdgeU=n),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==l&&(this.removeEndEdgeV=l)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepNthU=s),void 0!==r&&(this.shiftHalfStepUOffsetN=r),void 0!==n&&(this.removeStartEdgeNthU=n),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==l&&(this.removeEndEdgeUOffsetN=l),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==c&&(this.shiftHalfStepVOffsetN=c),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==_&&(this.removeEndEdgeNthV=_),void 0!==p&&(this.removeEndEdgeVOffsetN=p)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,i,s,r,n,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i),void 0!==s&&(this.nrPoints=s),void 0!==r&&(this.shiftHalfStep=r),void 0!==n&&(this.removeStartPoint=n),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,i){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==i&&(this.paramV=i)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,i){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.RectangleDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.LPolygonDto=class{constructor(e,t,i,s,n,o,a,l){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=r.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==i&&(this.widthSecond=i),void 0!==s&&(this.lengthSecond=s),void 0!==n&&(this.align=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==l&&(this.direction=l)}},e.BoxDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.center=s)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.corner=s)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,i,s,r,n){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==i&&(this.height=i),void 0!==s&&(this.angle=s),void 0!==r&&(this.center=r),void 0!==n&&(this.direction=n)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,i){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==i&&(this.end=i)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,i,s){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==i&&(this.end=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,i,s){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==i&&(this.alphaAngle2=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,i,s){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==s&&(this.sense=s)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,i){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==i&&(this.end=i)}},e.CylinderDto=class{constructor(e,t,i,s){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,i,s){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.indexes=s)}},e.FilletEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radius=i)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusLists=i),void 0!==s&&(this.paramsULists=s)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.Fillet3DWireDto=class{constructor(e,t,i,s,r){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.radiusList=s),void 0!==r&&(this.indexes=r)}},e.ChamferDto=class{constructor(e,t,i,s){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.distanceList=i),void 0!==s&&(this.indexes=s)}},e.ChamferEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.distanceList=i)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances1=s),void 0!==r&&(this.distances2=r)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances=s),void 0!==r&&(this.angles=r)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,i,s,r){this.keepLines=p.outside,this.circleRemainders=_.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.keepLines=i),void 0!==s&&(this.circleRemainders=s),void 0!==r&&(this.tolerance=r)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,i,s){this.combination=f.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,i,s){this.combination=f.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,i,s){this.nrZigZags=20,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==i&&(this.nrZigZags=i),void 0!==s&&(this.inverse=s)}},e.InterpolationDto=class{constructor(e,t,i){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==i&&(this.tolerance=i)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.ProjectWireDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.WiresToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.EdgesToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.ProjectWiresDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.DivideShapesDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,i,s){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.tEdgeParam=i),void 0!==s&&(this.distance2DParam=s)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,i,r,n,o,a,l,h,c,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=s.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==i&&(this.closed=i),void 0!==r&&(this.periodic=r),void 0!==n&&(this.straight=n),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==l&&(this.maxUDegree=l),void 0!==h&&(this.tolerance=h),void 0!==c&&(this.parType=c),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,i,s){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==i&&(this.distance=i),void 0!==s&&(this.tolerance=s)}},e.OffsetAdvancedDto=class{constructor(e,i,s,r,n,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.joinType=n),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,i,s){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.copy=s)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,i){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.nrCorners=i)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,i){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==i&&(this.keepEdges=i)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,i){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==i&&(this.precsmall=i)}},e.BasicShapeRepairDto=class{constructor(e,t,i,s){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.maxTolerance=i),void 0!==s&&(this.minTolerance=s)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,i){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==i&&(this.angle=i)}},e.ThickSolidByJoinDto=class{constructor(e,i,s,r,n,o,a,l){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.shapes=i),void 0!==s&&(this.offset=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.intersection=n),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==l&&(this.removeIntEdges=l)}},e.TransformDto=class{constructor(e,t,i,s,r){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==i&&(this.rotationAxis=i),void 0!==s&&(this.rotationAngle=s),void 0!==r&&(this.scaleFactor=r)}},e.TransformShapesDto=class{constructor(e,t,i,s,r){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==i&&(this.rotationAxes=i),void 0!==s&&(this.rotationAngles=s),void 0!==r&&(this.scaleFactors=r)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,i,s,r){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==i&&(this.fromDirection=i),void 0!==s&&(this.toOrigin=s),void 0!==r&&(this.toDirection=r)}},e.AlignShapesDto=class{constructor(e,t,i,s,r){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==i&&(this.fromDirections=i),void 0!==s&&(this.toOrigins=s),void 0!==r&&(this.toDirections=r)}},e.MirrorDto=class{constructor(e,t,i){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.direction=i)}},e.MirrorShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.directions=i)}},e.MirrorAlongNormalDto=class{constructor(e,t,i){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.normal=i)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.normals=i)}},e.AlignAndTranslateDto=class{constructor(e,t,i){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.center=i)}},e.UnifySameDomainDto=class{constructor(e,t,i,s){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==i&&(this.unifyFaces=i),void 0!==s&&(this.concatBSplines=s)}},e.FilterFacePointsDto=class{constructor(e,t,i,s,r,n,o,a,l){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.useBndBox=s),void 0!==r&&(this.gapTolerance=r),void 0!==n&&(this.keepIn=n),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==l&&(this.keepUnknown=l)}},e.FilterSolidPointsDto=class{constructor(e,t,i,s,r,n,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.keepIn=s),void 0!==r&&(this.keepOn=r),void 0!==n&&(this.keepOut=n),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,i){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==i&&(this.centers=i)}},e.RotateDto=class{constructor(e,t,i){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundCenterDto=class{constructor(e,t,i,s){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.center=i),void 0!==s&&(this.axis=s)}},e.RotateShapesDto=class{constructor(e,t,i){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==i&&(this.angles=i)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,i,s){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==i&&(this.centers=i),void 0!==s&&(this.axes=s)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,i){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==i&&(this.center=i)}},e.Scale3DShapesDto=class{constructor(e,t,i){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==i&&(this.centers=i)}},e.ShapeToMeshDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.ShapesToMeshesDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.SaveStepDto=class{constructor(e,t,i,s){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustYtoZ=i),void 0!==s&&(this.tryDownload=s)}},e.SaveStlDto=class{constructor(e,t,i,s,r,n){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.precision=i),void 0!==s&&(this.adjustYtoZ=s),void 0!==r&&(this.tryDownload=r),void 0!==n&&(this.binary=n)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,i){this.fileType=n.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==i&&(this.adjustZtoY=i)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,i){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustZtoY=i)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,i){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==i&&(this.direction=i)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,i){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==i&&(this.dir=i)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,i,s){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==i&&(this.nrOfPointsV=i),void 0!==s&&(this.flat=s)}},e.Geom2dEllipseDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s),void 0!==r&&(this.sense=r)}},e.Geom2dCircleDto=class{constructor(e,t,i,s){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.sense=s)}},e.ChristmasTreeDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==i&&(this.outerDist=i),void 0!==s&&(this.nrSkirts=s),void 0!==r&&(this.trunkHeight=r),void 0!==n&&(this.trunkWidth=n),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,i,s,r,n,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.numRays=i),void 0!==s&&(this.center=s),void 0!==r&&(this.direction=r),void 0!==n&&(this.offsetOuterEdges=n),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.aroundCenter=i),void 0!==s&&(this.width=s),void 0!==r&&(this.height=r),void 0!==n&&(this.angle=n)}},e.Heart2DDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.sizeApprox=s)}},e.NGonWireDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.nrCorners=i),void 0!==s&&(this.radius=s)}},e.EllipseDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,i,s,r){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==i&&(this.u2=i),void 0!==s&&(this.sense=s),void 0!==r&&(this.adjustPeriodic=r)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,i){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==i&&(this.direction=i)}},e.SliceInStepPatternDto=class{constructor(e,t,i){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==i&&(this.direction=i)}}}(rk||(rk={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(nk||(nk={})),"undefined"!=typeof document&&document.currentScript&&document.currentScript.src;class ck{constructor(e){this.context=e}create(e){const t=new de(e.target[0],e.target[1],e.target[2]),i=new Th(`arcRotateCamera${Math.random()}`,this.getRadians(e.alpha),this.getRadians(e.beta),e.radius,t,this.context.scene);void 0!==e.angularSensibilityX&&(i.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(i.angularSensibilityY=e.angularSensibilityY),void 0!==e.lowerBetaLimit&&(i.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(i.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.panningSensibility&&(i.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(i.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(i.maxZ=e.maxZ),i.minZ=0;const s=document.getElementById("renderCanvas");return i.attachControl(s,!0),i}getRadians(e){let t=vr.FromDegrees(e).radians();return e<0&&(t=-t),t}}class uk{constructor(e){this.context=e}create(e){const t=new de(e.position[0],e.position[1],e.position[2]),i=new xh(`freeCamera${Math.random()}`,t,this.context.scene),s=new de(e.target[0],e.target[1],e.target[2]);i.setTarget(s);const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i.minZ=0,i.maxZ=1e3,i}}class dk{constructor(e){this.context=e}create(e){const t=new de(e.position[0],e.position[1],e.position[2]),i=new vh(`freeCamera${Math.random()}`,t,this.context.scene),s=new de(e.target[0],e.target[1],e.target[2]);i.setTarget(s);const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i.minZ=0,i.maxZ=1e3,i}}class _k{constructor(e){this.context=e,this.free=new uk(this.context),this.arcRotate=new ck(this.context),this.target=new dk(this.context)}freezeProjectionMatrix(e){e.camera.freezeProjectionMatrix()}unfreezeProjectionMatrix(e){e.camera.unfreezeProjectionMatrix()}setPosition(e){const t=new de(e.position[0],e.position[1],e.position[2]);e.camera.position=t}getPosition(e){return[e.camera.position.x,e.camera.position.y,e.camera.position.z]}setTarget(e){const t=new de(e.target[0],e.target[1],e.target[2]);e.camera.setTarget(t)}getTarget(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setSpeed(e){e.camera.speed=e.speed}getSpeed(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setMinZ(e){e.camera.minZ=e.minZ}setMaxZ(e){e.camera.maxZ=e.maxZ}makeCameraOrthographic(e){e.camera.mode=Kr.ORTHOGRAPHIC_CAMERA,e.camera.orthoBottom=e.orthoBottom||-1,e.camera.orthoTop=e.orthoTop||1,e.camera.orthoLeft=e.orthoLeft||-1,e.camera.orthoRight=e.orthoRight||1}makeCameraPerspective(e){e.camera.mode=Kr.PERSPECTIVE_CAMERA}}class pk{constructor(e,t){this.context=e,this.color=t}create(e){const t=new zv(e.name,this.context.scene);return t.baseColor=Ce.FromHexString(e.baseColor),t.metallic=e.metallic,t.roughness=e.roughness,t.alpha=e.alpha,t.backFaceCulling=e.backFaceCulling,t.zOffset=e.zOffset,t.alphaMode=1,e.emissiveColor&&(t.emissiveColor=Ce.FromHexString(e.emissiveColor)),t}setBaseColor(e){e.material.baseColor=Ce.FromHexString(e.baseColor)}setMetallic(e){e.material.metallic=e.metallic}setRoughness(e){e.material.roughness=e.roughness}setAlpha(e){e.material.alpha=e.alpha}setBackFaceCulling(e){e.material.backFaceCulling=e.backFaceCulling}setBaseTexture(e){e.material.baseTexture=e.baseTexture}getBaseColor(e){const t=e.material,i=this.context.remap(t.baseColor.r,0,1,0,255),s=this.context.remap(t.baseColor.g,0,1,0,255),r=this.context.remap(t.baseColor.b,0,1,0,255);return this.color.rgbToHex({r:i,g:s,b:r})}getMetallic(e){return e.material.metallic}getRoughness(e){return e.material.roughness}getAlpha(e){return e.material.alpha}getBackFaceCulling(e){return e.material.backFaceCulling}getBaseTexture(e){return e.material.baseTexture}}class fk{constructor(e,t){this.context=e,this.color=t,this.pbrMetallicRoughness=new pk(e,t)}}var mk,gk=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class vk{constructor(e){this.context=e}createDefaultXRExperienceWithTeleportation(e){return gk(this,void 0,void 0,(function*(){const t=yield this.context.scene.createDefaultXRExperienceAsync();this.context.scene.metadata?this.context.scene.metadata.xr=t:this.context.scene.metadata={xr:t};const i=[];e.groundMeshes.forEach((e=>{e.getChildMeshes&&(null==e||e.getChildMeshes().forEach((e=>{e.isPickable=!0,i.push(e)}))),i.push(e),e.isPickable=!0}));const s=t.baseExperience.featuresManager,r=new zv("teleportation");r.baseColor=new Ce(0,0,1),r.metallic=0,r.roughness=1,s.enableFeature(ha.TELEPORTATION,"stable",{xrInput:t.input,floorMeshes:i,defaultTargetMeshOptions:{torusArrowMaterial:r,disableLighting:!1}});const n=new SN(this.context.scene);this.context.scene.metadata.guiManager=n,n.useRealisticScaling=!0;const o=new sN("near");n.addControl(o);const a=new Qw("button1"),l=new UD;l.text="Exit VR",l.color="white",l.fontSize="48px",a.onPointerClickObservable.add((()=>gk(this,void 0,void 0,(function*(){yield t.baseExperience.exitXRAsync()})))),o.addButton(a),a.content=l}))}}class xk{constructor(e){this.context=e}getEngine(){return this.context.engine}getRenderingCanvas(){return this.context.engine.getRenderingCanvas()}}class bk{static _CreateBufferView(e,t,i,s,r){const n={buffer:e,byteLength:i};return t&&(n.byteOffset=t),r&&(n.name=r),s&&(n.byteStride=s),n}static _CreateAccessor(e,t,i,s,r,n,o,a){const l={name:t,bufferView:e,componentType:s,count:r,type:i};return null!=o&&(l.min=o),null!=a&&(l.max=a),null!=n&&(l.byteOffset=n),l}static _CalculateMinMaxPositions(e,t,i){const s=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];let n,o,a;if(i)for(let l=t,h=t+i;lr[e]&&(r[e]=t),++n}}return{min:s,max:r}}static _NormalizeTangentFromRef(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);t>0&&(e.x/=t,e.y/=t,e.z/=t)}static _GetDataAccessorElementCount(e){switch(e){case"MAT2":case"VEC4":return 4;case"MAT3":return 9;case"MAT4":return 16;case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3}}}!function(e){e[e.INTANGENT=0]="INTANGENT",e[e.OUTTANGENT=1]="OUTTANGENT"}(mk||(mk={}));class Tk{static _IsTransformable(e){return e&&(e instanceof xn||e instanceof Kr||e instanceof yo)}static _CreateNodeAnimation(e,t,i,s,r){if(this._IsTransformable(e)){const n=[],o=[],a=t.getKeys(),l=Tk._CalculateMinMaxKeyFrames(a),h=Tk._DeduceInterpolation(a,i,s),c=h.interpolationType,u=h.shouldBakeAnimation;if(u?Tk._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,r,n,o,l,s):"LINEAR"===c||"STEP"===c?Tk._CreateLinearOrStepAnimation(e,t,i,n,o,s):"CUBICSPLINE"===c?Tk._CreateCubicSplineAnimation(e,t,i,n,o,s):Tk._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,r,n,o,l,s),n.length&&o.length)return{inputs:n,outputs:o,samplerInterpolation:c,inputsMin:u?l.min:hs.FloatRound(l.min/t.framePerSecond),inputsMax:u?l.max:hs.FloatRound(l.max/t.framePerSecond)}}return null}static _DeduceAnimationInfo(e){let t=null,i="VEC3",s=!1;const r=e.targetProperty.split(".");switch(r[0]){case"scaling":t="scale";break;case"position":t="translation";break;case"rotation":i="VEC4",t="rotation";break;case"rotationQuaternion":i="VEC4",s=!0,t="rotation";break;case"influence":i="SCALAR",t="weights";break;default:hs.Error(`Unsupported animatable property ${r[0]}`)}return t?{animationChannelTargetPath:t,dataAccessorType:i,useQuaternion:s}:(hs.Error("animation channel target path and data accessor type could be deduced"),null)}static _CreateNodeAnimationFromNodeAnimations(e,t,i,s,r,n,o,a,l,h){let c;if(Tk._IsTransformable(e)&&e.animations)for(const r of e.animations){if(h&&!h(r))continue;const u=Tk._DeduceAnimationInfo(r);u&&(c={name:r.name,samplers:[],channels:[]},Tk._AddAnimation(`${r.name}`,r.hasRunningRuntimeAnimations?t:c,e,r,u.dataAccessorType,u.animationChannelTargetPath,s,n,o,a,u.useQuaternion,l),c.samplers.length&&c.channels.length&&i.push(c))}}static _CreateMorphTargetAnimationFromMorphTargetAnimations(e,t,i,s,r,n,o,a,l,h){let c;if(e instanceof bo){const r=e.morphTargetManager;if(r)for(let u=0;u{for(let i=0;ie.morphTargetManager===i));s&&(h.has(s)||h.set(s,new Map),h.get(s)?.set(t,f),d.add(s),u.set(s,f))}}}}d.forEach((e=>{const t=e.morphTargetManager;let a=null;const d=[],p=u.get(e).getKeys(),f=p.length;for(let i=0;i0;)t=_.inputs.shift(),e%d==0&&i.push(t),e++;_.inputs=i}const s=o[i.uniqueId];let c=4*_.inputs.length;p=bk._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} keyframe data view`),l.push(p),_.inputs.forEach((function(e){a.setFloat32(e)})),f=bk._CreateAccessor(l.length-1,`${e} keyframes`,"SCALAR",5126,_.inputs.length,null,[_.inputsMin],[_.inputsMax]),h.push(f),m=h.length-1,v=_.outputs.length,c=4*bk._GetDataAccessorElementCount(r)*_.outputs.length,p=bk._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} data view`),l.push(p),_.outputs.forEach((function(e){e.forEach((function(e){a.setFloat32(e)}))})),f=bk._CreateAccessor(l.length-1,`${e} data`,r,5126,v,null,null,null),h.push(f),g=h.length-1,x={interpolation:_.samplerInterpolation,input:m,output:g},t.samplers.push(x),b={sampler:t.samplers.length-1,target:{node:s,path:n}},t.channels.push(b)}}static _CreateBakedAnimation(e,t,i,s,r,n,o,a,l,h,c){let u;const d=pe.Identity();let _,p=null,f=null,m=null,g=null,v=null,x=null;h.min=hs.FloatRound(s/n);const b=t.getKeys();for(let s=0,h=b.length;s{"StandardMaterial"===e.getClassName()?s.push(this._convertStandardMaterialAsync(e,t,i)):-1!==e.getClassName().indexOf("PBR")?s.push(this._convertPBRMaterialAsync(e,t,i)):hs.Warn(`Unsupported material type: ${e.name}`)})),Promise.all(s).then((()=>{}))}_stripTexturesFromMaterial(e){const t={};if(e){t.name=e.name,t.doubleSided=e.doubleSided,t.alphaMode=e.alphaMode,t.alphaCutoff=e.alphaCutoff,t.emissiveFactor=e.emissiveFactor;const i=e.pbrMetallicRoughness;i&&(t.pbrMetallicRoughness={},t.pbrMetallicRoughness.baseColorFactor=i.baseColorFactor,t.pbrMetallicRoughness.metallicFactor=i.metallicFactor,t.pbrMetallicRoughness.roughnessFactor=i.roughnessFactor)}return t}_hasTexturesPresent(e){if(e.emissiveTexture||e.normalTexture||e.occlusionTexture)return!0;const t=e.pbrMetallicRoughness;if(t&&(t.baseColorTexture||t.metallicRoughnessTexture))return!0;if(e.extensions)for(const t in e.extensions){const i=e.extensions[t];if(i)return i.hasTextures?.()}return!1}_getTextureInfo(e){if(e){const t=e.uid;if(t in this._textureMap)return this._textureMap[t]}return null}_convertToGLTFPBRMetallicRoughness(e){const t=new ue(0,1),i=new ue(0,.1),s=new ue(0,.1),r=new ue(1300,.1),n=e.diffuseColor.toLinearSpace(e.getScene().getEngine().useExactSrgbConversions).scale(.5),o=e.alpha,a=(l=xe.Clamp(e.specularPower,0,Sk._MaxSpecularPower),h=Math.pow(l/r.x,.333333),c=t.y,u=i.y,d=s.y,_=r.y,(1-h)*(1-h)*(1-h)*c+3*(1-h)*(1-h)*h*u+3*(1-h)*h*h*d+h*h*h*_);var l,h,c,u,d,_;return{baseColorFactor:[n.r,n.g,n.b,o],metallicFactor:0,roughnessFactor:a}}static _SolveMetallic(e,t,i){if(t{e&&(o.baseColorTexture=e)})));const i=e.bumpTexture;i&&n.push(this._exportTextureAsync(i,t).then((e=>{e&&(a.normalTexture=e,1!==i.level&&(a.normalTexture.scale=i.level))}))),e.emissiveTexture&&(a.emissiveFactor=[1,1,1],n.push(this._exportTextureAsync(e.emissiveTexture,t).then((e=>{e&&(a.emissiveTexture=e)})))),e.ambientTexture&&n.push(this._exportTextureAsync(e.ambientTexture,t).then((e=>{if(e){const t={index:e.index};a.occlusionTexture=t}})))}return(e.alpha<1||e.opacityTexture)&&(e.alphaMode===Yd.ALPHA_COMBINE?a.alphaMode="BLEND":hs.Warn(e.name+": glTF 2.0 does not support alpha mode: "+e.alphaMode.toString())),e.emissiveColor&&!Sk._FuzzyEquals(e.emissiveColor,Ce.Black(),Sk._Epsilon)&&(a.emissiveFactor=e.emissiveColor.asArray()),a.pbrMetallicRoughness=o,Sk._SetAlphaMode(a,e),r.push(a),s[e.uniqueId]=r.length-1,this._finishMaterial(n,a,e,t)}_finishMaterial(e,t,i,s){return Promise.all(e).then((()=>{const e=this._exporter._extensionsPostExportMaterialAdditionalTextures("exportMaterial",t,i);let r=null;for(const t of e)r||(r=[]),r.push(this._exportTextureAsync(t,s));return r||(r=[Promise.resolve(null)]),Promise.all(r).then((()=>{const e=this._exporter._extensionsPostExportMaterialAsync("exportMaterial",t,i);return e?e.then((()=>t)):t}))}))}async _getImageDataAsync(e,t,i,s){const r=Yd.TEXTURETYPE_UNSIGNED_INT,n=this._exporter._babylonScene,o=n.getEngine(),a=o.createRawTexture(e,t,i,Yd.TEXTUREFORMAT_RGBA,!1,!0,Vo.NEAREST_SAMPLINGMODE,null,r);await g_.ApplyPostProcess("pass",a,n,r,Yd.TEXTURE_NEAREST_SAMPLINGMODE,Yd.TEXTUREFORMAT_RGBA);const l=await o._readTexturePixels(a,t,i);return await _l.DumpDataAsync(t,i,l,s,void 0,!0,!0)}_createWhiteTexture(e,t,i){const s=new Uint8Array(e*t*4);for(let e=0;er.width?(o=t&&t instanceof Vo?g_.CreateResizedCopy(t,s.width,s.height,!0):this._createWhiteTexture(s.width,s.height,i),n=e):(n=e,o=t),{texture1:n,texture2:o}}_convertPixelArrayToFloat32(e){if(e instanceof Uint8Array){const t=e.length,i=new Float32Array(e.length);for(let s=0;sSk._Epsilon?T.baseColor.r:1,m[i+1]/=T.baseColor.g>Sk._Epsilon?T.baseColor.g:1,m[i+2]/=T.baseColor.b>Sk._Epsilon?T.baseColor.b:1;const s=Ce.FromInts(m[i],m[i+1],m[i+2]).toGammaSpace(n.getEngine().useExactSrgbConversions);m[i]=255*s.r,m[i+1]=255*s.g,m[i+2]=255*s.b,Sk._FuzzyEquals(s,Ce.White(),Sk._Epsilon)||(S=!0),f[i+1]/=T.roughness>Sk._Epsilon?T.roughness:1,f[i+2]/=T.metallic>Sk._Epsilon?T.metallic:1;const r=Ce.FromInts(255,f[i+1],f[i+2]);Sk._FuzzyEquals(r,Ce.White(),Sk._Epsilon)||(y=!0)}return y&&r.push(this._getImageDataAsync(f,c,u,s).then((e=>{T.metallicRoughnessTextureData=e}))),S&&r.push(this._getImageDataAsync(m,c,u,s).then((e=>{T.baseColorTextureData=e}))),Promise.all(r).then((()=>T))}return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!")}_convertSpecularGlossinessToMetallicRoughness(e){const t=this._getPerceivedBrightness(e.diffuseColor),i=this._getPerceivedBrightness(e.specularColor),s=1-this._getMaxComponent(e.specularColor),r=Sk._SolveMetallic(t,i,s),n=e.diffuseColor.scale(s/(1-Sk._DielectricSpecular.r)/Math.max(1-r,Sk._Epsilon)),o=e.specularColor.subtract(Sk._DielectricSpecular.scale(1-r)).scale(1/Math.max(r,Sk._Epsilon));let a=Ce.Lerp(n,o,r*r);return a=a.clampToRef(0,1,a),{baseColor:a,metallic:r,roughness:1-e.glossiness}}_getPerceivedBrightness(e){return e?Math.sqrt(.299*e.r*e.r+.587*e.g*e.g+.114*e.b*e.b):0}_getMaxComponent(e){return e?Math.max(e.r,Math.max(e.g,e.b)):0}_convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,i,s){const r=[],n={baseColor:e._albedoColor,metallic:e._metallic,roughness:e._roughness};if(s){e._albedoTexture&&r.push(this._exportTextureAsync(e._albedoTexture,t).then((e=>{e&&(i.baseColorTexture=e)})));const s=e._metallicTexture;s&&r.push(this._exportTextureAsync(s,t).then((e=>{e&&(i.metallicRoughnessTexture=e)})))}return Promise.all(r).then((()=>n))}_getTextureSampler(e){const t={};if(!(e&&e instanceof Vo))return t;const i=this._getGLTFTextureWrapMode(e.wrapU);10497!==i&&(t.wrapS=i);const s=this._getGLTFTextureWrapMode(e.wrapV);switch(10497!==s&&(t.wrapT=s),e.samplingMode){case Vo.LINEAR_LINEAR:t.magFilter=9729,t.minFilter=9729;break;case Vo.LINEAR_NEAREST:t.magFilter=9729,t.minFilter=9728;break;case Vo.NEAREST_LINEAR:t.magFilter=9728,t.minFilter=9729;break;case Vo.NEAREST_LINEAR_MIPLINEAR:t.magFilter=9728,t.minFilter=9987;break;case Vo.NEAREST_NEAREST:t.magFilter=9728,t.minFilter=9728;break;case Vo.NEAREST_LINEAR_MIPNEAREST:t.magFilter=9728,t.minFilter=9985;break;case Vo.LINEAR_NEAREST_MIPNEAREST:t.magFilter=9729,t.minFilter=9984;break;case Vo.LINEAR_NEAREST_MIPLINEAR:t.magFilter=9729,t.minFilter=9986;break;case Vo.NEAREST_NEAREST_MIPLINEAR:t.magFilter=9728,t.minFilter=9986;break;case Vo.LINEAR_LINEAR_MIPLINEAR:t.magFilter=9729,t.minFilter=9987;break;case Vo.LINEAR_LINEAR_MIPNEAREST:t.magFilter=9729,t.minFilter=9985;break;case Vo.NEAREST_NEAREST_MIPNEAREST:t.magFilter=9728,t.minFilter=9984}return t}_getGLTFTextureWrapMode(e){switch(e){case Vo.WRAP_ADDRESSMODE:return 10497;case Vo.CLAMP_ADDRESSMODE:return 33071;case Vo.MIRROR_ADDRESSMODE:return 33648;default:return hs.Error(`Unsupported Texture Wrap Mode ${e}!`),10497}}_convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,i,s){return Promise.resolve().then((()=>{const r={diffuseColor:e._albedoColor,specularColor:e._reflectivityColor,glossiness:e._microSurface},n=e._albedoTexture,o=e._reflectivityTexture,a=e._useMicroSurfaceFromReflectivityMapAlpha;if(o&&!a)return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");if((n||o)&&s){const e=this._exportTextureSampler(n||o);return this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(n,o,r,t).then((s=>{const r=this._exporter._textures;if(s.baseColorTextureData){const o=this._exportImage(`baseColor${r.length}`,t,s.baseColorTextureData);i.baseColorTexture=this._exportTextureInfo(o,e,n?.coordinatesIndex)}if(s.metallicRoughnessTextureData){const n=this._exportImage(`metallicRoughness${r.length}`,t,s.metallicRoughnessTextureData);i.metallicRoughnessTexture=this._exportTextureInfo(n,e,o?.coordinatesIndex)}return s}))}return this._convertSpecularGlossinessToMetallicRoughness(r)}))}_convertPBRMaterialAsync(e,t,i){const s={},r={name:e.name};if(e.isMetallicWorkflow()){const n=e._albedoColor,o=e.alpha;return n&&(s.baseColorFactor=[n.r,n.g,n.b,o]),this._convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,s,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,r,s,t,i)))}return this._convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,s,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,r,s,t,i)))}_setMetallicRoughnessPbrMaterial(e,t,i,s,r,n){const o=this._exporter._materialMap,a=this._exporter._materials,l=[];if(e){if(Sk._SetAlphaMode(i,t),Sk._FuzzyEquals(e.baseColor,Ce.White(),Sk._Epsilon)&&t.alpha>=Sk._Epsilon||(s.baseColorFactor=[e.baseColor.r,e.baseColor.g,e.baseColor.b,t.alpha]),null!=e.metallic&&1!==e.metallic&&(s.metallicFactor=e.metallic),null!=e.roughness&&1!==e.roughness&&(s.roughnessFactor=e.roughness),null==t.backFaceCulling||t.backFaceCulling||(t._twoSidedLighting||hs.Warn(t.name+": Back-face culling disabled and two-sided lighting disabled is not supported in glTF."),i.doubleSided=!0),n){const e=t._bumpTexture;if(e){const t=this._exportTextureAsync(e,r).then((t=>{t&&(i.normalTexture=t,1!==e.level&&(i.normalTexture.scale=e.level))}));l.push(t)}const s=t._ambientTexture;if(s){const e=this._exportTextureAsync(s,r).then((e=>{if(e){const s={index:e.index,texCoord:e.texCoord,extensions:e.extensions};i.occlusionTexture=s;const r=t._ambientTextureStrength;r&&(s.strength=r)}}));l.push(e)}const n=t._emissiveTexture;if(n){const e=this._exportTextureAsync(n,r).then((e=>{e&&(i.emissiveTexture=e)}));l.push(e)}}const h=t._emissiveColor;Sk._FuzzyEquals(h,Ce.Black(),Sk._Epsilon)||(i.emissiveFactor=h.asArray()),i.pbrMetallicRoughness=s,a.push(i),o[t.uniqueId]=a.length-1}return this._finishMaterial(l,i,t,r)}_getPixelsFromTexture(e){return e.textureType,Yd.TEXTURETYPE_UNSIGNED_INT,e.readPixels()}_exportTextureAsync(e,t){const i=this._exporter._extensionsPreExportTextureAsync("exporter",e,t);return i?i.then((i=>i?this._exportTextureInfoAsync(i,t):this._exportTextureInfoAsync(e,t))):this._exportTextureInfoAsync(e,t)}async _exportTextureInfoAsync(e,t){const i=e.uid;if(!(i in this._textureMap)){const s=await this._getPixelsFromTexture(e);if(!s)return null;const r=this._exportTextureSampler(e),n=e.mimeType;if(n)switch(n){case"image/jpeg":case"image/png":case"image/webp":t=n;break;default:hs.Warn(`Unsupported media type: ${n}`)}const o=this._internalTextureToImage,a=e.getInternalTexture().uniqueId;o[a]||(o[a]={});let l=o[a][t];if(void 0===l){const i=e.getSize();l=(async()=>{const r=await this._getImageDataAsync(s,i.width,i.height,t);return this._exportImage(e.name,t,r)})(),o[a][t]=l}const h=this._exportTextureInfo(await l,r,e.coordinatesIndex);this._textureMap[i]=h,this._exporter._extensionsPostExportTextures("exporter",this._textureMap[i],e)}return this._textureMap[i]}_exportImage(e,t,i){const s=this._exporter._imageData,r=e.replace(/\.\/|\/|\.\\|\\/g,"_"),n=function(e){switch(e){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/webp":return".webp";case"image/avif":return".avif"}}(t);let o=r+n;o in s&&(o=`${r}_${hs.RandomId()}${n}`),s[o]={data:i,mimeType:t};const a=this._exporter._images;return a.push({name:e,uri:o}),a.length-1}_exportTextureInfo(e,t,i){const s=this._exporter._textures;let r=s.findIndex((i=>i.sampler==t&&i.source===e));-1===r&&(r=s.length,s.push({source:e,sampler:t}));const n={index:r};return i&&(n.texCoord=i),n}_exportTextureSampler(e){const t=this._getTextureSampler(e),i=this._exporter._samplers,s=i.findIndex((e=>e.minFilter===t.minFilter&&e.magFilter===t.magFilter&&e.wrapS===t.wrapS&&e.wrapT===t.wrapT));return-1!==s?s:(i.push(t),i.length-1)}}Sk._DielectricSpecular=new Ce(.04,.04,.04),Sk._MaxSpecularPower=1024,Sk._Epsilon=1e-6;const Ck=fe.Compose(new de(-1,1,1),pe.Identity(),de.Zero()),Ek=new pe(0,1,0,0);function Ak(e,t){if(!(e instanceof xn))return!1;if(t){if(!e.getWorldMatrix().isIdentity())return!1}else if(!e.getWorldMatrix().multiplyToRef(Ck,ge.Matrix[0]).isIdentity())return!1;return!(e instanceof bo&&e.geometry||e instanceof To&&e.sourceMesh.geometry)}function Pk(e){const t=de.FromArrayToRef(e.translation||[0,0,0],0,ge.Vector3[0]),i=pe.FromArrayToRef(e.rotation||[0,0,0,1],0,ge.Quaternion[0]),s=de.FromArrayToRef(e.scale||[1,1,1],0,ge.Vector3[1]);fe.ComposeToRef(s,i,t,ge.Matrix[0]).multiplyToRef(Ck,ge.Matrix[0]).decompose(s,i,t),t.equalsToFloats(0,0,0)?delete e.translation:e.translation=t.asArray(),pe.IsIdentity(i)?delete e.rotation:e.rotation=i.asArray(),s.equalsToFloats(1,1,1)?delete e.scale:e.scale=s.asArray()}class Rk{_applyExtension(e,t,i,s){if(i>=t.length)return Promise.resolve(e);const r=s(t[i],e);return r?r.then((e=>this._applyExtension(e,t,i+1,s))):this._applyExtension(e,t,i+1,s)}_applyExtensions(e,t){const i=[];for(const e of Rk._ExtensionNames)i.push(this._extensions[e]);return this._applyExtension(e,i,0,t)}_extensionsPreExportTextureAsync(e,t,i){return this._applyExtensions(t,((t,s)=>t.preExportTextureAsync&&t.preExportTextureAsync(e,s,i)))}_extensionsPostExportMeshPrimitiveAsync(e,t,i,s){return this._applyExtensions(t,((t,r)=>t.postExportMeshPrimitiveAsync&&t.postExportMeshPrimitiveAsync(e,r,i,s)))}_extensionsPostExportNodeAsync(e,t,i,s,r){return this._applyExtensions(t,((t,n)=>t.postExportNodeAsync&&t.postExportNodeAsync(e,n,i,s,r)))}_extensionsPostExportMaterialAsync(e,t,i){return this._applyExtensions(t,((t,s)=>t.postExportMaterialAsync&&t.postExportMaterialAsync(e,s,i)))}_extensionsPostExportMaterialAdditionalTextures(e,t,i){const s=[];for(const r of Rk._ExtensionNames){const n=this._extensions[r];n.postExportMaterialAdditionalTextures&&s.push(...n.postExportMaterialAdditionalTextures(e,t,i))}return s}_extensionsPostExportTextures(e,t,i){for(const s of Rk._ExtensionNames){const r=this._extensions[s];r.postExportTexture&&r.postExportTexture(e,t,i)}}_forEachExtensions(e){for(const t of Rk._ExtensionNames){const i=this._extensions[t];i.enabled&&e(i)}}_extensionsOnExporting(){this._forEachExtensions((e=>{e.wasUsed&&(null==this._glTF.extensionsUsed&&(this._glTF.extensionsUsed=[]),-1===this._glTF.extensionsUsed.indexOf(e.name)&&this._glTF.extensionsUsed.push(e.name),e.required&&(null==this._glTF.extensionsRequired&&(this._glTF.extensionsRequired=[]),-1===this._glTF.extensionsRequired.indexOf(e.name)&&this._glTF.extensionsRequired.push(e.name)),null==this._glTF.extensions&&(this._glTF.extensions={}),e.onExporting&&e.onExporting())}))}_loadExtensions(){for(const e of Rk._ExtensionNames){const t=Rk._ExtensionFactories[e](this);this._extensions[e]=t}}constructor(e,t){this._extensions={},this._glTF={asset:{generator:`Babylon.js v${gn.Version}`,version:"2.0"}},(e=e||se.LastCreatedScene)&&(this._babylonScene=e,this._bufferViews=[],this._accessors=[],this._meshes=[],this._scenes=[],this._cameras=[],this._nodes=[],this._images=[],this._materials=[],this._materialMap=[],this._textures=[],this._samplers=[],this._skins=[],this._animations=[],this._imageData={},this._orderedImageData=[],this._options=t||{},this._animationSampleRate=this._options.animationSampleRate||1/60,this._glTFMaterialExporter=new Sk(this),this._loadExtensions())}dispose(){for(const e in this._extensions)this._extensions[e].dispose()}get options(){return this._options}static RegisterExtension(e,t){Rk.UnregisterExtension(e)&&hs.Warn(`Extension with the name ${e} already exists`),Rk._ExtensionFactories[e]=t,Rk._ExtensionNames.push(e)}static UnregisterExtension(e){if(!Rk._ExtensionFactories[e])return!1;delete Rk._ExtensionFactories[e];const t=Rk._ExtensionNames.indexOf(e);return-1!==t&&Rk._ExtensionNames.splice(t,1),!0}_reorderIndicesBasedOnPrimitiveMode(e,t,i,s,r){switch(t){case uo.TriangleFillMode:s||(s=0);for(let t=e.indexStart,i=e.indexStart+e.indexCount;t=n;--t)r.setUInt32(i[t],s),s+=4;break;case uo.TriangleStripDrawMode:e.indexCount>=3&&(r.setUInt32(i[e.indexStart+2],s+4),r.setUInt32(i[e.indexStart+1],s+8))}}_reorderVertexAttributeDataBasedOnPrimitiveMode(e,t,i,s,r,n){switch(t){case uo.TriangleFillMode:this._reorderTriangleFillMode(e,i,s,r,n);break;case uo.TriangleStripDrawMode:this._reorderTriangleStripDrawMode(e,i,s,r,n);break;case uo.TriangleFanDrawMode:this._reorderTriangleFanMode(e,i,s,r,n)}}_reorderTriangleFillMode(e,t,i,s,r){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/ys.GetTypeByteLength(n.type);if(e.verticesCount%3!=0)hs.Error("The submesh vertices for the triangle fill mode is not divisible by 3!");else{const a=[];let l=0;switch(t){case ys.PositionKind:case ys.NormalKind:for(let t=e.verticesStart;t=e.verticesStart;--t)l=t*o,a.push(_e.FromArray(i,l));break;case ys.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,4===n.getSize()?a.push(_e.FromArray(i,l)):a.push(de.FromArray(i,l));break;case ys.UVKind:case ys.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(ue.FromArray(i,l));break;default:hs.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,s+12,t,r)}else hs.Warn(`reorderTriangleStripDrawMode: Vertex buffer kind ${t} not present!`)}_reorderTriangleFanMode(e,t,i,s,r){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/ys.GetTypeByteLength(n.type),a=[];let l=0;switch(t){case ys.PositionKind:case ys.NormalKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(de.FromArray(i,l));break;case ys.TangentKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(_e.FromArray(i,l));break;case ys.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(_e.FromArray(i,l)),4===n.getSize()?a.push(_e.FromArray(i,l)):a.push(de.FromArray(i,l));break;case ys.UVKind:case ys.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(ue.FromArray(i,l));break;default:hs.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,s,t,r)}else hs.Warn(`reorderTriangleFanMode: Vertex buffer kind ${t} not present!`)}_writeVertexAttributeData(e,t,i,s){for(const r of e){i===ys.NormalKind?r.normalize():i===ys.TangentKind&&r instanceof _e&&bk._NormalizeTangentFromRef(r);for(const e of r.asArray())s.setFloat32(e,t),t+=4}}_writeAttributeData(e,t,i,s,r,n){let o,a,l=[];switch(e){case ys.PositionKind:for(let e=0,t=i.length/s;e{e.uri&&(n=this._imageData[e.uri],this._orderedImageData.push(n),r=e.uri.split(".")[0]+" image",o=bk._CreateBufferView(0,a,n.data.byteLength,void 0,r),a+=n.data.byteLength,this._bufferViews.push(o),e.bufferView=this._bufferViews.length-1,e.name=r,e.mimeType=n.mimeType,e.uri=void 0,this._glTF.images||(this._glTF.images=[]),this._glTF.images.push(e))})),s.byteLength=a):this._glTF.images=this._images),e||(s.uri=t+".bin"),i?JSON.stringify(this._glTF,null,2):JSON.stringify(this._glTF)}_generateGLTFAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const s=this._generateJSON(!1,e,!0),r=new Blob([i],{type:"application/octet-stream"}),n=e+".gltf",o=e+".bin",a=new yk;if(a.glTFFiles[n]=s,a.glTFFiles[o]=r,this._imageData)for(const e in this._imageData)a.glTFFiles[e]=new Blob([this._imageData[e].data],{type:this._imageData[e].mimeType});return t&&this.dispose(),a}))}_generateBinaryAsync(){const e=new Ik(4);return this._createSceneAsync(e).then((()=>(this._localEngine&&this._localEngine.dispose(),e.getArrayBuffer())))}_getPadding(e){const t=e%4;return 0===t?t:4-t}_generateGLBAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const s=this._generateJSON(!0),r=e+".glb";let n,o=s.length,a=0;"undefined"!=typeof TextEncoder&&(n=(new TextEncoder).encode(s),o=n.length);for(let e=0;e0){if((null!==o.overrideMaterialSideOrientation?o.overrideMaterialSideOrientation:d.sideOrientation)===(this._babylonScene.useRightHandedSystem?uo.ClockWiseSideOrientation:uo.CounterClockWiseSideOrientation)){let e=null!=l?this._bufferViews[l].byteOffset:null;null==e&&(e=0);let t=null;if(null!=l&&(t=o.getIndices()),t)this._reorderIndicesBasedOnPrimitiveMode(r,h,t,e,i);else for(const e of a){const t=o.getVerticesData(e.kind,void 0,void 0,!0);if(t){const s=this._bufferViews[c[e.kind]].byteOffset||0;this._reorderVertexAttributeDataBasedOnPrimitiveMode(r,h,e.kind,t,s,i)}}}null!=_&&(f.material=_)}if(u){e.extras||(e.extras={}),e.extras.targetNames=[];for(let t=0;t{}))}_createSceneAsync(e){const t={nodes:[]};let i,s,r;const n=[...this._babylonScene.transformNodes,...this._babylonScene.meshes,...this._babylonScene.lights,...this._babylonScene.cameras],o=new Set;if(this._babylonScene.metadata&&(this._options.metadataSelector?t.extras=this._options.metadataSelector(this._babylonScene.metadata):this._babylonScene.metadata.gltf&&(t.extras=this._babylonScene.metadata.gltf.extras)),(this._options.removeNoopRootNodes??1)&&!this._options.includeCoordinateSystemConversionNodes)for(const e of this._babylonScene.rootNodes)Ak(e,this._babylonScene.useRightHandedSystem)&&(o.add(e),n.splice(n.indexOf(e),1));const a=new Map;this._babylonScene.cameras.forEach((e=>{if(this._options.shouldExportNode&&!this._options.shouldExportNode(e))return;const t={type:e.mode===Kr.PERSPECTIVE_CAMERA?"perspective":"orthographic"};if(e.name&&(t.name=e.name),"perspective"===t.type)t.perspective={aspectRatio:e.getEngine().getAspectRatio(e),yfov:e.fovMode===Kr.FOVMODE_VERTICAL_FIXED?e.fov:e.fov*e.getEngine().getAspectRatio(e),znear:e.minZ,zfar:e.maxZ};else if("orthographic"===t.type){const i=e.orthoLeft&&e.orthoRight?.5*(e.orthoRight-e.orthoLeft):.5*e.getEngine().getRenderWidth(),s=e.orthoBottom&&e.orthoTop?.5*(e.orthoTop-e.orthoBottom):.5*e.getEngine().getRenderHeight();t.orthographic={xmag:i,ymag:s,znear:e.minZ,zfar:e.maxZ}}a.set(e,this._cameras.length),this._cameras.push(t)}));const[l,h]=this._getExportNodes(n);return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(h,"image/png",!0).then((()=>this._createNodeMapAndAnimationsAsync(l,e).then((l=>this._createSkinsAsync(l,e).then((h=>{if(this._nodeMap=l,this._totalByteLength=e.getByteOffset(),null==this._totalByteLength)throw new Error("undefined byte length!");for(const e of n)if(i=this._nodeMap[e.uniqueId],void 0!==i&&(s=this._nodes[i],e.metadata&&(this._options.metadataSelector?s.extras=this._options.metadataSelector(e.metadata):e.metadata.gltf&&(s.extras=e.metadata.gltf.extras)),e instanceof Kr&&(s.camera=a.get(e)),this._options.shouldExportNode&&!this._options.shouldExportNode(e)?hs.Log("Omitting "+e.name+" from scene."):(e.parent||this._babylonScene.useRightHandedSystem||Pk(s),e.parent&&!o.has(e.parent)||t.nodes.push(i)),e instanceof bo&&e.skeleton&&(s.skin=h[e.skeleton.uniqueId]),r=e.getDescendants(!0),!s.children&&r&&r.length)){const e=[];for(const t of r)null!=this._nodeMap[t.uniqueId]&&e.push(this._nodeMap[t.uniqueId]);e.length&&(s.children=e)}t.nodes.length&&this._scenes.push(t)}))))))}_getExportNodes(e){const t=[],i=new Set;for(const s of e)if(!this._options.shouldExportNode||this._options.shouldExportNode(s)){t.push(s);const e=s;if(e.subMeshes&&e.subMeshes.length>0){const t=e.material||e.getScene().defaultMaterial;if(t instanceof _o)for(const e of t.subMaterials)e&&i.add(e);else i.add(t)}}else s.name;return[t,i]}_createNodeMapAndAnimationsAsync(e,t){let i=Promise.resolve();const s={};let r;const n={name:"runtime animations",channels:[],samplers:[]},o=[];for(const a of e)i=i.then((()=>this._createNodeAsync(a,t).then((e=>{const i=this._extensionsPostExportNodeAsync("createNodeAsync",e,a,s,t);return null==i?(hs.Warn(`Not exporting node ${a.name}`),Promise.resolve()):i.then((e=>{e&&(this._nodes.push(e),r=this._nodes.length-1,s[a.uniqueId]=r,this._babylonScene.animationGroups.length||(Tk._CreateMorphTargetAnimationFromMorphTargetAnimations(a,n,o,s,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),a.animations.length&&Tk._CreateNodeAnimationFromNodeAnimations(a,n,o,s,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation)))}))}))));return i.then((()=>(n.channels.length&&n.samplers.length&&this._animations.push(n),o.forEach((e=>{e.channels.length&&e.samplers.length&&this._animations.push(e)})),this._babylonScene.animationGroups.length&&Tk._CreateNodeAndMorphAnimationFromAnimationGroups(this._babylonScene,this._animations,s,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),s)))}_createNodeAsync(e,t){return Promise.resolve().then((()=>{const i={},s={primitives:[]};if(e.name&&(i.name=e.name),e instanceof xn){if(this._setNodeTransformation(i,e),e instanceof bo){const t=e.morphTargetManager;if(t&&t.numTargets>0){s.weights=[];for(let e=0;e(s.primitives.length&&(this._meshes.push(s),i.mesh=this._meshes.length-1),i)))}return e instanceof Kr?(this._setCameraTransformation(i,e),i):i}))}_createSkinsAsync(e,t){const i=Promise.resolve(),s={};for(const i of this._babylonScene.skeletons){if(i.bones.length<=0)continue;const r={joints:[]},n=[],o={};let a=-1;for(let e=0;ea&&(a=s))}for(let t=0;t<=a;++t){const i=o[t];n.push(i.getInvertedAbsoluteTransform());const s=i.getTransformNode();s&&null!==e[s.uniqueId]&&void 0!==e[s.uniqueId]?r.joints.push(e[s.uniqueId]):hs.Warn("Exporting a bone without a linked transform node is currently unsupported")}if(r.joints.length>0){const e=64,o=n.length*e,a=t.getByteOffset(),l=bk._CreateBufferView(0,a,o,void 0,"InverseBindMatrices - "+i.name);this._bufferViews.push(l);const h=this._bufferViews.length-1,c=bk._CreateAccessor(h,"InverseBindMatrices - "+i.name,"MAT4",5126,n.length,null,null,null),u=this._accessors.push(c)-1;r.inverseBindMatrices=u,this._skins.push(r),s[i.uniqueId]=this._skins.length-1,n.forEach((e=>{e.m.forEach((e=>{t.setFloat32(e)}))}))}}return i.then((()=>s))}}Rk._ExtensionNames=new Array,Rk._ExtensionFactories={};class Ik{constructor(e){this._arrayBuffer=new ArrayBuffer(e),this._dataView=new DataView(this._arrayBuffer),this._byteOffset=0}_resizeBuffer(e){const t=new ArrayBuffer(e),i=Math.min(this._arrayBuffer.byteLength,e),s=new Uint8Array(this._arrayBuffer,0,i);return new Uint8Array(t).set(s,0),this._arrayBuffer=t,this._dataView=new DataView(this._arrayBuffer),t}getArrayBuffer(){return this._resizeBuffer(this.getByteOffset())}getByteOffset(){if(null==this._byteOffset)throw new Error("Byte offset is undefined!");return this._byteOffset}setUInt8(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint8(this._byteOffset,e),this._byteOffset+=1)}setUInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint16(this._byteOffset,e,!0),this._byteOffset+=2)}getUInt32(e){if(ethis._byteOffset?hs.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0))}setVector3Float32FromRef(e,t){t+8>this._byteOffset?hs.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0))}getVector4Float32FromRef(e,t){t+12>this._byteOffset?hs.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0),e.w=this._dataView.getFloat32(t+12,!0))}setVector4Float32FromRef(e,t){t+12>this._byteOffset?hs.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0),this._dataView.setFloat32(t+12,e.w,!0))}setFloat32(e,t){isNaN(e)&&hs.Error("Invalid data being written!"),null!=t&&(tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setFloat32(this._byteOffset,e,!0),this._byteOffset+=4}setUInt32(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint32(this._byteOffset,e,!0),this._byteOffset+=4)}setInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt16(this._byteOffset,e,!0),this._byteOffset+=2)}setByte(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt8(this._byteOffset,e),this._byteOffset++)}}class Mk{static GLTFAsync(e,t,i){return e.whenReadyAsync().then((()=>{const s=t.replace(/\.[^/.]+$/,"");return new Rk(e,i)._generateGLTFAsync(s)}))}static _PreExportAsync(e,t){return Promise.resolve().then((()=>t&&t.exportWithoutWaitingForScene?Promise.resolve():e.whenReadyAsync()))}static _PostExportAsync(e,t,i){return Promise.resolve().then((()=>(i&&i.exportWithoutWaitingForScene,t)))}static GLBAsync(e,t,i){return this._PreExportAsync(e,i).then((()=>{const s=t.replace(/\.[^/.]+$/,"");return new Rk(e,i)._generateGLBAsync(s).then((t=>this._PostExportAsync(e,t,i)))}))}}const Ok="KHR_texture_transform";class Dk{constructor(){this.name=Ok,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportTexture(e,t,i){if(i&&(0===i.uAng&&0===i.wAng&&0===i.vAng||0===i.uRotationCenter&&0===i.vRotationCenter)){const e={};let s=!1;if(0===i.uOffset&&0===i.vOffset||(e.offset=[i.uOffset,i.vOffset],s=!0),1===i.uScale&&1===i.vScale||(e.scale=[i.uScale,i.vScale],s=!0),0!==i.wAng&&(e.rotation=-i.wAng,s=!0),0!==i.coordinatesIndex&&(e.texCoord=i.coordinatesIndex,s=!0),!s)return;this._wasUsed=!0,t.extensions||(t.extensions={}),t.extensions[Ok]=e}}preExportTextureAsync(e,t){return new Promise(((i,s)=>{t.getScene()?0!==t.uAng||0!==t.vAng?(hs.Warn(`${e}: Texture ${t.name} with rotation in the u or v axis is not supported in glTF.`),i(null)):0===t.wAng||0===t.uRotationCenter&&0===t.vRotationCenter?i(t):(hs.Warn(`${e}: Texture ${t.name} with rotation not centered at the origin cannot be exported with ${Ok}`),i(null)):s(`${e}: "scene" is not defined for Babylon texture ${t.name}!`)}))}}Rk.RegisterExtension(Ok,(()=>new Dk));const wk="KHR_lights_punctual";class Nk{constructor(e){this.name=wk,this.enabled=!0,this.required=!1,this._exporter=e}dispose(){this._lights=null}get wasUsed(){return!!this._lights}onExporting(){this._exporter._glTF.extensions[wk]=this._lights}postExportNodeAsync(e,t,i,s){return new Promise((r=>{if(t&&i instanceof am){let n;const o=i.getTypeID()==yo.LIGHTTYPEID_POINTLIGHT?"point":i.getTypeID()==yo.LIGHTTYPEID_DIRECTIONALLIGHT?"directional":i.getTypeID()==yo.LIGHTTYPEID_SPOTLIGHT?"spot":null;if(null==o)we.Warn(`${e}: Light ${i.name} is not supported in ${wk}`);else{if(i.position.equalsToFloats(0,0,0)||(t.translation=i.position.asArray()),"point"!==o){const e=i.direction,s=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),n=-Math.atan2(e.y,r),o=pe.RotationYawPitchRoll(s+Math.PI,n,0);pe.IsIdentity(o)||(t.rotation=o.asArray())}if(i.falloffType!==yo.FALLOFF_GLTF&&we.Warn(`${e}: Light falloff for ${i.name} does not match the ${wk} specification!`),n={type:o},i.diffuse.equals(Ce.White())||(n.color=i.diffuse.asArray()),1!==i.intensity&&(n.intensity=i.intensity),i.range!==Number.MAX_VALUE&&(n.range=i.range),"spot"===o){const e=i;e.angle!==Math.PI/2&&(null==n.spot&&(n.spot={}),n.spot.outerConeAngle=e.angle/2),0!==e.innerAngle&&(null==n.spot&&(n.spot={}),n.spot.innerConeAngle=e.innerAngle/2)}this._lights||(this._lights={lights:[]}),this._lights.lights.push(n);const a={light:this._lights.lights.length-1},l=i.parent;if(l&&1==l.getChildren().length){const e=this._exporter._nodes[s[l.uniqueId]];if(e){const i=de.FromArrayToRef(e.translation||[0,0,0],0,ge.Vector3[0]),s=pe.FromArrayToRef(e.rotation||[0,0,0,1],0,ge.Quaternion[0]),n=de.FromArrayToRef(e.scale||[1,1,1],0,ge.Vector3[1]),o=fe.ComposeToRef(n,s,i,ge.Matrix[0]),l=de.FromArrayToRef(t.translation||[0,0,0],0,ge.Vector3[2]),h=pe.FromArrayToRef(t.rotation||[0,0,0,1],0,ge.Quaternion[1]),c=fe.ComposeToRef(de.OneReadOnly,h,l,ge.Matrix[1]);return o.multiplyToRef(c,c),c.decompose(n,s,i),i.equalsToFloats(0,0,0)?delete e.translation:e.translation=i.asArray(),pe.IsIdentity(s)?delete e.rotation:e.rotation=s.asArray(),n.equalsToFloats(1,1,1)?delete e.scale:e.scale=n.asArray(),e.extensions||(e.extensions={}),e.extensions[wk]=a,void r(null)}}t.extensions||(t.extensions={}),t.extensions[wk]=a}}r(t)}))}}Rk.RegisterExtension(wk,(e=>new Nk(e)));const Fk="KHR_materials_clearcoat";class Bk{constructor(e){this.name=Fk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Vm&&i.clearCoat.isEnabled?(i.clearCoat.texture&&s.push(i.clearCoat.texture),!i.clearCoat.useRoughnessFromMainTexture&&i.clearCoat.textureRoughness&&s.push(i.clearCoat.textureRoughness),i.clearCoat.bumpTexture&&s.push(i.clearCoat.bumpTexture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Vm){if(!i.clearCoat.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture);let r;r=i.clearCoat.useRoughnessFromMainTexture?this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture):this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.textureRoughness),i.clearCoat.isTintEnabled&&hs.Warn(`Clear Color tint is not supported for glTF export. Ignoring for: ${i.name}`),i.clearCoat.remapF0OnInterfaceChange&&hs.Warn(`Clear Color F0 remapping is not supported for glTF export. Ignoring for: ${i.name}`);const n=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.bumpTexture),o={clearcoatFactor:i.clearCoat.intensity,clearcoatTexture:s??void 0,clearcoatRoughnessFactor:i.clearCoat.roughness,clearcoatRoughnessTexture:r??void 0,clearcoatNormalTexture:n??void 0,hasTextures:()=>null!==o.clearcoatTexture||null!==o.clearcoatRoughnessTexture||null!==o.clearcoatRoughnessTexture};t.extensions[Fk]=o}e(t)}))}}Rk.RegisterExtension(Fk,(e=>new Bk(e)));const Lk="KHR_materials_iridescence";class kk{constructor(e){this.name=Lk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Vm&&i.iridescence.isEnabled?(i.iridescence.texture&&s.push(i.iridescence.texture),i.iridescence.thicknessTexture&&i.iridescence.thicknessTexture!==i.iridescence.texture&&s.push(i.iridescence.thicknessTexture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Vm){if(!i.iridescence.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.texture),r=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.thicknessTexture),n={iridescenceFactor:i.iridescence.intensity,iridescenceIor:i.iridescence.indexOfRefraction,iridescenceThicknessMinimum:i.iridescence.minimumThickness,iridescenceThicknessMaximum:i.iridescence.maximumThickness,iridescenceTexture:s??void 0,iridescenceThicknessTexture:r??void 0,hasTextures:()=>null!==n.iridescenceTexture||null!==n.iridescenceThicknessTexture};t.extensions[Lk]=n}e(t)}))}}Rk.RegisterExtension(Lk,(e=>new kk(e)));const Vk="KHR_materials_anisotropy";class Uk{constructor(e){this.name=Vk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Vm&&i.anisotropy.isEnabled&&!i.anisotropy.legacy?(i.anisotropy.texture&&s.push(i.anisotropy.texture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Vm){if(!i.anisotropy.isEnabled||i.anisotropy.legacy)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.anisotropy.texture),r={anisotropyStrength:i.anisotropy.intensity,anisotropyRotation:i.anisotropy.angle,anisotropyTexture:s??void 0,hasTextures:()=>null!==r.anisotropyTexture};t.extensions[Vk]=r}e(t)}))}}Rk.RegisterExtension(Vk,(e=>new Uk(e)));const Gk="KHR_materials_sheen";class zk{constructor(e){this.name=Gk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){return i instanceof Um&&i.sheen.isEnabled&&i.sheen.texture?[i.sheen.texture]:[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um){if(!i.sheen.isEnabled)return void e(t);this._wasUsed=!0,null==t.extensions&&(t.extensions={});const s={sheenColorFactor:i.sheen.color.asArray(),sheenRoughnessFactor:i.sheen.roughness??0,hasTextures:()=>null!==s.sheenColorTexture||null!==s.sheenRoughnessTexture};i.sheen.texture&&(s.sheenColorTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),i.sheen.textureRoughness&&!i.sheen.useRoughnessFromMainTexture?s.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.textureRoughness)??void 0:i.sheen.texture&&i.sheen.useRoughnessFromMainTexture&&(s.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),t.extensions[Gk]=s}e(t)}))}}Rk.RegisterExtension(Gk,(e=>new zk(e)));const Wk="KHR_materials_unlit";class Hk{constructor(){this.name=Wk,this.enabled=!0,this.required=!1,this._wasUsed=!1}get wasUsed(){return this._wasUsed}dispose(){}postExportMaterialAsync(e,t,i){return new Promise((e=>{let s=!1;i instanceof Um?s=i.unlit:i instanceof yc&&(s=i.disableLighting),s&&(this._wasUsed=!0,null==t.extensions&&(t.extensions={}),t.extensions[Wk]={}),e(t)}))}}Rk.RegisterExtension(Wk,(()=>new Hk));const Xk="KHR_materials_ior";class Yk{constructor(){this.name=Xk,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){return!e.unlit&&null!=e.indexOfRefraction&&1.5!=e.indexOfRefraction}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={ior:i.indexOfRefraction};t.extensions=t.extensions||{},t.extensions[Xk]=e}e(t)}))}}Rk.RegisterExtension(Xk,(e=>new Yk));const Qk="KHR_materials_specular";class jk{constructor(e){this.name=Qk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Um&&this._isExtensionEnabled(i)?(i.metallicReflectanceTexture&&s.push(i.metallicReflectanceTexture),i.reflectanceTexture&&s.push(i.reflectanceTexture),s):s}_isExtensionEnabled(e){return!e.unlit&&(null!=e.metallicF0Factor&&1!=e.metallicF0Factor||null!=e.metallicReflectanceColor&&!e.metallicReflectanceColor.equalsFloats(1,1,1)||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.metallicReflectanceTexture||null!=e.reflectanceTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0,t.extensions=t.extensions||{};const e=this._exporter._glTFMaterialExporter._getTextureInfo(i.metallicReflectanceTexture)??void 0,s=this._exporter._glTFMaterialExporter._getTextureInfo(i.reflectanceTexture)??void 0,r={specularFactor:1==i.metallicF0Factor?void 0:i.metallicF0Factor,specularTexture:e,specularColorFactor:i.metallicReflectanceColor.equalsFloats(1,1,1)?void 0:i.metallicReflectanceColor.asArray(),specularColorTexture:s,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions[Qk]=r}e(t)}))}}Rk.RegisterExtension(Qk,(e=>new jk(e)));const Kk="KHR_materials_volume";class $k{constructor(e){this.name=Kk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Um&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isTranslucencyEnabled)&&(null!=t.maximumThickness&&0!=t.maximumThickness||null!=t.tintColorAtDistance&&t.tintColorAtDistance!=Number.POSITIVE_INFINITY||null!=t.tintColor&&t.tintColor!=Ce.White()||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.subSurface.thicknessTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={thicknessFactor:0==e.maximumThickness?void 0:e.maximumThickness,thicknessTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.thicknessTexture)??void 0,attenuationDistance:e.tintColorAtDistance==Number.POSITIVE_INFINITY?void 0:e.tintColorAtDistance,attenuationColor:e.tintColor.equalsFloats(1,1,1)?void 0:e.tintColor.asArray(),hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[Kk]=s}e(t)}))}}Rk.RegisterExtension(Kk,(e=>new $k(e)));const qk="KHR_materials_dispersion";class Zk{constructor(){this.name=qk,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isDispersionEnabled)}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={dispersion:i.subSurface.dispersion};t.extensions=t.extensions||{},t.extensions[qk]=e}e(t)}))}}Rk.RegisterExtension(qk,(()=>new Zk));const Jk="KHR_materials_transmission";class eV{constructor(e){this.name=Jk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Um&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return t.isRefractionEnabled&&null!=t.refractionIntensity&&0!=t.refractionIntensity||this._hasTexturesExtension(e)}_hasTexturesExtension(e){return null!=e.subSurface.refractionIntensityTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={transmissionFactor:0===e.refractionIntensity?void 0:e.refractionIntensity,transmissionTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.refractionIntensityTexture)??void 0,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[Jk]=s}e(t)}))}}Rk.RegisterExtension(Jk,(e=>new eV(e)));const tV="EXT_mesh_gpu_instancing";class iV{constructor(e){this.name=tV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportNodeAsync(e,t,i,s,r){return new Promise((e=>{if(t&&i instanceof bo&&i.hasThinInstances&&r){this._wasUsed=!0;const e=de.Zero(),s=pe.Identity(),n=de.One(),o=i.thinInstanceGetWorldMatrices(),a=ge.Vector3[2],l=ge.Quaternion[1],h=ge.Vector3[3];let c=!1,u=!1,d=!1;const _=new Float32Array(3*i.thinInstanceCount),p=new Float32Array(4*i.thinInstanceCount),f=new Float32Array(3*i.thinInstanceCount);let m=0;for(const t of o)t.decompose(h,l,a),_.set(a.asArray(),3*m),p.set(l.normalize().asArray(),4*m),f.set(h.asArray(),3*m),c=c||!a.equalsWithEpsilon(e),u=u||!l.equalsWithEpsilon(s),d=d||!h.equalsWithEpsilon(n),m++;const g={attributes:{}};if(c&&(g.attributes.TRANSLATION=this._buildAccessor(_,"VEC3",i.thinInstanceCount,r,5126)),u){const e=5126;g.attributes.ROTATION=this._buildAccessor(p,"VEC4",i.thinInstanceCount,r,e)}d&&(g.attributes.SCALE=this._buildAccessor(f,"VEC3",i.thinInstanceCount,r,5126)),t.extensions=t.extensions||{},t.extensions[tV]=g}e(t)}))}_buildAccessor(e,t,i,s,r){const n=s.getByteOffset();switch(r){case 5126:for(let t=0;t!=e.length;t++)s.setFloat32(e[t]);break;case 5120:for(let t=0;t!=e.length;t++)s.setByte(127*e[t]);break;case 5122:for(let t=0;t!=e.length;t++)s.setInt16(32767*e[t])}const o={buffer:0,byteOffset:n,byteLength:e.length*ys.GetTypeByteLength(r)},a=this._exporter._bufferViews.length;this._exporter._bufferViews.push(o);const l=this._exporter._accessors.length,h={bufferView:a,componentType:r,count:i,type:t,normalized:5120==r||5122==r};return this._exporter._accessors.push(h),l}}Rk.RegisterExtension(tV,(e=>new iV(e)));const sV="KHR_materials_emissive_strength";class rV{constructor(){this.name=sV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(!(i instanceof Um))return e(t);const s=i.emissiveColor.asArray(),r=Math.max(...s);if(r>1){this._wasUsed=!0,t.extensions||(t.extensions={});const e={emissiveStrength:r},s=i.emissiveColor.scale(1/e.emissiveStrength);t.emissiveFactor=s.asArray(),t.extensions[sV]=e}return e(t)}))}}Rk.RegisterExtension(sV,(e=>new rV));class nV{static CreateSTL(e,t=!0,i="stlmesh",s=!1,r=!0,n=!1,o=!1,a=!1){const l=function(e,t,i){const s=[3*e[i],3*e[i+1],3*e[i+2]],r=[new de(t[s[0]],t[s[0]+2],t[s[0]+1]),new de(t[s[1]],t[s[1]+2],t[s[1]+1]),new de(t[s[2]],t[s[2]+2],t[s[2]+1])],n=r[0].subtract(r[1]),o=r[2].subtract(r[1]);return{v:r,n:de.Cross(o,n).normalize()}},h=function(e,t,i,s){return t=c(e,t,i.x,s),t=c(e,t,i.y,s),c(e,t,i.z,s)},c=function(e,t,i,s){return e.setFloat32(t,i,s),t+4},u=function(e){if(o){let t=e;e instanceof To&&(t=e.sourceMesh);const i=t.getVerticesData(ys.PositionKind,!0,!0);if(!i)return[];const s=de.Zero();let r;for(r=0;r"bitbybit-hdrSkyBox"!==e.name&&!e.name.includes("bitbybit-ground")}),Mk.GLBAsync(this.context.scene,e.fileName,t).then((e=>{e.downloadFiles()}))}exportMeshToStl(e){return FV(this,void 0,void 0,(function*(){const t=e.mesh.getChildMeshes();let i=[];t&&t.length>0&&(i=t.filter((e=>!(e instanceof Qu))));let s=[e.mesh,...i];return s=s.filter((e=>e.isVisible)),nV.CreateSTL(s,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}exportMeshesToStl(e){return FV(this,void 0,void 0,(function*(){let t;return e.meshes.forEach((e=>{const i=e.getChildMeshes();let s=[];i&&i.length>0&&(s=i.filter((e=>!(e instanceof Qu)))),t.push(e),s.length>0&&t.push(...s)})),nV.CreateSTL(t,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}loadAsset(e,t,i,s){return FV(this,void 0,void 0,(function*(){const e=yield Pa.ImportMeshAsync("",t,i,this.context.scene),r=this.context.scene.metadata.shadowGenerators,n=new bo("ImportedMeshContainer"+Math.random(),this.context.scene);return r.length>0&&e.meshes.forEach((e=>{if(e.isPickable=!1,s&&(e.isVisible=!1),e.getChildMeshes().forEach((e=>{e.isPickable=!1,s&&(e.isVisible=!1)})),this.context.scene.metadata.shadowGenerators.length>0){try{e.receiveShadows=!0}catch(e){}r.forEach((t=>{t.addShadowCaster(e)})),e.getChildMeshes().forEach((e=>{try{e.receiveShadows=!0}catch(e){}r.forEach((t=>{t.addShadowCaster(e)}))}))}})),e.meshes.forEach((e=>{e.parent=n})),n}))}}!function(e){e.GetAssetDto=class{constructor(e){void 0!==e&&(this.fileName=e)}},e.FileDto=class{constructor(e){void 0!==e&&(this.file=e)}},e.FilesDto=class{constructor(e){void 0!==e&&(this.files=e)}},e.AssetFileDto=class{constructor(e,t){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.hidden=t)}},e.AssetFileByUrlDto=class{constructor(e,t,i){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.rootUrl=t),void 0!==i&&(this.hidden=i)}}}(oV||(oV={})),function(e){e.ArcRotateCameraDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.radius=20,this.target=[0,0,0],this.alpha=45,this.beta=70,this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,this.maxZ=1e3,void 0!==e&&(this.radius=e),void 0!==t&&(this.alpha=t),void 0!==i&&(this.beta=i),void 0!==s&&(this.lowerBetaLimit=s),void 0!==r&&(this.upperBetaLimit=r),void 0!==n&&(this.angularSensibilityX=n),void 0!==o&&(this.angularSensibilityY=o),void 0!==a&&(this.panningSensibility=a),void 0!==l&&(this.wheelPrecision=l),void 0!==h&&(this.maxZ=h)}},e.FreeCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.TargetCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.PositionDto=class{constructor(e,t){this.position=[20,20,20],void 0!==e&&(this.camera=e),void 0!==t&&(this.position=t)}},e.SpeedDto=class{constructor(e,t){this.speed=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.speed=t)}},e.TargetDto=class{constructor(e,t){this.target=[0,0,0],void 0!==e&&(this.camera=e),void 0!==t&&(this.target=t)}},e.MinZDto=class{constructor(e,t){this.minZ=0,void 0!==e&&(this.camera=e),void 0!==t&&(this.minZ=t)}},e.MaxZDto=class{constructor(e,t){this.maxZ=1e3,void 0!==e&&(this.camera=e),void 0!==t&&(this.maxZ=t)}},e.OrthographicDto=class{constructor(e,t,i,s,r){this.orthoLeft=-1,this.orthoRight=1,this.orthoBottom=-1,this.orthoTop=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.orthoLeft=t),void 0!==i&&(this.orthoRight=i),void 0!==s&&(this.orthoTop=s),void 0!==r&&(this.orthoBottom=r)}},e.CameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}}}(aV||(aV={})),function(e){e.ExportSceneGlbDto=class{constructor(e,t){this.fileName="bitbybit-scene",this.discardSkyboxAndGrid=!1,void 0!==e&&(this.fileName=e),void 0!==t&&(this.discardSkyboxAndGrid=t)}},e.ExportSceneDto=class{constructor(e){this.fileName="bitbybit-scene",void 0!==e&&(this.fileName=e)}},e.ExportMeshToStlDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.ExportMeshesToStlDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}}}(lV||(lV={})),function(e){e.PBRMetallicRoughnessDto=class{constructor(e,t,i,s,r,n,o,a){this.name="Custom Material",this.baseColor="#0000ff",this.emissiveColor="#000000",this.metallic=.6,this.roughness=.5,this.alpha=1,this.backFaceCulling=!1,this.zOffset=0,void 0!==e&&(this.name=e),void 0!==t&&(this.baseColor=t),void 0!==i&&(this.emissiveColor=i),void 0!==s&&(this.metallic=s),void 0!==r&&(this.roughness=r),void 0!==n&&(this.alpha=n),void 0!==o&&(this.backFaceCulling=o),void 0!==a&&(this.zOffset=a)}},e.BaseColorDto=class{constructor(e,t){this.baseColor="#0000ff",void 0!==e&&(this.material=e),void 0!==t&&(this.baseColor=t)}},e.MaterialPropDto=class{constructor(e){void 0!==e&&(this.material=e)}},e.MetallicDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.metallic=t)}},e.RoughnessDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.roughness=t)}},e.AlphaDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.alpha=t)}},e.BackFaceCullingDto=class{constructor(e,t){this.backFaceCulling=!0,void 0!==e&&(this.material=e),void 0!==t&&(this.backFaceCulling=t)}},e.BaseTextureDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.baseTexture=t)}}}(hV||(hV={})),function(e){let t;!function(e){e.frontside="frontside",e.backside="backside",e.doubleside="doubleside"}(t=e.sideOrientationEnum||(e.sideOrientationEnum={})),e.UpdateDrawnBabylonMesh=class{constructor(e,t,i,s,r){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.scaling=s),void 0!==r&&(this.colours=r)}},e.SetParentDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.parentMesh=t)}},e.UpdateDrawnBabylonMeshPositionDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t)}},e.UpdateDrawnBabylonMeshRotationDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotation=t)}},e.UpdateDrawnBabylonMeshScaleDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.scale=t)}},e.IntersectsMeshDto=class{constructor(e,t,i,s){this.precise=!1,this.includeDescendants=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.babylonMesh2=t),void 0!==i&&(this.precise=i),void 0!==s&&(this.includeDescendants=s)}},e.IntersectsPointDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.point=t)}},e.BabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ShowHideMeshDto=class{constructor(e,t){this.includeChildren=!0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.includeChildren=t)}},e.CloneBabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ChildMeshesBabylonMeshDto=class{constructor(e,t){this.directDescendantsOnly=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.directDescendantsOnly=t)}},e.TranslateBabylonMeshDto=class{constructor(e,t){this.distance=0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.distance=t)}},e.NameBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.name=t),void 0!==i&&(this.includeChildren=i)}},e.ByNameBabylonMeshDto=class{constructor(e){void 0!==e&&(this.name=e)}},e.MaterialBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.material=t),void 0!==i&&(this.includeChildren=i)}},e.IdBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.id=t)}},e.ByIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.id=e)}},e.UniqueIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.uniqueId=e)}},e.PickableBabylonMeshDto=class{constructor(e,t,i){this.pickable=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.pickable=t),void 0!==i&&(this.includeChildren=i)}},e.CheckCollisionsBabylonMeshDto=class{constructor(e,t,i){this.checkCollisions=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.checkCollisions=t),void 0!==i&&(this.includeChildren=i)}},e.RotateBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotate=t)}},e.SetMeshVisibilityDto=class{constructor(e,t,i){this.visibility=0,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.visibility=t),void 0!==i&&(this.includeChildren=i)}},e.MeshInstanceAndTransformDto=class{constructor(e,t,i,s){void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.scaling=s)}},e.MeshInstanceDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,s){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}}}(cV||(cV={})),function(e){e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.PickInfo=class{constructor(e){void 0!==e&&(this.pickInfo=e)}}}(uV||(uV={})),function(e){e.BaseRayDto=class{constructor(e,t,i){void 0!==e&&(this.origin=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.length=i)}},e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.FromToDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.to=t)}}}(dV||(dV={})),function(e){e.CreateBoxDto=class{constructor(e,t,i,s){this.width=1,this.depth=1,this.height=1,this.sideOrientation=cV.sideOrientationEnum.frontside,void 0!==e&&(this.width=e),void 0!==t&&(this.depth=t),void 0!==i&&(this.height=i),void 0!==s&&(this.sideOrientation=s)}},e.CreateCubeDto=class{constructor(e,t){this.size=1,this.sideOrientation=cV.sideOrientationEnum.frontside,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t)}},e.CreateSquarePlaneDto=class{constructor(e,t){this.size=1,this.sideOrientation=cV.sideOrientationEnum.frontside,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t)}},e.CreateRectanglePlaneDto=class{constructor(e,t,i){this.width=1,this.height=1,this.sideOrientation=cV.sideOrientationEnum.frontside,void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.sideOrientation=i)}}}(_V||(_V={})),function(e){let t;!function(e){e.nearest="nearest",e.bilinear="bilinear",e.trilinear="trilinear"}(t=e.samplingModeEnum||(e.samplingModeEnum={})),e.TextureSimpleDto=class{constructor(t,i,s,r,n,o,a,l,h,c){this.name="Custom Texture",this.invertY=!1,this.invertZ=!1,this.wAng=0,this.uScale=1,this.vScale=1,this.uOffset=0,this.vOffset=0,this.samplingMode=e.samplingModeEnum.nearest,void 0!==t&&(this.name=t),void 0!==i&&(this.url=i),void 0!==s&&(this.invertY=s),void 0!==r&&(this.invertZ=r),void 0!==n&&(this.wAng=n),void 0!==o&&(this.uScale=o),void 0!==a&&(this.vScale=a),void 0!==l&&(this.uOffset=l),void 0!==h&&(this.vOffset=h),void 0!==c&&(this.samplingMode=c)}}}(pV||(pV={})),function(e){e.DefaultWebXRWithTeleportationDto=class{constructor(e){void 0!==e&&(this.groundMeshes=e)}}}(fV||(fV={})),function(e){e.HexDto=class{constructor(e){this.color="#0000ff",void 0!==e&&(this.color=e)}},e.HexDtoMapped=class{constructor(e,t,i){this.color="#0000ff",this.from=0,this.to=255,void 0!==e&&(this.color=e),void 0!==t&&(this.from=t),void 0!==i&&(this.to=i)}},e.RGBDto=class{constructor(e,t,i){this.r=255,this.g=255,this.b=255,void 0!==e&&(this.r=e),void 0!==t&&(this.g=t),void 0!==i&&(this.b=i)}},e.RGBObjectDto=class{constructor(e){void 0!==e&&(this.rgb=e)}}}(mV||(mV={})),function(e){let t;e.DrawAny=class{constructor(e,t,i){void 0!==e&&(this.entity=e),void 0!==t&&(this.options=t),void 0!==i&&(this.babylonMesh=i)}},e.SceneDrawGridMeshDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.width=400,this.height=400,this.subdivisions=10,this.majorUnitFrequency=10,this.minorUnitVisibility=.45,this.gridRatio=.5,this.opacity=.5,this.backFaceCulling=!1,this.mainColor="#ffffff",this.secondaryColor="#ffffff",void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.subdivisions=i),void 0!==s&&(this.majorUnitFrequency=s),void 0!==r&&(this.minorUnitVisibility=r),void 0!==n&&(this.gridRatio=n),void 0!==o&&(this.opacity=o),void 0!==a&&(this.backFaceCulling=a),void 0!==l&&(this.mainColor=l),void 0!==h&&(this.secondaryColor=h)}},e.DrawBasicGeometryOptions=class{constructor(e,t,i,s,r){this.colours="#ff0000",this.size=.1,this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.colours=e),void 0!==t&&(this.size=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r)}},e.DrawNodeOptions=class{constructor(e,t,i,s){this.colorX="#0000ff",this.colorY="#00ff00",this.colorZ="#ff0000",this.size=2,void 0!==e&&(this.colorX=e),void 0!==t&&(this.colorY=t),void 0!==i&&(this.colorZ=i),void 0!==s&&(this.size=s)}},e.DrawOcctShapeOptions=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.vertexColour="#ffaaff",this.edgeWidth=2,this.vertexSize=.03,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.faceOpacity=e),void 0!==t&&(this.edgeOpacity=t),void 0!==i&&(this.edgeColour=i),void 0!==s&&(this.faceMaterial=s),void 0!==r&&(this.faceColour=r),void 0!==h&&(this.vertexColour=h),void 0!==c&&(this.vertexSize=c),void 0!==n&&(this.edgeWidth=n),void 0!==o&&(this.drawEdges=o),void 0!==a&&(this.drawFaces=a),void 0!==l&&(this.drawVertices=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdgeIndexes=d),void 0!==_&&(this.edgeIndexHeight=_),void 0!==p&&(this.edgeIndexColour=p),void 0!==f&&(this.drawFaceIndexes=f),void 0!==m&&(this.faceIndexHeight=m),void 0!==g&&(this.faceIndexColour=g)}},e.DrawOcctShapeSimpleOptions=class{constructor(e,t,i,s,r,n){this.precision=.01,this.drawFaces=!0,this.faceColour="#ff0000",this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.drawFaces=t),void 0!==i&&(this.faceColour=i),void 0!==s&&(this.drawEdges=s),void 0!==r&&(this.edgeColour=r),void 0!==n&&(this.edgeWidth=n)}},e.DrawOcctShapeMaterialOptions=class{constructor(e,t,i,s,r){this.precision=.01,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.faceMaterial=t),void 0!==i&&(this.drawEdges=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.edgeWidth=r)}},function(e){e[e.point=0]="point",e[e.points=1]="points",e[e.line=2]="line",e[e.lines=3]="lines",e[e.node=4]="node",e[e.nodes=5]="nodes",e[e.polyline=6]="polyline",e[e.polylines=7]="polylines",e[e.verbCurve=8]="verbCurve",e[e.verbCurves=9]="verbCurves",e[e.verbSurface=10]="verbSurface",e[e.verbSurfaces=11]="verbSurfaces",e[e.jscadMesh=12]="jscadMesh",e[e.jscadMeshes=13]="jscadMeshes",e[e.occt=14]="occt",e[e.tag=15]="tag",e[e.tags=16]="tags"}(t=e.drawingTypes||(e.drawingTypes={}))}(gV||(gV={})),function(e){let t,i;!function(e){e.edge="edge",e.round="round",e.chamfer="chamfer"}(t=e.solidCornerTypeEnum||(e.solidCornerTypeEnum={})),function(e){e.left="left",e.center="center",e.right="right"}(i=e.jscadTextAlignEnum||(e.jscadTextAlignEnum={})),e.DrawSolidMeshDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.mesh=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawSolidMeshesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.meshes=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawPathDto=class{constructor(e,t,i,s,r,n){this.colour="#444444",this.opacity=1,this.width=10,this.updatable=!1,void 0!==e&&(this.path=e),void 0!==t&&(this.colour=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.width=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pathMesh=n)}},e.TransformSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.transformation=t)}},e.TransformSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.DownloadSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.DownloadGeometryDto=class{constructor(e,t){void 0!==e&&(this.geometry=e),void 0!==t&&(this.fileName=t)}},e.DownloadSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}},e.ColorizeDto=class{constructor(e,t){this.color="#0000ff",void 0!==e&&(this.geometry=e),void 0!==t&&(this.color=t)}},e.BooleanObjectsDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.BooleanTwoObjectsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.BooleanObjectsFromDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.meshes=t)}},e.ExpansionDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.OffsetDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.ExtrudeLinearDto=class{constructor(e,t,i,s){this.height=1,this.twistAngle=90,this.twistSteps=15,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.twistAngle=i),void 0!==s&&(this.twistSteps=s)}},e.HullDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.ExtrudeRectangularDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRectangularPointsDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.points=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRotateDto=class{constructor(e,t,i,s){this.angle=90,this.startAngle=0,this.segments=24,void 0!==e&&(this.polygon=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.startAngle=i),void 0!==s&&(this.segments=s)}},e.PathDto=class{constructor(e){void 0!==e&&(this.path=e)}},e.PathFromPointsDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.PathsFromPointsDto=class{constructor(e){void 0!==e&&(this.pointsLists=e)}},e.PathFromPolylineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.closed=t)}},e.PathAppendCurveDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.path=t)}},e.PathAppendPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.path=t)}},e.PathAppendPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.path=t)}},e.PathAppendArcDto=class{constructor(e,t,i,s,r,n,o,a){this.endPoint=[1,1],this.xAxisRotation=90,this.clockwise=!0,this.large=!1,this.segments=24,this.radiusX=1,this.radiusY=1,void 0!==e&&(this.path=e),void 0!==t&&(this.endPoint=t),void 0!==i&&(this.xAxisRotation=i),void 0!==s&&(this.clockwise=s),void 0!==r&&(this.large=r),void 0!==n&&(this.segments=n),void 0!==o&&(this.radiusX=o),void 0!==a&&(this.radiusY=a)}},e.CircleDto=class{constructor(e,t,i){this.center=[0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipseDto=class{constructor(e,t,i){this.center=[0,0],this.radius=[1,2],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SquareDto=class{constructor(e,t){this.center=[0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.RectangleDto=class{constructor(e,t,i){this.center=[0,0],this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i)}},e.RoundedRectangleDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.roundRadius=.2,this.segments=24,this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.segments=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r)}},e.StarDto=class{constructor(e,t,i,s,r,n){this.center=[0,0],this.vertices=10,this.density=1,this.outerRadius=2,this.innerRadius=1,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.vertices=t),void 0!==i&&(this.density=i),void 0!==s&&(this.outerRadius=s),void 0!==r&&(this.innerRadius=r),void 0!==n&&(this.startAngle=n)}},e.CubeDto=class{constructor(e,t){this.center=[0,0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CubeCentersDto=class{constructor(e,t){this.size=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.size=t)}},e.CuboidDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.width=1,this.length=1,this.height=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.CuboidCentersDto=class{constructor(e,t,i,s){this.width=1,this.length=1,this.height=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.RoundedCuboidDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.roundRadius=1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.RoundedCuboidCentersDto=class{constructor(e,t,i,s,r,n){this.roundRadius=.1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.CylidnerEllipticDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerCentersEllipticDto=class{constructor(e,t,i,s,r){this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.EllipsoidDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipsoidCentersDto=class{constructor(e,t,i){this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.GeodesicSphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.frequency=12,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.GeodesicSphereCentersDto=class{constructor(e,t,i){this.radius=1,this.frequency=12,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.CylidnerCentersDto=class{constructor(e,t,i,s){this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerCentersDto=class{constructor(e,t,i,s,r){this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.SphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SphereCentersDto=class{constructor(e,t,i){this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.TorusDto=class{constructor(e,t,i,s,r,n,o,a){this.center=[0,0,0],this.innerRadius=1,this.outerRadius=2,this.innerSegments=24,this.outerSegments=24,this.innerRotation=0,this.outerRotation=360,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.outerRadius=i),void 0!==s&&(this.innerSegments=s),void 0!==r&&(this.outerSegments=r),void 0!==n&&(this.innerRotation=n),void 0!==o&&(this.outerRotation=o),void 0!==a&&(this.startAngle=a)}},e.TextDto=class{constructor(e,t,s,r,n,o,a,l,h){this.text="Hello World",this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.segments=t),void 0!==s&&(this.xOffset=s),void 0!==r&&(this.yOffset=r),void 0!==n&&(this.height=n),void 0!==o&&(this.lineSpacing=o),void 0!==a&&(this.letterSpacing=a),void 0!==l&&(this.align=l),void 0!==h&&(this.extrudeOffset=h)}},e.CylinderTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c,u){this.text="Hello World",this.extrusionHeight=.5,this.extrusionSize=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.extrusionHeight=t),void 0!==s&&(this.extrusionSize=s),void 0!==r&&(this.segments=r),void 0!==n&&(this.xOffset=n),void 0!==o&&(this.yOffset=o),void 0!==a&&(this.height=a),void 0!==l&&(this.lineSpacing=l),void 0!==h&&(this.letterSpacing=h),void 0!==c&&(this.align=c),void 0!==u&&(this.extrudeOffset=u)}},e.SphereTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c){this.text="Hello World",this.radius=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.radius=t),void 0!==s&&(this.segments=s),void 0!==r&&(this.xOffset=r),void 0!==n&&(this.yOffset=n),void 0!==o&&(this.height=o),void 0!==a&&(this.lineSpacing=a),void 0!==l&&(this.letterSpacing=l),void 0!==h&&(this.align=h),void 0!==c&&(this.extrudeOffset=c)}},e.FromPolygonPoints=class{constructor(e){void 0!==e&&(this.polygonPoints=e)}}}(vV||(vV={})),function(e){e.StringifyDto=class{constructor(e){void 0!==e&&(this.json=e)}},e.ParseDto=class{constructor(e){void 0!==e&&(this.text=e)}},e.QueryDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.SetValueDto=class{constructor(e,t,i){void 0!==e&&(this.json=e),void 0!==t&&(this.value=t),void 0!==i&&(this.path=i)}},e.SetValuesOnPathsDto=class{constructor(e,t,i){void 0!==e&&(this.json=e),void 0!==t&&(this.values=t),void 0!==i&&(this.paths=i)}},e.PathsDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.JsonDto=class{constructor(e){void 0!==e&&(this.json=e)}}}(xV||(xV={})),function(e){e.LinePointsDto=class{constructor(e,t){void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LineStartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoints=e),void 0!==t&&(this.endPoints=t)}},e.DrawLineDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.line=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.lineMesh=n)}},e.DrawLinesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.linesMesh=n)}},e.PointsLinesDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.LineDto=class{constructor(e){void 0!==e&&(this.line=e)}},e.LinesDto=class{constructor(e){void 0!==e&&(this.lines=e)}},e.PointOnLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.param=t)}},e.TransformLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.transformation=t)}},e.TransformsLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}},e.TransformLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}}}(bV||(bV={})),function(e){let t;!function(e){e.first="first",e.last="last"}(t=e.firstLastEnum||(e.firstLastEnum={})),e.ListItemDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.SubListDto=class{constructor(e,t,i,s){this.indexStart=0,this.indexEnd=1,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.indexStart=t),void 0!==i&&(this.indexEnd=i),void 0!==s&&(this.clone=s)}},e.ListDto=class{constructor(e,t){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t)}},e.GroupListDto=class{constructor(e,t,i){this.nrElements=2,this.keepRemainder=!1,void 0!==e&&(this.list=e),void 0!==t&&(this.nrElements=t),void 0!==i&&(this.keepRemainder=i)}},e.MultiplyItemDto=class{constructor(e,t){void 0!==e&&(this.item=e),void 0!==t&&(this.times=t)}},e.AddItemAtIndexDto=class{constructor(e,t,i,s){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.index=i),void 0!==s&&(this.clone=s)}},e.AddItemAtIndexesDto=class{constructor(e,t,i,s){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.indexes=i),void 0!==s&&(this.clone=s)}},e.AddItemsAtIndexesDto=class{constructor(e,t,i,s){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.items=t),void 0!==i&&(this.indexes=i),void 0!==s&&(this.clone=s)}},e.RemoveItemAtIndexDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.RemoveNthItemDto=class{constructor(e,t,i,s){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==s&&(this.clone=s)}},e.GetByPatternDto=class{constructor(e,t){this.pattern=[!0,!0,!1],void 0!==e&&(this.list=e),void 0!==t&&(this.pattern=t)}},e.GetNthItemDto=class{constructor(e,t,i,s){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==s&&(this.clone=s)}},e.GetLongestListLength=class{constructor(e){void 0!==e&&(this.lists=e)}},e.MergeElementsOfLists=class{constructor(e,t){this.level=0,void 0!==e&&(this.lists=e),void 0!==t&&(this.level=t)}},e.AddItemFirstLastDto=class{constructor(e,i,s,r){this.position=t.last,this.clone=!0,void 0!==e&&(this.list=e),void 0!==i&&(this.item=i),void 0!==s&&(this.position=s),void 0!==r&&(this.clone=r)}}}(TV||(TV={})),function(e){let t;!function(e){e.less="<",e.lessOrEqual="<=",e.greater=">",e.greaterOrEqual=">=",e.tripleEqual="===",e.tripleNotEqual="!==",e.equal="==",e.notEqual="!="}(t=e.BooleanOperatorsEnum||(e.BooleanOperatorsEnum={})),e.ComparisonDto=class{constructor(e,t,i){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operator=i)}},e.BooleanDto=class{constructor(e){this.boolean=!1,void 0!==e&&(this.boolean=e)}},e.BooleanListDto=class{constructor(e){void 0!==e&&(this.booleans=e)}},e.ValueGateDto=class{constructor(e,t){this.boolean=!1,void 0!==e&&(this.value=e),void 0!==t&&(this.boolean=t)}},e.TwoValueGateDto=class{constructor(e,t){void 0!==e&&(this.value1=e),void 0!==t&&(this.value2=t)}},e.RandomBooleansDto=class{constructor(e){this.length=10,void 0!==e&&(this.length=e)}},e.TwoThresholdRandomGradientDto=class{},e.ThresholdBooleanListDto=class{},e.ThresholdGapsBooleanListDto=class{}}(yV||(yV={})),function(e){let t,i;!function(e){e.add="add",e.subtract="subtract",e.multiply="multiply",e.divide="divide",e.power="power",e.modulus="modulus"}(t=e.mathTwoNrOperatorEnum||(e.mathTwoNrOperatorEnum={})),function(e){e.absolute="absolute",e.negate="negate",e.ln="ln",e.log10="log10",e.tenPow="tenPow",e.round="round",e.floor="floor",e.ceil="ceil",e.sqrt="sqrt",e.sin="sin",e.cos="cos",e.tan="tan",e.asin="asin",e.acos="acos",e.atan="atan",e.log="log",e.exp="exp",e.radToDeg="radToDeg",e.degToRad="degToRad"}(i=e.mathOneNrOperatorEnum||(e.mathOneNrOperatorEnum={})),e.NumberDto=class{constructor(e){this.number=0,void 0!==e&&(this.number=e)}},e.ModulusDto=class{constructor(e,t){this.number=1,this.modulus=2,void 0!==e&&(this.number=e),void 0!==t&&(this.modulus=t)}},e.RoundToDecimalsDto=class{constructor(e,t){this.number=1.123456,this.decimalPlaces=2,void 0!==e&&(this.number=e),void 0!==t&&(this.decimalPlaces=t)}},e.ActionOnTwoNumbersDto=class{constructor(e,t,i){this.first=1,this.second=1,void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operation=i)}},e.ActionOnOneNumberDto=class{constructor(e,t){this.number=1,void 0!==e&&(this.number=e),void 0!==t&&(this.operation=t)}},e.RemapNumberDto=class{constructor(e,t,i,s,r){this.number=.5,this.fromLow=0,this.fromHigh=1,this.toLow=1,this.toHigh=2,void 0!==e&&(this.number=e),void 0!==t&&(this.fromLow=t),void 0!==i&&(this.fromHigh=i),void 0!==s&&(this.toLow=s),void 0!==r&&(this.toHigh=r)}},e.RandomNumberDto=class{constructor(e,t){this.low=0,this.high=1,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t)}},e.RandomNumbersDto=class{constructor(e,t,i){this.low=0,this.high=1,this.count=10,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t),void 0!==i&&(this.count=i)}}}(SV||(SV={})),function(e){e.NodeDto=class{constructor(e){void 0!==e&&(this.node=e)}},e.NodeTranslationDto=class{constructor(e,t,i){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.distance=i)}},e.NodeParentDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.parentNode=t)}},e.NodeDirectionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t)}},e.NodePositionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.position=t)}},e.RotateNodeDto=class{constructor(e,t,i){this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,s){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}},e.CreateNodeFromRotationDto=class{constructor(e,t,i){this.origin=[0,0,0],this.rotation=[0,0,0],void 0!==e&&(this.parent=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.rotation=i)}},e.DrawNodeDto=class{constructor(e,t,i,s,r){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.node=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==s&&(this.colorZ=s),void 0!==r&&(this.size=r)}},e.DrawNodesDto=class{constructor(e,t,i,s,r){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.nodes=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==s&&(this.colorZ=s),void 0!==r&&(this.size=r)}}}(CV||(CV={})),function(e){e.PointDto=class{constructor(e){void 0!==e&&(this.point=e)}},e.PointXYZDto=class{constructor(e,t,i){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.PointXYDto=class{constructor(e,t){this.x=0,this.y=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.DrawPointDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.size=3,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.point=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==s&&(this.colours=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pointMesh=n)}},e.DrawPointsDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.size=.1,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==s&&(this.colours=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pointsMesh=n)}},e.TransformPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.transformation=t)}},e.TransformPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.TransformsForPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.ClosestPointFromPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.point=t)}},e.StartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoint=t)}},e.StartEndPointsListDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoints=t)}},e.MultiplyPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.amountOfPoints=t)}},e.SpiralDto=class{constructor(e,t,i,s,r){this.phi=.9,this.numberPoints=200,this.widening=3,this.radius=6,this.factor=1,void 0!==e&&(this.radius=e),void 0!==t&&(this.numberPoints=t),void 0!==i&&(this.widening=i),void 0!==s&&(this.factor=s),void 0!==r&&(this.phi=r)}},e.HexGridCentersDto=class{constructor(e,t,i,s,r){this.nrHexagonsY=21,this.nrHexagonsX=21,this.orientOnCenter=!1,this.pointsOnGround=!1,void 0!==e&&(this.nrHexagonsX=e),void 0!==t&&(this.nrHexagonsY=t),void 0!==i&&(this.radiusHexagon=i),void 0!==s&&(this.orientOnCenter=s),void 0!==r&&(this.pointsOnGround=r)}}}(EV||(EV={})),function(e){e.PolylinePropertiesDto=class{constructor(e,t){this.isClosed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.isClosed=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.polyline=e)}},e.PolylinesDto=class{constructor(e){void 0!==e&&(this.polylines=e)}},e.TransformPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.transformation=t)}},e.DrawPolylineDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.polylineMesh=n)}},e.DrawPolylinesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.polylinesMesh=n)}}}(AV||(AV={})),function(e){let t,i;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={})),function(e){e.none="none",e.exponential="exponential",e.exponentialSquared="exponentialSquared",e.linear="linear"}(i=e.fogModeEnum||(e.fogModeEnum={}))}(PV||(PV={})),function(e){e.SceneBackgroundColourDto=class{constructor(e){this.colour="#ffffff",void 0!==e&&(this.colour=e)}},e.SceneDto=class{constructor(e){void 0!==e&&(this.scene=e)}},e.EnablePhysicsDto=class{constructor(e){this.vector=[0,-9.81,0],void 0!==e&&(this.vector=e)}},e.PointLightDto=class{constructor(e,t,i,s,r,n,o,a){this.position=[0,0,0],this.intensity=2e3,this.diffuse="#ffffff",this.specular="#ffffff",this.radius=.1,this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,void 0!==e&&(this.position=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==s&&(this.specular=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.shadowGeneratorMapSize=n),void 0!==o&&(this.enableShadows=o),void 0!==a&&(this.shadowDarkness=a)}},e.ActiveCameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}},e.UseRightHandedSystemDto=class{constructor(e){this.use=!0,void 0!==e&&(this.use=e)}},e.DirectionalLightDto=class{constructor(e,t,i,s,r,n,o){this.direction=[-100,-100,-100],this.intensity=.5,this.diffuse="#ffffff",this.specular="#ffffff",this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,void 0!==e&&(this.direction=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==s&&(this.specular=s),void 0!==r&&(this.shadowGeneratorMapSize=r),void 0!==n&&(this.enableShadows=n),void 0!==o&&(this.shadowDarkness=o)}},e.CameraConfigurationDto=class{constructor(e,t,i,s,r,n,o,a,l){this.position=[10,10,10],this.lookAt=[0,0,0],this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.maxZ=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,void 0!==e&&(this.position=e),void 0!==t&&(this.lookAt=t),void 0!==i&&(this.lowerBetaLimit=i),void 0!==s&&(this.upperBetaLimit=s),void 0!==r&&(this.angularSensibilityX=r),void 0!==n&&(this.angularSensibilityY=n),void 0!==o&&(this.maxZ=o),void 0!==a&&(this.panningSensibility=a),void 0!==l&&(this.wheelPrecision=l)}},e.SkyboxDto=class{constructor(e,t,i,s){this.skybox=PV.skyboxEnum.clearSky,this.size=1e3,this.blur=.1,this.environmentIntensity=.7,void 0!==e&&(this.skybox=e),void 0!==t&&(this.size=t),void 0!==i&&(this.blur=i),void 0!==s&&(this.environmentIntensity=s)}},e.PointerDto=class{},e.FogDto=class{constructor(e,t,i,s,r){this.color="#ffffff",this.density=.1,void 0!==e&&(this.mode=e),void 0!==t&&(this.color=t),void 0!==i&&(this.density=i),void 0!==s&&(this.start=s),void 0!==r&&(this.end=r)}}}(RV||(RV={})),function(e){e.DrawTagDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tag=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagVariable=i)}},e.DrawTagsDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tags=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagsVariable=i)}},e.TagDto=class{constructor(e,t,i,s,r,n,o){this.position=[0,0,0],this.colour="#444444",this.size=12,this.adaptDepth=!1,void 0!==e&&(this.text=e),void 0!==t&&(this.position=t),void 0!==i&&(this.colour=i),void 0!==s&&(this.size=s),void 0!==r&&(this.adaptDepth=r),void 0!==n&&(this.needsUpdate=n),void 0!==o&&(this.id=o)}}}(IV||(IV={})),function(e){e.TextDto=class{constructor(e){this.text="Hello World",void 0!==e&&(this.text=e)}},e.TextSplitDto=class{constructor(e,t){this.text="a,b,c",this.separator=",",void 0!==e&&(this.text=e),void 0!==t&&(this.separator=t)}},e.TextReplaceDto=class{constructor(e,t,i){this.text="a-c",this.search="-",this.replaceWith="b",void 0!==e&&(this.text=e),void 0!==t&&(this.search=t),void 0!==i&&(this.replaceWith=i)}},e.TextJoinDto=class{constructor(e,t){this.separator=",",void 0!==e&&(this.list=e),void 0!==t&&(this.separator=t)}},e.ToStringDto=class{constructor(e){void 0!==e&&(this.item=e)}},e.ToStringEachDto=class{constructor(e){void 0!==e&&(this.list=e)}}}(MV||(MV={})),function(e){e.PostFromIframe=class{constructor(e,t){void 0!==e&&(this.data=e),void 0!==t&&(this.targetOrigin=t)}}}(OV||(OV={})),function(e){e.RotationCenterAxisDto=class{constructor(e,t,i){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.center=i)}},e.TransformBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.RotationCenterDto=class{constructor(e,t){this.angle=90,this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.center=t)}},e.RotationCenterYawPitchRollDto=class{constructor(e,t,i,s){this.yaw=0,this.pitch=0,this.roll=0,this.center=[0,0,0],void 0!==e&&(this.yaw=e),void 0!==t&&(this.pitch=t),void 0!==i&&(this.roll=i),void 0!==s&&(this.center=s)}},e.ScaleXYZDto=class{constructor(e){this.scaleXyz=[1,1,1],void 0!==e&&(this.scaleXyz=e)}},e.ScaleCenterXYZDto=class{constructor(e,t){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.center=e),void 0!==t&&(this.scaleXyz=t)}},e.UniformScaleDto=class{constructor(e){this.scale=1,void 0!==e&&(this.scale=e)}},e.UniformScaleFromCenterDto=class{constructor(e,t){this.scale=1,this.center=[0,0,0],void 0!==e&&(this.scale=e),void 0!==t&&(this.center=t)}},e.TranslationXYZDto=class{constructor(e){this.translation=[0,0,0],void 0!==e&&(this.translation=e)}},e.TranslationsXYZDto=class{constructor(e){void 0!==e&&(this.translations=e)}}}(DV||(DV={})),function(e){e.TwoVectorsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.VectorBoolDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.VectorDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.RangeMaxDto=class{constructor(e){void 0!==e&&(this.max=e)}},e.VectorXYZDto=class{constructor(e,t,i){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.VectorXYDto=class{constructor(e,t){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.SpanDto=class{constructor(e,t,i){this.step=.1,this.min=0,this.max=1,void 0!==e&&(this.step=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i)}},e.RayPointDto=class{constructor(e,t,i){void 0!==e&&(this.point=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.vector=i)}},e.VectorsDto=class{constructor(e){void 0!==e&&(this.vectors=e)}},e.FractionTwoVectorsDto=class{constructor(e,t,i){this.fraction=.5,void 0!==e&&(this.fraction=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}},e.VectorScalarDto=class{constructor(e,t){void 0!==e&&(this.scalar=e),void 0!==t&&(this.vector=t)}},e.TwoVectorsReferenceDto=class{constructor(e,t,i){void 0!==e&&(this.reference=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}}}(wV||(wV={})),function(e){e.CurveDto=class{constructor(e){void 0!==e&&(this.curve=e)}},e.CurvesDto=class{constructor(e){void 0!==e&&(this.curves=e)}},e.ClosestPointDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.point=t)}},e.ClosestPointsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.points=t)}},e.BezierCurveDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t)}},e.DrawCurveDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curve=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.curveMesh=n)}},e.CurveParameterDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t)}},e.CurvesParameterDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.parameter=t)}},e.CurveTransformDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.transformation=t)}},e.CurvesTransformDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.transformation=t)}},e.CurveToleranceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.tolerance=t)}},e.CurveLengthToleranceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t),void 0!==i&&(this.tolerance=i)}},e.CurveDerivativesDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.numDerivatives=i)}},e.CurveSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.subdivision=t)}},e.CurvesSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.subdivision=t)}},e.CurvesDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.length=t)}},e.CurveDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t)}},e.DrawCurvesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curves=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.curvesMesh=n)}},e.CurveNurbsDataDto=class{constructor(e,t,i,s){void 0!==e&&(this.degree=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.knots=i),void 0!==s&&(this.points=s)}},e.CurvePathDataDto=class{constructor(e,t){void 0!==e&&(this.degree=e),void 0!==t&&(this.points=t)}},e.EllipseDto=class{constructor(e){void 0!==e&&(this.ellipse=e)}},e.CircleDto=class{constructor(e){void 0!==e&&(this.circle=e)}},e.ArcDto=class{constructor(e){void 0!==e&&(this.arc=e)}},e.EllipseParametersDto=class{constructor(e,t,i){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.center=i)}},e.CircleParametersDto=class{constructor(e,t,i,s){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.center=s)}},e.ArcParametersDto=class{constructor(e,t,i,s,r,n){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==s&&(this.yAxis=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.center=n)}},e.EllipseArcParametersDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==s&&(this.yAxis=s),void 0!==r&&(this.center=r)}},e.SurfaceDto=class{constructor(e){void 0!==e&&(this.surface=e)}},e.SurfaceTransformDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.transformation=t)}},e.SurfaceParameterDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.useV=i)}},e.IsocurvesParametersDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameters=t),void 0!==i&&(this.useV=i)}},e.IsocurveSubdivisionDto=class{constructor(e,t,i,s,r){this.useV=!1,this.includeLast=!0,this.includeFirst=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.useV=t),void 0!==i&&(this.includeLast=i),void 0!==s&&(this.includeFirst=s),void 0!==r&&(this.isocurveSegments=r)}},e.DerivativesDto=class{constructor(e,t,i,s){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i),void 0!==s&&(this.numDerivatives=s)}},e.SurfaceLocationDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i)}},e.CornersDto=class{constructor(e,t,i,s){void 0!==e&&(this.point1=e),void 0!==t&&(this.point2=t),void 0!==i&&(this.point3=i),void 0!==s&&(this.point4=s)}},e.SurfaceParamDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.point=t)}},e.KnotsControlPointsWeightsDto=class{constructor(e,t,i,s,r,n){void 0!==e&&(this.degreeU=e),void 0!==t&&(this.degreeV=t),void 0!==i&&(this.knotsU=i),void 0!==s&&(this.knotsV=s),void 0!==r&&(this.points=r),void 0!==n&&(this.weights=n)}},e.LoftCurvesDto=class{constructor(e,t){void 0!==e&&(this.degreeV=e),void 0!==t&&(this.curves=t)}},e.DrawSurfaceDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surface=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfaceMesh=n)}},e.DrawSurfacesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfacesMesh=n)}},e.DrawSurfacesColoursDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.colours=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfacesMesh=n)}},e.ConeAndCylinderParametersDto=class{constructor(e,t,i,s,r){this.axis=[0,1,0],this.xAxis=[1,0,0],this.base=[0,0,0],this.height=2,this.radius=1,void 0!==e&&(this.axis=e),void 0!==t&&(this.xAxis=t),void 0!==i&&(this.base=i),void 0!==s&&(this.height=s),void 0!==r&&(this.radius=r)}},e.ConeDto=class{constructor(e){void 0!==e&&(this.cone=e)}},e.CylinderDto=class{constructor(e){void 0!==e&&(this.cylinder=e)}},e.ExtrusionParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.direction=t)}},e.ExtrusionDto=class{constructor(e){void 0!==e&&(this.extrusion=e)}},e.SphericalParametersDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.SphereDto=class{constructor(e){void 0!==e&&(this.sphere=e)}},e.RevolutionParametersDto=class{constructor(e,t,i,s){void 0!==e&&(this.profile=e),void 0!==t&&(this.center=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}},e.RevolutionDto=class{constructor(e){void 0!==e&&(this.revolution=e)}},e.SweepParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.rail=t)}},e.SweepDto=class{constructor(e){void 0!==e&&(this.sweep=e)}},e.CurveCurveDto=class{constructor(e,t,i){void 0!==e&&(this.firstCurve=e),void 0!==t&&(this.secondCurve=t),void 0!==i&&(this.tolerance=i)}},e.CurveSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t),void 0!==i&&(this.tolerance=i)}},e.SurfaceSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.firstSurface=e),void 0!==t&&(this.secondSurface=t),void 0!==i&&(this.tolerance=i)}},e.CurveCurveIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}},e.CurveSurfaceIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}}}(NV||(NV={}));class LV{constructor(e){this.context=e}dispose(e){e.babylonMesh&&(e.babylonMesh.getScene().removeMesh(e.babylonMesh,!0),e.babylonMesh.dispose())}updateDrawn(e){const t=e.babylonMesh.metadata.type;e.babylonMesh.position=new de(e.position[0],e.position[1],e.position[2]),e.babylonMesh.rotation=new de(e.rotation[0],e.rotation[1],e.rotation[2]),e.babylonMesh.scaling=new de(e.scaling[0],e.scaling[1],e.scaling[2]);const i=Array.isArray(e.colours);let s;if(e.babylonMesh.getChildMeshes&&(s=e.babylonMesh.getChildMeshes()),s&&s.length>0)i&&e.colours.length===s.length?s.forEach(((t,i)=>{const s=Ce.FromHexString(e.colours[i]);this.assignColorToMesh(t,s)})):i?s.forEach((t=>{const i=Ce.FromHexString(e.colours[0]);this.assignColorToMesh(t,i)})):s.forEach((t=>{const i=Ce.FromHexString(e.colours);this.assignColorToMesh(t,i)}));else{const t=i?Ce.FromHexString(e.colours[0]):Ce.FromHexString(e.colours);this.assignColorToMesh(e.babylonMesh,t)}if(null!==e.babylonMesh.edgesRenderer){const t=i?Ce.FromHexString(e.colours[0]):Ce.FromHexString(e.colours);e.babylonMesh.edgesColor=Ee.FromColor3(t)}if([gV.drawingTypes.point,gV.drawingTypes.points,gV.drawingTypes.line,gV.drawingTypes.lines,gV.drawingTypes.polyline,gV.drawingTypes.polylines].includes(t)){const t=e.babylonMesh.getVerticesData(ys.ColorKind).length/4,s=[];if(i&&t===e.colours.length)for(let i=0;i{t.visibility=e.visibility}))}hide(e){e.babylonMesh.isVisible=!1,e.includeChildren&&e.babylonMesh.getChildMeshes&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!1}))}show(e){e.babylonMesh.isVisible=!0,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!0}))}setParent(e){e.babylonMesh.parent=e.parentMesh}getParent(e){return e.babylonMesh.parent}setCheckCollisions(e){e.babylonMesh.checkCollisions=e.checkCollisions,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.checkCollisions=e.checkCollisions}))}getCheckCollisions(e){return e.babylonMesh.checkCollisions}setPickable(e){e.babylonMesh.isPickable=e.pickable,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.isPickable=e.pickable}))}getPickable(e){return e.babylonMesh.isPickable}getMeshesWhereNameContains(e){return this.context.scene.meshes.filter((t=>t.name.includes(e.name)))}getChildMeshes(e){return e.babylonMesh.getChildMeshes(e.directDescendantsOnly)}getMeshesOfId(e){return this.context.scene.getMeshesById(e.id)}getMeshOfId(e){return this.context.scene.getMeshById(e.id)}getMeshOfUniqueId(e){return this.context.scene.getMeshByUniqueId(e.uniqueId)}clone(e){var t,i;const s=e.babylonMesh.clone(),r=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;return r.length>0&&(s.getChildMeshes().forEach((e=>{e.receiveShadows=!0,r.forEach((t=>t.addShadowCaster(e)))})),s.receiveShadows=!0,r.forEach((e=>e.addShadowCaster(s)))),s}setId(e){e.babylonMesh.id=e.id}getId(e){return e.babylonMesh.id}getUniqueId(e){return e.babylonMesh.uniqueId}setName(e){e.babylonMesh.name=e.name,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.name=e.name}))}getVerticesAsPolygonPoints(e){const t=e.babylonMesh.getVerticesData(ys.PositionKind),i=e.babylonMesh.getIndices(),s=[];for(let e=0;e{t.material=e.material}))}getMaterial(e){return e.babylonMesh.material}getPosition(e){const t=e.babylonMesh;return[t.position.x,t.position.y,t.position.z]}getAbsolutePosition(e){const t=e.babylonMesh;return[t.absolutePosition.x,t.absolutePosition.y,t.absolutePosition.z]}getRotation(e){const t=e.babylonMesh;return[t.rotation.x,t.rotation.y,t.rotation.z]}getScale(e){const t=e.babylonMesh;return[t.scaling.x,t.scaling.y,t.scaling.z]}moveForward(e){const t=e.babylonMesh;t.translate(t.forward,e.distance,lr.WORLD)}moveBackward(e){const t=e.babylonMesh;t.translate(t.forward.negate(),e.distance,lr.WORLD)}moveUp(e){const t=e.babylonMesh;t.translate(t.up,e.distance,lr.WORLD)}moveDown(e){const t=e.babylonMesh;t.translate(t.up.negate(),e.distance,lr.WORLD)}moveRight(e){const t=e.babylonMesh;t.translate(t.right,e.distance,lr.WORLD)}moveLeft(e){const t=e.babylonMesh;t.translate(t.right.negate(),e.distance,lr.WORLD)}yaw(e){const t=e.babylonMesh,i=vr.FromDegrees(e.rotate).radians();t.rotate(_r.Y,i,lr.LOCAL)}pitch(e){const t=e.babylonMesh,i=vr.FromDegrees(e.rotate).radians();t.rotate(_r.X,i,lr.LOCAL)}roll(e){const t=e.babylonMesh,i=vr.FromDegrees(e.rotate).radians();t.rotate(_r.Z,i,lr.LOCAL)}rotateAroundAxisWithPosition(e){e.mesh.rotateAround(new de(e.position[0],e.position[1],e.position[2]),new de(e.axis[0],e.axis[1],e.axis[2]),vr.FromDegrees(e.angle).radians())}setPosition(e){e.babylonMesh.position=new de(e.position[0],e.position[1],e.position[2])}setRotation(e){const t=vr.FromDegrees(e.rotation[0]).radians(),i=vr.FromDegrees(e.rotation[1]).radians(),s=vr.FromDegrees(e.rotation[2]).radians();e.babylonMesh.rotation=new de(t,i,s)}setScale(e){e.babylonMesh.scaling=new de(e.scale[0],e.scale[1],e.scale[2])}intersectsMesh(e){return e.babylonMesh.intersectsMesh(e.babylonMesh2,e.precise,e.includeDescendants)}intersectsPoint(e){const t=new de(e.point[0],e.point[1],e.point[2]);return e.babylonMesh.intersectsPoint(t)}createMeshInstanceAndTransformNoReturn(e){this.createMeshInstanceAndTransform(e)}createMeshInstanceAndTransform(e){var t,i;const s=new bo("instanceContainer"+Math.random(),this.context.scene),r=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0)e.mesh.getChildMeshes(!1).forEach((t=>{const i=t.getTotalVertices();if(t.createInstance&&i>0){t.disableEdgesRendering();const i=t.createInstance(`InstanceMesh${Math.random()}`);i.position=new de(e.position[0],e.position[1],e.position[2]),i.rotation=new de(e.rotation[0],e.rotation[1],e.rotation[2]),i.scaling=new de(e.scaling[0],e.scaling[1],e.scaling[2]),r.length>0&&r.forEach((e=>{e.addShadowCaster(i)})),i.parent=s}})),e.mesh.isVisible=!1;else if(e.mesh){e.mesh.isVisible=!1;const t=e.mesh.createInstance(`InstanceMesh${Math.random()}`);t.position=new de(e.position[0],e.position[1],e.position[2]),t.rotation=new de(vr.FromDegrees(e.rotation[0]).radians(),vr.FromDegrees(e.rotation[1]).radians(),vr.FromDegrees(e.rotation[2]).radians()),t.scaling=new de(e.scaling[0],e.scaling[1],e.scaling[2]),t.parent=s,r.length>0&&r.forEach((e=>{e.addShadowCaster(t)}))}return s}createMeshInstance(e){let t;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0){e.mesh.setParent(null);const i=new bo("meshCloneContainer"+Math.random());e.mesh.getChildMeshes(!1).forEach((e=>{e.createInstance&&e.getTotalVertices()>0&&e.getTotalIndices()>0&&(e.createInstance(`InstanceMesh${Math.random()}`).parent=i)})),t=i;const s=this.context.scene.metadata.shadowGenerators;s.length>0&&(t.getChildMeshes().forEach((e=>{s.forEach((t=>t.addShadowCaster(e)))})),s.forEach((e=>e.addShadowCaster(t))))}else if(e.mesh&&(e.mesh.setParent(null),e.mesh.getTotalVertices()>0)){const i=new bo("meshCloneContainer"+Math.random());e.mesh.createInstance(`InstanceMesh${Math.random()}`).parent=i,t=i}return t}getSideOrientation(e){switch(e){case cV.sideOrientationEnum.frontside:return bo.FRONTSIDE;case cV.sideOrientationEnum.backside:return bo.BACKSIDE;case cV.sideOrientationEnum.doubleside:return bo.DOUBLESIDE;default:return bo.FRONTSIDE}}assignColorToMesh(e,t){const i=e.material;i instanceof zv?i.baseColor=t:i instanceof yc&&(i.diffuseColor=t)}}class kV{constructor(e,t){this.context=e,this.mesh=t}createBox(e){const t=Gd.CreateBox("BabylonMesh"+Math.random(),{width:e.width,height:e.height,depth:e.depth,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createCube(e){const t=Gd.CreateBox("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createSquarePlane(e){const t=Gd.CreatePlane("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createRectanglePlane(e){const t=Gd.CreatePlane("BabylonMesh"+Math.random(),{width:e.width,height:e.height,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}enableShadows(e){this.context.scene.metadata.shadowGenerators&&(e.receiveShadows=!0,this.context.scene.metadata.shadowGenerators.forEach((t=>{t.addShadowCaster(e)})))}}class VV{constructor(e,t){this.context=e,this.geometryHelper=t}drawNode(e){this.geometryHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=e.node}drawNodes(e){e.nodes.forEach((t=>{this.geometryHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=t}))}createNodeFromRotation(e){const t=new xn(`node${Math.random()}`,this.context.scene);return e.parent&&(t.parent=e.parent),t.position=new de(e.origin[0],e.origin[1],e.origin[2]),t.rotation=new de(vr.FromDegrees(e.rotation[0]).radians(),vr.FromDegrees(e.rotation[1]).radians(),vr.FromDegrees(e.rotation[2]).radians()),t}createWorldNode(){const e=new xn(`root${Math.random()}`,this.context.scene);return e.parent=this.context.scene.getTransformNodeByID("root"),e}getAbsoluteForwardVector(e){const t=e.node.forward;return[t.x,t.y,t.z]}getAbsoluteRightVector(e){const t=e.node.right;return[t.x,t.y,t.z]}getAbsoluteUpVector(e){const t=e.node.up;return[t.x,t.y,t.z]}getAbsolutePosition(e){const t=e.node.getAbsolutePosition();return[t.x,t.y,t.z]}getAbsoluteRotationTransformation(e){const t=new fe;return e.node.absoluteRotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getRotationTransformation(e){const t=new fe;return e.node.rotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getChildren(e){return e.node.getChildren()}getParent(e){return e.node.parent}getPositionExpressedInLocalSpace(e){const t=e.node.getPositionExpressedInLocalSpace();return[t.x,t.y,t.z]}getRootNode(){return this.context.scene.getTransformNodeByID("root")}getRotation(e){const t=e.node.rotation;return[vr.FromRadians(t.x).degrees(),vr.FromRadians(t.y).degrees(),vr.FromRadians(t.z).degrees()]}rotateAroundAxisWithPosition(e){e.node.rotateAround(new de(e.position[0],e.position[1],e.position[2]),new de(e.axis[0],e.axis[1],e.axis[2]),vr.FromDegrees(e.angle).radians())}rotate(e){e.node.rotate(new de(e.axis[0],e.axis[1],e.axis[2]),vr.FromDegrees(e.angle).radians())}setAbsolutePosition(e){e.node.setAbsolutePosition(new de(e.position[0],e.position[1],e.position[2]))}setDirection(e){e.node.setDirection(new de(e.direction[0],e.direction[1],e.direction[2]))}setParent(e){e.node.setParent(e.parentNode)}translate(e){e.node.translate(new de(e.direction[0],e.direction[1],e.direction[2]),e.distance)}}class UV{constructor(e){this.context=e}pickWithRay(e){return this.context.scene.pickWithRay(e.ray)}pickWithPickingRay(){const e=this.context.scene,t=e.createPickingRay(e.pointerX,e.pointerY,fe.Identity(),this.context.scene.activeCamera,!1);return e.pickWithRay(t)}getDistance(e){return e.pickInfo.distance}getPickedMesh(e){return e.pickInfo.pickedMesh}getPickedPoint(e){const t=e.pickInfo.pickedPoint;return[t.x,t.y,t.z]}hit(e){return e.pickInfo.hit}getSubMeshId(e){return e.pickInfo.subMeshId}getSubMeshFaceId(e){return e.pickInfo.subMeshFaceId}getBU(e){return e.pickInfo.bu}getBV(e){return e.pickInfo.bv}getPickedSprite(e){return e.pickInfo.pickedSprite}}class GV{constructor(e){this.context=e}createPickingRay(){const e=this.context.scene;return e.createPickingRay(e.pointerX,e.pointerY,fe.Identity(),this.context.scene.activeCamera,!1)}createRay(e){const t=new de(e.origin[0],e.origin[1],e.origin[2]),i=new de(e.direction[0],e.direction[1],e.direction[2]);let s;return 0!==e.length&&(s=e.length),new Zo(t,i,s)}createRayFromTo(e){const t=new de(e.from[0],e.from[1],e.from[2]),i=new de(e.to[0],e.to[1],e.to[2]);return Zo.CreateNewFromTo(t,i)}getOrigin(e){const t=e.ray.origin;return[t.x,t.y,t.z]}getDirection(e){const t=e.ray.direction;return[t.x,t.y,t.z]}getLength(e){return e.ray.length}}class zV{constructor(e){this.context=e}getScene(){return this.context.scene}setAndAttachScene(e){return e.scene.metadata={shadowGenerators:[]},new xn("root",this.context.scene),this.context.scene=e.scene}backgroundColour(e){this.context.scene.clearColor=Ee.FromColor3(Ce.FromHexString(e.colour))}activateCamera(e){this.context.scene.activeCamera.detachControl(),this.context.scene.activeCamera=e.camera}useRightHandedSystem(e){this.context.scene.useRightHandedSystem=e.use,this.context.scene.activeCamera.getViewMatrix(!0),this.context.scene.activeCamera.getProjectionMatrix(!0)}drawPointLightNoReturn(e){this.drawPointLight(e)}getShadowGenerators(){return this.context.scene.metadata&&this.context.scene.metadata.shadowGenerators?this.context.scene.metadata.shadowGenerators:[]}drawPointLight(e){const t=new de(e.position[0],e.position[1],e.position[2]),i=new ov(`pointLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new Kg(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=!0,t.contactHardeningLightSizeUVRatio=.2,t.bias=1e-4,t.normalBias=.002,i.shadowMaxZ=1e3,i.shadowMinZ=.01,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}if(i.diffuse=Ce.FromHexString(e.diffuse),i.specular=Ce.FromHexString(e.specular),i.intensityMode=yo.INTENSITYMODE_LUMINOUSPOWER,i.intensity=e.intensity,e.radius>0){const t=Gd.CreateSphere(`PointLightSphere${Math.random()}`,{diameter:2*e.radius},this.context.scene),s=new yc(`LightMaterial${Math.random()}`,this.context.scene);s.diffuseColor=i.diffuse,s.specularColor=i.diffuse,s.emissiveColor=i.diffuse,t.material=s,t.parent=i}return i}drawDirectionalLightNoReturn(e){this.drawDirectionalLight(e)}drawDirectionalLight(e){const t=new de(e.direction[0],e.direction[1],e.direction[2]),i=new lm(`directionalLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new Kg(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=!0,t.contactHardeningLightSizeUVRatio=.2,t.bias=1e-4,t.normalBias=.002,i.shadowMaxZ=1e3,i.shadowMinZ=0,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}return i.diffuse=Ce.FromHexString(e.diffuse),i.specular=Ce.FromHexString(e.specular),i.intensity=e.intensity,i.shadowMaxZ=1e3,i}getActiveCamera(){return this.context.scene.activeCamera}adjustActiveArcRotateCamera(e){const t=this.context.scene.getCameraByName("Camera");t.position=new de(e.position[0],e.position[1],e.position[2]),t.target=new de(e.lookAt[0],e.lookAt[1],e.lookAt[2]);const i=de.Distance(t.position,t.target);t.radius=i,void 0!==e.lowerBetaLimit&&(t.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(t.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.angularSensibilityX&&(t.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(t.angularSensibilityY=e.angularSensibilityY),void 0!==e.panningSensibility&&(t.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(t.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(t.maxZ=e.maxZ)}clearAllDrawn(){const e=this.context.scene;if(e&&(e.environmentTexture&&e.environmentTexture.dispose(),e.environmentTexture=null,e.fogMode=dr.FOGMODE_NONE,e.meshes.forEach((e=>e.dispose())),e.meshes=[],e.materials.forEach((e=>e.dispose())),e.textures.forEach((e=>e.dispose())),e.materials=[],e.textures=[],e.useRightHandedSystem=!1,e.geometries.forEach((e=>{e.meshes&&e.meshes.forEach((e=>e.dispose())),e.dispose&&e.dispose()})),e.geometries=[],e.lights.forEach((e=>{"HemiLight"!==e.name&&e.dispose()})),e.lights=e.lights.filter((e=>"HemiLight"===e.name)),e.transformNodes&&e.transformNodes.forEach((e=>{e&&"root"!==e.name&&e.dispose()})),e.metadata&&(e.metadata.shadowGenerators.length>0&&(e.metadata.shadowGenerators.forEach((e=>e.dispose())),e.metadata.shadowGenerators=[]),e.metadata.xr&&e.metadata.xr.dispose(),e.metadata.guiManager&&e.metadata.guiManager.dispose()),e.transformNodes=[e.getTransformNodeByName("root")],e.activeCamera&&"Camera"!==e.activeCamera.name)){e.cameras.forEach((e=>e.dispose()));const t=new Th("Camera",0,10,10,new de(0,0,0),e);t.lowerRadiusLimit=0,e.setActiveCameraByName(t.name),t.setPosition(new de(0,10,20));const i=document.getElementById("renderCanvas");t.attachControl(i,!0),t.minZ=0}}enableSkybox(e){let t;e.skybox===PV.skyboxEnum.default?t=new mm("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.14.7.5/textures/skybox/default_skybox/skybox",this.context.scene):e.skybox===PV.skyboxEnum.clearSky?t=mm.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.14.7.5/textures/skybox/clear_sky/environment.env",this.context.scene,!1,!1):e.skybox===PV.skyboxEnum.city&&(t=mm.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.14.7.5/textures/skybox/city/environmentSpecular.env",this.context.scene,!1,!1)),this.context.scene.createDefaultSkybox(t,!0,e.size,e.blur,!0).name="bitbybit-hdrSkyBox",this.context.scene.environmentIntensity=e.environmentIntensity}onPointerDown(e){this.context.scene.onPointerDown=e.statement_update}onPointerUp(e){this.context.scene.onPointerUp=e.statement_update}onPointerMove(e){this.context.scene.onPointerMove=e.statement_update}fog(e){switch(e.mode){case PV.fogModeEnum.none:this.context.scene.fogMode=0;break;case PV.fogModeEnum.exponential:this.context.scene.fogMode=1;break;case PV.fogModeEnum.exponentialSquared:this.context.scene.fogMode=2;break;case PV.fogModeEnum.linear:this.context.scene.fogMode=3}this.context.scene.fogDensity=e.density,this.context.scene.fogStart=e.start,this.context.scene.fogEnd=e.end,this.context.scene.fogColor=Ce.FromHexString(e.color)}enablePhysics(e){this.context.scene.enablePhysics(new de(e.vector[0],e.vector[1],e.vector[2]),this.context.havokPlugin)}getRadians(e){let t=vr.FromDegrees(e).radians();return e<0&&(t=-t),t}}class WV{constructor(e){this.context=e}createSimple(e){const t=new Vo(e.url,this.context.scene,void 0,e.invertY,this.getSamplingMode(e.samplingMode));return t.uScale=e.uScale,t.vScale=e.vScale,t.wAng=e.wAng,t.invertZ=e.invertZ,t.uOffset=e.uOffset,t.vOffset=e.vOffset,t}getSamplingMode(e){switch(e){case pV.samplingModeEnum.nearest:return Vo.NEAREST_SAMPLINGMODE;case pV.samplingModeEnum.bilinear:return Vo.BILINEAR_SAMPLINGMODE;case pV.samplingModeEnum.trilinear:return Vo.TRILINEAR_SAMPLINGMODE;default:return Vo.NEAREST_SAMPLINGMODE}}}class HV{rotationCenterAxis(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationAxis(new de(e.axis[0],e.axis[1],e.axis[2]),vr.FromDegrees(e.angle).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterX(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationX(vr.FromDegrees(e.angle).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterY(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationY(vr.FromDegrees(e.angle).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterZ(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationZ(vr.FromDegrees(e.angle).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterYawPitchRoll(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationYawPitchRoll(vr.FromDegrees(e.yaw).radians(),vr.FromDegrees(e.pitch).radians(),vr.FromDegrees(e.roll).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}scaleCenterXYZ(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}scaleXYZ(e){return[[...fe.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).toArray()]]}uniformScale(e){return[[...fe.Scaling(e.scale,e.scale,e.scale).toArray()]]}uniformScaleFromCenter(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.Scaling(e.scale,e.scale,e.scale).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}translationXYZ(e){return[[...fe.Translation(e.translation[0],e.translation[1],e.translation[2]).toArray()]]}translationsXYZ(e){return e.translations.map((e=>[[...fe.Translation(e[0],e[1],e[2]).toArray()]]))}}class XV{constructor(e,t,i){this.mesh=new LV(e),this.camera=new _k(e),this.node=new VV(e,t),this.scene=new zV(e),this.webxr=new vk(e),this.transforms=new HV,this.io=new BV(e),this.ray=new GV(e),this.pick=new UV(e),this.material=new fk(e,i),this.texture=new WV(e),this.meshBuilder=new kV(e,this.mesh),this.engine=new xk(e)}}var YV=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class QV{constructor(e){this.jscadWorkerManager=e}intersect(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.intersect",e)}))}subtract(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtract",e)}))}union(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.union",e)}))}intersectTwo(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.intersectTwo",e)}))}subtractTwo(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtractTwo",e)}))}unionTwo(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.unionTwo",e)}))}subtractFrom(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtractFrom",e)}))}}var jV=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class KV{constructor(e){this.jscadWorkerManager=e}expand(e){return jV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("expansions.expand",e)}))}offset(e){return jV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("expansions.offset",e)}))}}var $V=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class qV{constructor(e){this.jscadWorkerManager=e}extrudeLinear(e){return $V(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeLinear",e)}))}extrudeRectangular(e){return $V(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRectangular",e)}))}extrudeRectangularPoints(e){return $V(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRectangularPoints",e)}))}extrudeRotate(e){return $V(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRotate",e)}))}}var ZV=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class JV{constructor(e){this.jscadWorkerManager=e}hullChain(e){return ZV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("hulls.hullChain",e)}))}hull(e){return ZV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("hulls.hullChain",e)}))}}var eU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class tU{constructor(e){this.jscadWorkerManager=e}createFromPoints(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createFromPoints",e)}))}createPathsFromPoints(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createPathsFromPoints",e)}))}createFromPolyline(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createFromPolyline",e)}))}createEmpty(){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createEmpty",{})}))}close(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.close",e)}))}appendPoints(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendPoints",e)}))}appendPolyline(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendPolyline",e)}))}appendArc(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendArc",e)}))}}var iU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class sU{constructor(e){this.jscadWorkerManager=e}createFromPoints(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPoints",e)}))}createFromPolyline(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPolyline",e)}))}createFromCurve(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromCurve",e)}))}createFromPath(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPath",e)}))}circle(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.circle",e)}))}ellipse(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.ellipse",e)}))}rectangle(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.rectangle",e)}))}roundedRectangle(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.roundedRectangle",e)}))}square(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.square",e)}))}star(e){return iU(this,void 0,void 0,(function*(){return yield this.jscadWorkerManager.genericCallToWorkerPromise("polygon.star",e)}))}}var rU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class nU{constructor(e){this.jscadWorkerManager=e}cube(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cube",e)}))}cubesOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cubesOnCenterPoints",e)}))}cuboid(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cuboid",e)}))}cuboidsOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cuboidsOnCenterPoints",e)}))}cylinderElliptic(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinderElliptic",e)}))}cylinderEllipticOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinderEllipticOnCenterPoints",e)}))}cylinder(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinder",e)}))}cylindersOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylindersOnCenterPoints",e)}))}ellipsoid(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.ellipsoid",e)}))}ellipsoidsOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.ellipsoidsOnCenterPoints",e)}))}geodesicSphere(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.geodesicSphere",e)}))}geodesicSpheresOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.geodesicSpheresOnCenterPoints",e)}))}roundedCuboid(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCuboid",e)}))}roundedCuboidsOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCuboidsOnCenterPoints",e)}))}roundedCylinder(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCylinder",e)}))}roundedCylindersOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCylindersOnCenterPoints",e)}))}sphere(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.sphere",e)}))}spheresOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.spheresOnCenterPoints",e)}))}torus(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.torus",e)}))}fromPolygonPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.fromPolygonPoints",e)}))}}var oU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class aU{constructor(e){this.jscadWorkerManager=e}cylindricalText(e){return oU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.cylindricalText",e)}))}sphericalText(e){return oU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.sphericalText",e)}))}createVectorText(e){return oU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.createVectorText",e)}))}}class lU{constructor(e){this.jscadWorkerManager=e}colorize(e){return t=this,i=void 0,r=function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("colors.colorize",e)},new((s=void 0)||(s=Promise))((function(e,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,a)}l((r=r.apply(t,i||[])).next())}));var t,i,s,r}}var hU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class cU{constructor(e,t,i){this.jscadWorkerManager=e,this.context=t,this.geometryHelper=i,this.booleans=new QV(e),this.expansions=new KV(e),this.extrusions=new qV(e),this.hulls=new JV(e),this.path=new tU(e),this.polygon=new sU(e),this.shapes=new nU(e),this.text=new aU(e),this.colors=new lU(e)}drawSolidOrPolygonMesh(e){return hU(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);let i,s;i=e.jscadMesh&&e.updatable?e.jscadMesh:new bo(`jscadMesh${Math.random()}`,this.context.scene),s=e.mesh.color&&e.mesh.color.length>0?Ce.FromArray(e.mesh.color).toHexString():Array.isArray(e.colours)?e.colours[0]:e.colours;const r=this.makeMesh(Object.assign(Object.assign({},e),{colour:s}),i,t);return e.jscadMesh=r,r}))}makeMesh(e,t,i){this.createMesh(i.positions,i.indices,i.normals,t,i.transforms,e.updatable),t.material=new zv(`jscadMaterial${Math.random()}`,this.context.scene),t.flipFaces(!1);const s=t.material;return s.baseColor=Ce.FromHexString(e.colour),s.metallic=1,s.roughness=.6,s.alpha=e.opacity,s.alphaMode=1,s.backFaceCulling=!0,s.zOffset=0,t.isPickable=!1,e.hidden&&(t.isVisible=!1),t}drawSolidOrPolygonMeshes(e){return hU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e).then((t=>{let i;e.jscadMesh&&e.updatable?(i=e.jscadMesh,i.getChildMeshes().forEach((e=>{e.dispose(),i.removeChild(e)}))):i=new bo("local_origin"+Math.random(),this.context.scene),i.isVisible=!1;const s=Array.isArray(e.colours)&&e.colours.length===t.length,r=Array.isArray(e.colours);return t.map(((t,n)=>{const o=new bo(`jscadMesh${Math.random()}`,this.context.scene);let a;a=t.color?Ce.FromArray(t.color).toHexString():s?e.colours[n]:r?e.colours[0]:e.colours,this.makeMesh(Object.assign(Object.assign({},e),{colour:a}),o,t).parent=i})),e.jscadMesh=i,i}))}))}drawPath(e){return hU(this,void 0,void 0,(function*(){return new Promise((t=>{if(e.path.points&&e.path.isClosed){const t=e.path.points[0];e.path.points.push([t[0],0,t[1]])}let i=e.colour;e.path.color&&(i=Ce.FromArray(e.path.color).toHexString()),t(this.geometryHelper.drawPolyline(e.pathMesh,e.path.points,e.updatable,e.width,e.opacity,i))}))}))}transformSolids(e){return hU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("transformSolids",e)}))}transformSolid(e){return hU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("transformSolid",e)}))}downloadSolidSTL(e){return hU(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadSolidSTL",e);this.downloadFile(t.blob,e.fileName,"stl")}))}downloadSolidsSTL(e){return hU(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadSolidsSTL",e);this.downloadFile(t.blob,e.fileName,"stl")}))}downloadGeometryDxf(e){return hU(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadGeometryDxf",e);this.downloadFile(t.blob,e.fileName,"dxf")}))}downloadFile(e,t,i){const s=URL.createObjectURL(e),r=document.createElement("a");r.href=s,r.target="_self",r.download=t+"."+i,r.click(),r.remove()}createMesh(e,t,i,s,r,n){const o=new cn;o.positions=e,o.indices=t,cn.ComputeNormals(e,t,i,{useRightHandedSystem:!0}),o.normals=i,o.applyToMesh(s,n),s.setPreTransformMatrix(fe.FromArray(r))}}var uU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class dU extends tL{constructor(e,t,i){super(e),this.occWorkerManager=e,this.context=t,this.geometryHelper=i}loadSTEPorIGES(e){return this.context.getFile(e.assetFile).then((t=>this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new rk.LoadStepOrIgesDto(t,e.assetFile.name,e.adjustZtoY))))}loadSTEPorIGESFromText(e){return this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new rk.LoadStepOrIgesDto(e.text,`fake.${e.fileType}`,e.adjustZtoY))}saveShapeStl(e){return uU(this,void 0,void 0,(function*(){this.saveStl(e)}))}saveShapeStlAndReturn(e){return uU(this,void 0,void 0,(function*(){return this.saveStl(e)}))}saveStl(e){return uU(this,void 0,void 0,(function*(){const t=new rk.DrawShapeDto;t.drawEdges=!1,t.shape=e.shape,t.precision=e.precision;const i=(yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",t)).faceList.map((e=>this.geometryHelper.createOrUpdateSurfaceMesh({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes},void 0,!1,void 0,!0,!1)));let s;return e.fileName.includes(".stl")&&(e.fileName=e.fileName.replace(".stl","")),s=document&&e.tryDownload?nV.CreateSTL(i,!0,e.fileName,e.binary,!0,!0):nV.CreateSTL(i,!1,e.fileName,e.binary,!0,!0),i.forEach((e=>e.dispose())),s}))}}var _U,pU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class fU extends bL{constructor(e,t,i,s,r){super(t),this.context=e,this.occWorkerManager=t,this.geometryHelper=i,this.solidText=s,this.vector=r,this.usedMaterials=[],this.io=new dU(t,e,i)}drawShape(e){return pU(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);return this.handleDecomposedMesh(e,i,t)}))}drawShapes(e){return pU(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e),s=yield Promise.all(i.map((i=>pU(this,void 0,void 0,(function*(){return this.handleDecomposedMesh(e,i,t)}))))),r=new bo("shapesMeshContainer"+Math.random(),this.context.scene);return s.forEach((e=>{e.parent=r})),r}))}handleDecomposedMesh(e,t,i){return pU(this,void 0,void 0,(function*(){const s=new bo("brepMesh"+Math.random(),this.context.scene);let r;if(s.isVisible=!1,e.drawFaces&&t&&t.faceList&&t.faceList.length){let n;if(i.faceMaterial)n=i.faceMaterial;else{const t=Array.isArray(e.faceColour)?e.faceColour[0]:e.faceColour,i=e.faceOpacity,s=e.drawEdges?2:0,r=this.usedMaterials.find((e=>e.sceneId===this.context.scene.uid&&e.hex===t&&e.alpha===i&&e.zOffset===s));if(this.usedMaterials=this.usedMaterials.filter((e=>e.sceneId===this.context.scene.uid)),r)n=r.material;else{const e=new zv("pbr"+Math.random(),this.context.scene);e.baseColor=Ce.FromHexString(t),e.metallic=1,e.roughness=.6,e.alpha=i,e.alphaMode=1,e.backFaceCulling=!0,e.doubleSided=!1,e.zOffset=s,this.usedMaterials.push({sceneId:this.context.scene.uid,hex:t,alpha:i,zOffset:s,material:e}),n=e}}const o=t.faceList.map((e=>({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes,uvs:e.uvs})));this.geometryHelper.createOrUpdateSurfacesMesh(o,r,!1,n,!0,!1).parent=s}if(e.drawEdges&&t&&t.edgeList&&t.edgeList.length){const i=[];t.edgeList.forEach((e=>{const t=e.vertex_coord.filter((e=>void 0!==e));i.push(t)})),this.geometryHelper.drawPolylines(r,i,!1,e.edgeWidth,e.edgeOpacity,e.edgeColour).parent=s}if(e.drawVertices&&t&&t.pointsList&&t.pointsList.length&&(this.geometryHelper.drawPoints({pointsMesh:r,points:t.pointsList,opacity:1,size:e.vertexSize,colours:e.vertexColour,updatable:!1}).parent=s),e.drawEdgeIndexes){const i=t.edgeList.map((t=>pU(this,void 0,void 0,(function*(){const i=this.computeEdgeMiddlePos(t),s=new vV.TextDto;return s.text=`${t.edge_index+1}`,s.height=e.edgeIndexHeight,s.lineSpacing=1.5,(yield this.solidText.createVectorText(s)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),r=yield Promise.all(i),n=this.geometryHelper.drawPolylines(null,r.flat(),!1,.2,1,e.edgeIndexColour);n.parent=s,n.material.zOffset=-2}if(e.drawFaceIndexes){const i=t.faceList.map((t=>pU(this,void 0,void 0,(function*(){const i=this.computeFaceMiddlePos(t.vertex_coord_vec),s=new vV.TextDto;return s.text=`${t.face_index}`,s.height=e.faceIndexHeight,s.lineSpacing=1.5,(yield this.solidText.createVectorText(s)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),r=yield Promise.all(i),n=this.geometryHelper.drawPolylines(null,r.flat(),!1,.2,1,e.faceIndexColour);n.parent=s,e.drawEdges&&(n.material.zOffset=-2)}return s}))}computeFaceMiddlePos(e){let t=0,i=0,s=0,r=0;return e.forEach((e=>{t+=e[0],i+=e[1],s+=e[2],r++})),[t/r,i/r,s/r]}computeEdgeMiddlePos(e){let t;if(2===e.vertex_coord.length){const i=e.vertex_coord[0],s=e.vertex_coord[1];t=this.vector.lerp({first:i,second:s,fraction:.5})}else if(3===e.vertex_coord.length)t=e.vertex_coord[1];else{const i=e.vertex_coord[Math.floor(e.vertex_coord.length/2)],s=e.vertex_coord[Math.floor(e.vertex_coord.length/2+1)];t=this.vector.lerp({first:i,second:s,fraction:.5})}return t}}class mU{constructor(e){this.context=e}createCircle(e){return new this.context.verb.geom.Circle(e.center,e.xAxis,e.yAxis,e.radius)}createArc(e){return new this.context.verb.geom.Arc(e.center,e.xAxis,e.yAxis,e.radius,vr.FromDegrees(e.minAngle).radians(),vr.FromDegrees(e.maxAngle).radians())}center(e){return e.circle.center()}radius(e){return e.circle.radius()}maxAngle(e){return vr.FromRadians(e.circle.maxAngle()).degrees()}minAngle(e){return vr.FromRadians(e.circle.minAngle()).degrees()}xAxis(e){return e.circle.xaxis()}yAxis(e){return e.circle.yaxis()}}class gU{constructor(e){this.context=e}createEllipse(e){return new this.context.verb.geom.Ellipse(e.center,e.xAxis,e.yAxis)}createArc(e){return new this.context.verb.geom.EllipseArc(e.center,e.xAxis,e.yAxis,vr.FromDegrees(e.minAngle).radians(),vr.FromDegrees(e.maxAngle).radians())}center(e){return e.ellipse.center()}maxAngle(e){return vr.FromRadians(e.ellipse.maxAngle()).degrees()}minAngle(e){return vr.FromRadians(e.ellipse.minAngle()).degrees()}xAxis(e){return e.ellipse.xaxis()}yAxis(e){return e.ellipse.yaxis()}}class vU{constructor(e,t){this.context=e,this.geometryHelper=t,this.circle=new mU(e),this.ellipse=new gU(e)}drawCurve(e){const t=e.curve.tessellate();return this.geometryHelper.drawPolyline(e.curveMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawCurves(e){const t=e.curves.map((e=>e.tessellate()));return this.geometryHelper.drawPolylines(e.curvesMesh,t,e.updatable,e.size,e.opacity,e.colours)}createCurveByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.degree,e.knots,e.points,e.weights)}createCurveByPoints(e){return this.context.verb.geom.NurbsCurve.byPoints(e.points,e.degree)}createBezierCurve(e){return new this.context.verb.geom.BezierCurve(e.points,e.weights)}clone(e){return e.curve.clone()}closestParam(e){return e.curve.closestParam(e.point)}closestParams(e){return e.points.map((t=>e.curve.closestParam(t)))}closestPoint(e){return e.curve.closestPoint(e.point)}closestPoints(e){return e.points.map((t=>e.curve.closestPoint(t)))}controlPoints(e){return e.curve.controlPoints()}degree(e){return e.curve.degree()}derivatives(e){return e.curve.derivatives(e.parameter,e.numDerivatives)}divideByEqualArcLengthToParams(e){return e.curve.divideByEqualArcLength(e.subdivision).map((e=>e.u))}divideByEqualArcLengthToPoints(e){return e.curve.divideByEqualArcLength(e.subdivision).map((t=>e.curve.point(t.u)))}divideByArcLengthToParams(e){return e.curve.divideByArcLength(e.length).map((e=>e.u))}divideByArcLengthToPoints(e){return e.curve.divideByArcLength(e.length).map((t=>e.curve.point(t.u)))}divideCurvesByEqualArcLengthToPoints(e){return e.curves.map((t=>this.divideByEqualArcLengthToPoints({curve:t,subdivision:e.subdivision})))}divideCurvesByArcLengthToPoints(e){return e.curves.map((t=>this.divideByArcLengthToPoints({curve:t,length:e.length})))}domain(e){return e.curve.domain()}startPoint(e){return e.curve.point(e.curve.domain().min)}endPoint(e){return e.curve.point(e.curve.domain().max)}startPoints(e){return e.curves.map((e=>this.startPoint({curve:e})))}endPoints(e){return e.curves.map((e=>this.endPoint({curve:e})))}knots(e){return e.curve.knots()}lengthAtParam(e){return e.curve.lengthAtParam(e.parameter)}length(e){return e.curve.length()}paramAtLength(e){return e.curve.paramAtLength(e.length,e.tolerance)}pointAtParam(e){return e.curve.point(e.parameter)}pointsAtParam(e){return e.curves.map((t=>this.pointAtParam({curve:t,parameter:e.parameter})))}reverse(e){return e.curve.reverse()}split(e){return e.curve.split(e.parameter)}tangent(e){return e.curve.tangent(e.parameter)}tessellate(e){return e.curve.tessellate(e.tolerance)}transform(e){const t=e.curve.controlPoints(),i=this.geometryHelper.transformControlPoints(e.transformation,t);return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.curve.degree(),e.curve.knots(),i,e.curve.weights())}transformCurves(e){return e.curves.map((t=>this.transform({curve:t,transformation:e.transformation})))}weights(e){return e.curve.weights()}}class xU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.RevolvedSurface(e.profile,e.center,e.axis,vr.FromDegrees(e.angle).radians())}profile(e){return e.revolution.profile()}center(e){return e.revolution.center()}axis(e){return e.revolution.axis()}angle(e){return vr.FromRadians(e.revolution.angle()).degrees()}}class bU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ConicalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cone.axis()}base(e){return e.cone.base()}height(e){return e.cone.height()}radius(e){return e.cone.radius()}xAxis(e){return e.cone.xaxis()}}class TU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.CylindricalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cylinder.axis()}base(e){return e.cylinder.base()}height(e){return e.cylinder.height()}radius(e){return e.cylinder.radius()}xAxis(e){return e.cylinder.xaxis()}}class yU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ExtrudedSurface(e.profile,e.direction)}direction(e){return e.extrusion.direction()}profile(e){return e.extrusion.profile()}}class SU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SphericalSurface(e.center,e.radius)}radius(e){return e.sphere.radius()}center(e){return e.sphere.center()}}class CU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SweptSurface(e.profile,e.rail)}profile(e){return e.sweep.profile()}rail(e){return e.sweep.rail()}}class EU{constructor(e,t){this.context=e,this.geometryHelper=t,this.cone=new bU(e),this.cylinder=new TU(e),this.extrusion=new yU(e),this.sphere=new SU(e),this.revolved=new xU(e),this.sweep=new CU(e)}drawSurface(e){const t=e.surface.tessellate(),i={positions:[],indices:[],normals:[]};let s=0;t.faces.forEach((e=>{s=this.parseFaces(e,t,i,s)}));const r=new zv("pbr"+Math.random(),this.context.scene);return r.baseColor=Ce.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!1,r.doubleSided=!0,this.geometryHelper.createOrUpdateSurfaceMesh(i,e.surfaceMesh,e.updatable,r,!0,e.hidden)}drawSurfaces(e){const t=[];e.surfaces.forEach((e=>{t.push(e.tessellate())}));const i={positions:[],indices:[],normals:[]};let s=0;t.forEach((e=>{e.faces.forEach((t=>{s=this.parseFaces(t,e,i,s)}))}));const r=new zv("pbr"+Math.random(),this.context.scene);return r.baseColor=Ce.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!0,r.doubleSided=!1,this.geometryHelper.createOrUpdateSurfaceMesh(i,e.surfacesMesh,e.updatable,r,!0,e.hidden)}drawSurfacesMultiColour(e){return e.surfacesMesh&&e.updatable&&e.surfacesMesh.getChildren().forEach((e=>e.dispose())),e.surfacesMesh=new bo(`ColouredSurfaces${Math.random()}`,this.context.scene),Array.isArray(e.colours)?e.surfaces.forEach(((t,i)=>{const s=this.drawSurface({surface:t,colours:e.colours[i]?e.colours[i]:e.colours[0],updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(s)})):e.surfaces.forEach(((t,i)=>{const s=this.drawSurface({surface:t,colours:e.colours,updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(s)})),e.surfacesMesh}boundaries(e){return e.surface.boundaries()}createSurfaceByCorners(e){return this.context.verb.geom.NurbsSurface.byCorners(e.point1,e.point2,e.point3,e.point4)}createSurfaceByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.degreeU,e.degreeV,e.knotsU,e.knotsV,e.points,e.weights)}createSurfaceByLoftingCurves(e){return this.context.verb.geom.NurbsSurface.byLoftingCurves(e.curves,e.degreeV)}clone(e){return e.surface.clone()}closestParam(e){return e.surface.closestParam(e.point)}closestPoint(e){return e.surface.closestPoint(e.point)}controlPoints(e){return e.surface.controlPoints()}degreeU(e){return e.surface.degreeU()}degreeV(e){return e.surface.degreeV()}derivatives(e){return e.surface.derivatives(e.u,e.v,e.numDerivatives)}domainU(e){return e.surface.domainU()}domainV(e){return e.surface.domainV()}isocurve(e){return e.surface.isocurve(e.parameter,e.useV)}isocurvesSubdivision(e){const t=.999999/e.isocurveSegments,i=this.context.verb.core.Vec.span(1e-7,.9999999,t);return e.includeLast||i.pop(),e.includeFirst||i.shift(),i.map((t=>e.surface.isocurve(t,e.useV)))}isocurvesAtParams(e){return e.parameters.map((t=>e.surface.isocurve(t,e.useV)))}knotsU(e){return e.surface.knotsU()}knotsV(e){return e.surface.knotsV()}normal(e){return e.surface.normal(e.u,e.v)}point(e){return e.surface.point(e.u,e.v)}reverse(e){return e.surface.reverse()}split(e){return e.surface.split(e.parameter,e.useV)}transformSurface(e){const t=e.surface.controlPoints(),i=e.transformation,s=[];return t.forEach((e=>{let t=e;t=this.geometryHelper.transformControlPoints(i,t),s.push(t)})),this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.surface.degreeU(),e.surface.degreeV(),e.surface.knotsU(),e.surface.knotsV(),s,e.surface.weights())}weights(e){return e.surface.weights()}parseFaces(e,t,i,s){return e.reverse().forEach((e=>{const r=t.normals[e];i.normals.push(r[0],r[1],r[2]);const n=t.points[e];i.positions.push(n[0],n[1],n[2]),i.indices.push(s),s++})),s}}class AU{constructor(e,t){this.context=e,this.geometryHelper=t}curves(e){return this.context.verb.geom.Intersect.curves(e.firstCurve,e.secondCurve,e.tolerance)}curveAndSurface(e){return this.context.verb.geom.Intersect.curveAndSurface(e.curve,e.surface,e.tolerance)}surfaces(e){return this.context.verb.geom.Intersect.surfaces(e.firstSurface,e.secondSurface)}curveCurveFirstParams(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.u0))}curveCurveSecondParams(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.u1))}curveCurveFirstPoints(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.point0))}curveCurveSecondPoints(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.point1))}curveSurfaceCurveParams(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.u))}curveSurfaceSurfaceParams(e){return e.intersections.map((e=>e.uv))}curveSurfaceCurvePoints(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.curvePoint))}curveSurfaceSurfacePoints(e){return e.intersections.map((e=>e.surfacePoint))}}class PU{constructor(e,t){this.curve=new vU(e,t),this.surface=new EU(e,t),this.intersect=new AU(e,t)}}!function(e){e.IntervalDto=class{constructor(){this.min=0,this.max=1}},e.UVDto=class{constructor(){this.u=0,this.v=0}},e.CurveCurveIntersection=class{},e.CurveSurfaceIntersection=class{},e.SurfaceSurfaceIntersectionPoint=class{}}(_U||(_U={}));bi.ShadersStore.cellPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{diffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;if (info.ndl<0.5)\nlevel=0.5;diffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];ToonThresholds[0]=0.95;ToonThresholds[1]=0.5;ToonThresholds[2]=0.2;ToonThresholds[3]=0.03;float ToonBrightnessLevels[5];ToonBrightnessLevels[0]=1.0;ToonBrightnessLevels[1]=0.8;ToonBrightnessLevels[2]=0.6;ToonBrightnessLevels[3]=0.35;ToonBrightnessLevels[4]=0.2;if (info.ndl>ToonThresholds[0])\n{diffuseBase.rgb*=ToonBrightnessLevels[0];}\nelse if (info.ndl>ToonThresholds[1])\n{diffuseBase.rgb*=ToonBrightnessLevels[1];}\nelse if (info.ndl>ToonThresholds[2])\n{diffuseBase.rgb*=ToonBrightnessLevels[2];}\nelse if (info.ndl>ToonThresholds[3])\n{diffuseBase.rgb*=ToonBrightnessLevels[3];}\nelse\n{diffuseBase.rgb*=ToonBrightnessLevels[4];}\n#endif\nreturn max(diffuseBase,vec3(0.2));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nlightingInfo info;vec3 diffuseBase=vec3(0.,0.,0.);float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.cellVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class RU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NDOTL=!0,this.CUSTOMUSERLIGHTING=!0,this.CELLBASIC=!0,this.DEPTHPREPASS=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class IU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this._computeHighLevel=!1,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new RU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(r.CELLBASIC=!this.computeHighLevel,qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="cell",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),In(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this._maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}getClassName(){return"CellMaterial"}clone(e){return yt.Clone((()=>new IU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.CellMaterial",e}static Parse(e,t,i){return yt.Parse((()=>new IU(e.name,t)),e,t,i)}}qe([rt("diffuseTexture")],IU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],IU.prototype,"diffuseTexture",void 0),qe([nt("diffuse")],IU.prototype,"diffuseColor",void 0),qe([st("computeHighLevel")],IU.prototype,"_computeHighLevel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],IU.prototype,"computeHighLevel",void 0),qe([st("disableLighting")],IU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],IU.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],IU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],IU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.CellMaterial",IU);class MU{constructor(){}}class OU extends yc{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof Ce?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof Ee?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s);const o=this._createdShaderName;return Ti.ShadersStore[o+"VertexShader"]&&Ti.ShadersStore[o+"PixelShader"]||(Ti.ShadersStore[o+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),Ti.ShadersStore[o+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),o}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const s=i[t];if(s&&s.length>0){const i="#define "+t;e=e.replace(i,"\n"+s+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_UPDATE_DIFFUSE:this.CustomParts.Fragment_Custom_Diffuse,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t),this.CustomParts=new MU,this.customShaderNameResolve=this.Builder,this.FragmentShader=Ti.ShadersStore.defaultPixelShader,this.VertexShader=Ti.ShadersStore.defaultVertexShader,OU.ShaderIndexer++,this._createdShaderName="custom_"+OU.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Fragment_Custom_Diffuse(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}OU.ShaderIndexer=1,ee("BABYLON.CustomMaterial",OU);class DU{constructor(){}}class wU extends Um{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof Ce?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof Ee?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e{if("vertex"===t)return e?e(t,i):i;const s=new U_(i);return s.inlineToken="#define pbr_inline",s.processCode(),e?e(t,s.code):s.code}}n&&this._customAttributes&&this._customAttributes.length>0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s);const a=this._createdShaderName;return Ti.ShadersStore[a+"VertexShader"]&&Ti.ShadersStore[a+"PixelShader"]||(Ti.ShadersStore[a+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),Ti.ShadersStore[a+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),a}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const s=i[t];if(s&&s.length>0){const i="#define "+t;e=e.replace(i,"\n"+s+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.CustomParts.Fragment_Custom_Albedo,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS:this.CustomParts.Fragment_Custom_MetallicRoughness,CUSTOM_FRAGMENT_UPDATE_MICROSURFACE:this.CustomParts.Fragment_Custom_MicroSurface,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:this.CustomParts.Fragment_Before_FinalColorComposition,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t),this.CustomParts=new DU,this.customShaderNameResolve=this.Builder,this.FragmentShader=Ti.ShadersStore.pbrPixelShader,this.VertexShader=Ti.ShadersStore.pbrVertexShader,this.FragmentShader=this.FragmentShader.replace(/#include/g,Ti.IncludesShadersStore.pbrBlockAlbedoOpacity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Ti.IncludesShadersStore.pbrBlockReflectivity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Ti.IncludesShadersStore.pbrBlockFinalColorComposition),wU.ShaderIndexer++,this._createdShaderName="custompbr_"+wU.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_Custom_Albedo(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Custom_MetallicRoughness(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}Fragment_Custom_MicroSurface(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FinalColorComposition(e){return this.CustomParts.Fragment_Before_FinalColorComposition=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}wU.ShaderIndexer=1,ee("BABYLON.PBRCustomMaterial",wU);bi.ShadersStore.firePixelShader="precision highp float;uniform vec4 vEyePosition;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\nuniform sampler2D distortionSampler;uniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec4 bx2(vec4 x)\n{return vec4(2.0)*x-vec4(1.0);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);float alpha=1.0;\n#ifdef DIFFUSE\nconst float distortionAmount0 =0.092;const float distortionAmount1 =0.092;const float distortionAmount2 =0.092;vec2 heightAttenuation=vec2(0.3,0.39);vec4 noise0=texture2D(distortionSampler,vDistortionCoords1);vec4 noise1=texture2D(distortionSampler,vDistortionCoords2);vec4 noise2=texture2D(distortionSampler,vDistortionCoords3);vec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;vec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);vec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;baseColor*=opacityColor;baseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec4 color=vec4(baseColor.rgb,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.fireVertexShader="precision highp float;attribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\nuniform float time;uniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSE\nvDiffuseUV=uv;vDiffuseUV.y-=0.2;\n#endif\n#include\n#include\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;vDistortionCoords1.x=uv.x;vDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;vDistortionCoords2.x=uv.x;vDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;vDistortionCoords3.x=uv.x;vDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class NU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.UV1=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.BonesPerMesh=0,this.NUM_BONE_INFLUENCERS=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class FU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this.speed=1,this._scaledDiffuse=new Ce,this._lastTime=0}needAlphaBlending(){return!1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new NU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(r.ALPHATEST=!!this._opacityTexture,r._areMiscDirty&&(r.POINTSIZE=this.pointsCloud||n.forcePointsCloud,r.FOG=n.fogEnabled&&e.applyFog&&n.fogMode!==dr.FOGMODE_NONE&&this.fogEnabled,r.LOGARITHMICDEPTH=this._useLogarithmicDepth),eo(n,o,this,r,!!i),ro(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.UV1&&s.push(ys.UVKind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="fire",l=["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed"];An(l);const h=r.toString();t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:l,uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),In(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._distortionTexture===e||this._opacityTexture===e}getClassName(){return"FireMaterial"}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new FU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e}static Parse(e,t,i){const s=new FU(e.name,t);return s.diffuseColor=Ce.FromArray(e.diffuseColor),s.speed=e.speed,s.alpha=e.alpha,s.id=e.id,bt.AddTagsTo(s,e.tags),s.backFaceCulling=e.backFaceCulling,s.wireframe=e.wireframe,e._diffuseTexture&&(s._diffuseTexture=Vo.Parse(e._diffuseTexture,t,i)),e._distortionTexture&&(s._distortionTexture=Vo.Parse(e._distortionTexture,t,i)),e._opacityTexture&&(s._opacityTexture=Vo.Parse(e._opacityTexture,t,i)),s}}qe([rt("diffuseTexture")],FU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],FU.prototype,"diffuseTexture",void 0),qe([rt("distortionTexture")],FU.prototype,"_distortionTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],FU.prototype,"distortionTexture",void 0),qe([rt("opacityTexture")],FU.prototype,"_opacityTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],FU.prototype,"opacityTexture",void 0),qe([nt("diffuse")],FU.prototype,"diffuseColor",void 0),qe([st()],FU.prototype,"speed",void 0),ee("BABYLON.FireMaterial",FU);bi.ShadersStore.furPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 furColor;uniform float furLength;varying vec3 vPositionW;varying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform float furOcclusion;uniform sampler2D furTexture;varying vec2 vFurUV;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=furColor;vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));if (furTextureColor.a<=0.0 || furTextureColor.g[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;vec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.furVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\nuniform float furLength;uniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform vec3 furGravity;uniform float furTime;uniform float furSpacing;uniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);vec3 tangent2=vec3(-normal.z,0,normal.x);r=Rand(tangent1*r);float J=(2.0+4.0*r);r=Rand(tangent2*r);float K=(2.0+2.0*r);tangent1=tangent1*J+tangent2*K;tangent1=normalize(tangent1);vec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\nvec3 forceDirection=vec3(0.0,0.0,0.0);forceDirection.x=sin(furTime+position.x*0.05)*0.2;forceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;forceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;vec3 displacement=vec3(0.0,0.0,0.0);displacement=furGravity+forceDirection;float displacementFactor=pow(furOffset,3.0);vec3 aNormal=normal;aNormal.xyz+=displacement*displacementFactor;newPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class BU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.HEIGHTMAP=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.HIGHLEVEL=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class LU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this.furLength=1,this.furAngle=0,this.furColor=new Ce(.44,.21,.02),this.furOffset=0,this.furSpacing=12,this.furGravity=new de(0,0,0),this.furSpeed=100,this.furDensity=20,this.furOcclusion=0,this._disableLighting=!1,this._maxSimultaneousLights=4,this.highLevelFur=!0,this._furTime=0}get furTime(){return this._furTime}set furTime(e){this._furTime=e}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}updateFur(){for(let e=1;e0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="fur",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"];An(h);const c=["diffuseSampler","heightTexture","furTexture"],u=[];co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),In(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e||this._heightTexture===e}dispose(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(let t=1;tnew LU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e}getClassName(){return"FurMaterial"}static Parse(e,t,i){const s=yt.Parse((()=>new LU(e.name,t)),e,t,i);return e.sourceMeshName&&s.highLevelFur&&t.executeWhenReady((()=>{const i=t.getMeshByName(e.sourceMeshName);if(i){const r=LU.GenerateTexture("Fur Texture",t);s.furTexture=r,LU.FurifyMesh(i,e.quality)}})),s}static GenerateTexture(e,t){const i=new Sc("FurTexture "+e,256,t,!0),s=i.getContext();for(let e=0;e<2e4;++e)s.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",s.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=Vo.WRAP_ADDRESSMODE,i.wrapV=Vo.WRAP_ADDRESSMODE,i}static FurifyMesh(e,t){const i=[e],s=e.material;let r;if(!(s instanceof LU))throw"The material of the source mesh must be a Fur Material";for(r=1;r0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="gradient",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","logarithmicDepthConstant","topColor","bottomColor","offset","smoothness","scale"];An(h);const c=[],u=[];co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,n),this._mustRebind(s,n,i)&&(In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new VU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GradientMaterial",e}getClassName(){return"GradientMaterial"}static Parse(e,t,i){return yt.Parse((()=>new VU(e.name,t)),e,t,i)}}qe([st("maxSimultaneousLights")],VU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],VU.prototype,"maxSimultaneousLights",void 0),qe([nt()],VU.prototype,"topColor",void 0),qe([st()],VU.prototype,"topColorAlpha",void 0),qe([nt()],VU.prototype,"bottomColor",void 0),qe([st()],VU.prototype,"bottomColorAlpha",void 0),qe([st()],VU.prototype,"offset",void 0),qe([st()],VU.prototype,"scale",void 0),qe([st()],VU.prototype,"smoothness",void 0),qe([st("disableLighting")],VU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],VU.prototype,"disableLighting",void 0),ee("BABYLON.GradientMaterial",VU);bi.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;uniform float visibility;uniform vec3 mainColor;uniform vec3 lineColor;uniform vec4 gridControl;uniform vec3 gridOffset;varying vec3 vPosition;varying vec3 vNormal;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform vec2 vOpacityInfos;\n#endif\nfloat getDynamicVisibility(float position) {float majorGridFrequency=gridControl.y;if (floor(position+0.5)==floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{return 1.0;}\nreturn gridControl.z;}\nfloat getAnisotropicAttenuation(float differentialLength) {const float maxNumberOfLines=10.0;return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);}\nfloat isPointOnLine(float position,float differentialLength) {float fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \n#ifdef ANTIALIAS\nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);float result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result;\n#else\nreturn abs(fractionPartOfPosition)\n#endif\nfloat opacity=1.0;\n#ifdef TRANSPARENT\nopacity=clamp(grid,0.08,gridControl.w*grid);\n#endif\n#ifdef OPACITY\nopacity*=texture2D(opacitySampler,vOpacityUV).a;\n#endif\ngl_FragColor=vec4(color.rgb,opacity*visibility);\n#ifdef TRANSPARENT\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.gridVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#include\nuniform mat4 projection;uniform mat4 view;varying vec3 vPosition;varying vec3 vNormal;\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\nvec4 cameraSpacePosition=view*worldPos;gl_Position=projection*cameraSpacePosition;\n#ifdef OPACITY\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\nif (vOpacityInfos.x==0.)\n{vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));}\nelse\n{vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));}\n#endif \n#include\nvPosition=position;vNormal=normal;\n#define CUSTOM_VERTEX_MAIN_END\n}";class UU extends Oa{constructor(){super(),this.OPACITY=!1,this.ANTIALIAS=!1,this.TRANSPARENT=!1,this.FOG=!1,this.PREMULTIPLYALPHA=!1,this.MAX_LINE=!1,this.UV1=!1,this.UV2=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class GU extends Ra{constructor(e,t){super(e,t),this.mainColor=Ce.Black(),this.lineColor=Ce.Teal(),this.gridRatio=1,this.gridOffset=de.Zero(),this.majorUnitFrequency=10,this.minorUnitVisibility=.33,this.opacity=1,this.antialias=!0,this.preMultiplyAlpha=!1,this.useMaxLine=!1,this._gridControl=new _e(this.gridRatio,this.majorUnitFrequency,this.minorUnitVisibility,this.opacity)}needAlphaBlending(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()}needAlphaBlendingForMesh(e){return e.visibility<1||this.needAlphaBlending()}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new UU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(r.TRANSPARENT!==this.opacity<1&&(r.TRANSPARENT=!r.TRANSPARENT,r.markAsUnprocessed()),r.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(r.PREMULTIPLYALPHA=!r.PREMULTIPLYALPHA,r.markAsUnprocessed()),r.MAX_LINE!==this.useMaxLine&&(r.MAX_LINE=!r.MAX_LINE,r.markAsUnprocessed()),r.ANTIALIAS!==this.antialias&&(r.ANTIALIAS=!r.ANTIALIAS,r.markAsUnprocessed()),r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._opacityTexture&&lc.OpacityTextureEnabled)){if(!this._opacityTexture.isReady())return!1;r._needUVs=!0,r.OPACITY=!0}if(qn(e,n,this._useLogarithmicDepth,!1,this.fogEnabled,!1,r),eo(n,n.getEngine(),this,r,!!i),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial(),ro(e,r,!1,!1);const i=[ys.PositionKind,ys.NormalKind];r.UV1&&i.push(ys.UVKind),r.UV2&&i.push(ys.UV2Kind),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess,jn(i,r);const s=r.toString();t.setEffect(n.getEngine().createEffect("grid",i,["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility","logarithmicDepthConstant"],["opacitySampler"],s,void 0,this.onCompiled,this.onError),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this._activeEffect.setFloat("visibility",t.visibility),r.INSTANCES&&!r.THIN_INSTANCE||this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",s.getViewMatrix()),this._activeEffect.setMatrix("projection",s.getProjectionMatrix()),this._mustRebind(s,n,i)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&lc.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),this._useLogarithmicDepth&&wn(r,n,s)),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new GU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return yt.Parse((()=>new GU(e.name,t)),e,t,i)}}qe([nt()],GU.prototype,"mainColor",void 0),qe([nt()],GU.prototype,"lineColor",void 0),qe([st()],GU.prototype,"gridRatio",void 0),qe([lt()],GU.prototype,"gridOffset",void 0),qe([st()],GU.prototype,"majorUnitFrequency",void 0),qe([st()],GU.prototype,"minorUnitVisibility",void 0),qe([st()],GU.prototype,"opacity",void 0),qe([st()],GU.prototype,"antialias",void 0),qe([st()],GU.prototype,"preMultiplyAlpha",void 0),qe([st()],GU.prototype,"useMaxLine",void 0),qe([rt("opacityTexture")],GU.prototype,"_opacityTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],GU.prototype,"opacityTexture",void 0),ee("BABYLON.GridMaterial",GU);bi.ShadersStore.lavaPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;uniform float time;uniform float speed;uniform float movingSpeed;uniform vec3 fogColor;uniform sampler2D noiseTexture;uniform float fogDensity;varying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nfloat random( vec3 scale,float seed ){return fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );vec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time *0.02;vec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;T1.x+=noiseTex.x*2.0;T1.y+=noiseTex.y*2.0;T2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;T2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;float p=texture2D( noiseTexture,T1*3.0 ).a;vec4 lavaColor=texture2D( diffuseSampler,T2*4.0);vec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );baseColor=temp;float depth=gl_FragCoord.z*4.0;const float LOG2=1.442695;float fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );fogFactor=1.0-clamp( fogFactor,0.0,1.0 );baseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );diffuseColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.lavaVertexShader="precision highp float;uniform float time;uniform float lowFrequencySpeed;varying float noise;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n/* NOISE FUNCTIONS */\nvec3 mod289(vec3 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 permute(vec4 x)\n{return mod289(((x*34.0)+1.0)*x);}\nvec4 taylorInvSqrt(vec4 r)\n{return 1.79284291400159-0.85373472095314*r;}\nvec3 fade(vec3 t) {return t*t*t*(t*(t*6.0-15.0)+10.0);}\nfloat pnoise(vec3 P,vec3 rep)\n{vec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);Pi1=mod289(Pi1);vec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);vec4 iy=vec4(Pi0.yy,Pi1.yy);vec4 iz0=Pi0.zzzz;vec4 iz1=Pi1.zzzz;vec4 ixy=permute(permute(ix)+iy);vec4 ixy0=permute(ixy+iz0);vec4 ixy1=permute(ixy+iz1);vec4 gx0=ixy0*(1.0/7.0);vec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;gx0=fract(gx0);vec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);vec4 sz0=step(gz0,vec4(0.0));gx0-=sz0*(step(0.0,gx0)-0.5);gy0-=sz0*(step(0.0,gy0)-0.5);vec4 gx1=ixy1*(1.0/7.0);vec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;gx1=fract(gx1);vec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);vec4 sz1=step(gz1,vec4(0.0));gx1-=sz1*(step(0.0,gx1)-0.5);gy1-=sz1*(step(0.0,gy1)-0.5);vec3 g000=vec3(gx0.x,gy0.x,gz0.x);vec3 g100=vec3(gx0.y,gy0.y,gz0.y);vec3 g010=vec3(gx0.z,gy0.z,gz0.z);vec3 g110=vec3(gx0.w,gy0.w,gz0.w);vec3 g001=vec3(gx1.x,gy1.x,gz1.x);vec3 g101=vec3(gx1.y,gy1.y,gz1.y);vec3 g011=vec3(gx1.z,gy1.z,gz1.z);vec3 g111=vec3(gx1.w,gy1.w,gz1.w);vec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));g000*=norm0.x;g010*=norm0.y;g100*=norm0.z;g110*=norm0.w;vec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));g001*=norm1.x;g011*=norm1.y;g101*=norm1.z;g111*=norm1.w;float n000=dot(g000,Pf0);float n100=dot(g100,vec3(Pf1.x,Pf0.yz));float n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));float n110=dot(g110,vec3(Pf1.xy,Pf0.z));float n001=dot(g001,vec3(Pf0.xy,Pf1.z));float n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));float n011=dot(g011,vec3(Pf0.x,Pf1.yz));float n111=dot(g111,Pf1);vec3 fade_xyz=fade(Pf0);vec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);vec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);float n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);return 2.2*n_xyz;}\n/* END FUNCTION */\nfloat turbulence( vec3 p ) {float w=100.0;float t=-.5;for (float f=1.0 ; f<=10.0 ; f++ ){float power=pow( 2.0,f );t+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );}\nreturn t;}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\n#ifdef NORMAL\nnoise=10.0* -.10*turbulence( .5*normal+time*1.15 );float b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );float displacement=- 1.5*noise+b;vec3 newPosition=position+normal*displacement;gl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class zU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.UNLIT=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class WU extends Ra{constructor(e,t){super(e,t),this.speed=1,this.movingSpeed=1,this.lowFrequencySpeed=1,this.fogDensity=.15,this._lastTime=0,this.diffuseColor=new Ce(1,1,1),this._disableLighting=!1,this._unlit=!1,this._maxSimultaneousLights=4,this._scaledDiffuse=new Ce}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new zU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=!0,Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="lava",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"];An(h);const c=["diffuseSampler","noiseTexture"],u=[];co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,r.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=Ce.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new WU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.LavaMaterial",e}getClassName(){return"LavaMaterial"}static Parse(e,t,i){return yt.Parse((()=>new WU(e.name,t)),e,t,i)}}qe([rt("diffuseTexture")],WU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],WU.prototype,"diffuseTexture",void 0),qe([rt()],WU.prototype,"noiseTexture",void 0),qe([nt()],WU.prototype,"fogColor",void 0),qe([st()],WU.prototype,"speed",void 0),qe([st()],WU.prototype,"movingSpeed",void 0),qe([st()],WU.prototype,"lowFrequencySpeed",void 0),qe([st()],WU.prototype,"fogDensity",void 0),qe([nt()],WU.prototype,"diffuseColor",void 0),qe([st("disableLighting")],WU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],WU.prototype,"disableLighting",void 0),qe([st("unlit")],WU.prototype,"_unlit",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],WU.prototype,"unlit",void 0),qe([st("maxSimultaneousLights")],WU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],WU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.LavaMaterial",WU);bi.ShadersStore.mixPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D mixMap1Sampler;uniform vec2 vTextureInfos;\n#ifdef MIXMAP2\nuniform sampler2D mixMap2Sampler;\n#endif\nuniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform sampler2D diffuse4Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;uniform vec2 diffuse4Infos;\n#ifdef MIXMAP2\nuniform sampler2D diffuse5Sampler;uniform sampler2D diffuse6Sampler;uniform sampler2D diffuse7Sampler;uniform sampler2D diffuse8Sampler;uniform vec2 diffuse5Infos;uniform vec2 diffuse6Infos;uniform vec2 diffuse7Infos;uniform vec2 diffuse8Infos;\n#endif\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 finalMixColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef MIXMAP2\nvec4 mixColor2=vec4(1.,1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec4 mixColor=texture2D(mixMap1Sampler,vTextureUV);\n#include\nmixColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);vec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);diffuse1Color.rgb*=mixColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);diffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a);\n#ifdef MIXMAP2\nmixColor=texture2D(mixMap2Sampler,vTextureUV);mixColor.rgb*=vTextureInfos.y;vec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);vec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);vec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);vec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);diffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);diffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);diffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a);\n#endif\n#endif\n#ifdef VERTEXCOLOR\nfinalMixColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.mixVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class HU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.MIXMAP2=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class XU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new HU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this._mixTexture1||!this._mixTexture1.isReady())return!1;if(r._needUVs=!0,lc.DiffuseTextureEnabled){if(!this._diffuseTexture1||!this._diffuseTexture1.isReady())return!1;if(r.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())return!1;if(!this._diffuseTexture3||!this._diffuseTexture3.isReady())return!1;if(!this._diffuseTexture4||!this._diffuseTexture4.isReady())return!1;if(this._mixTexture2){if(!this._mixTexture2.isReady())return!1;if(r.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())return!1;if(!this._diffuseTexture6||!this._diffuseTexture6.isReady())return!1;if(!this._diffuseTexture7||!this._diffuseTexture7.isReady())return!1;if(!this._diffuseTexture8||!this._diffuseTexture8.isReady())return!1}}}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="mix",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","logarithmicDepthConstant","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],c=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),lc.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),lc.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture1&&e.push(this._mixTexture1),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._diffuseTexture4&&e.push(this._diffuseTexture4),this._mixTexture2&&e.push(this._mixTexture2),this._diffuseTexture5&&e.push(this._diffuseTexture5),this._diffuseTexture6&&e.push(this._diffuseTexture6),this._diffuseTexture7&&e.push(this._diffuseTexture7),this._diffuseTexture8&&e.push(this._diffuseTexture8),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture1===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._diffuseTexture4===e||this._mixTexture2===e||this._diffuseTexture5===e||this._diffuseTexture6===e||this._diffuseTexture7===e||this._diffuseTexture8===e}dispose(e){this._mixTexture1&&this._mixTexture1.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new XU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MixMaterial",e}getClassName(){return"MixMaterial"}static Parse(e,t,i){return yt.Parse((()=>new XU(e.name,t)),e,t,i)}}qe([rt("mixTexture1")],XU.prototype,"_mixTexture1",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"mixTexture1",void 0),qe([rt("mixTexture2")],XU.prototype,"_mixTexture2",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"mixTexture2",void 0),qe([rt("diffuseTexture1")],XU.prototype,"_diffuseTexture1",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture1",void 0),qe([rt("diffuseTexture2")],XU.prototype,"_diffuseTexture2",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture2",void 0),qe([rt("diffuseTexture3")],XU.prototype,"_diffuseTexture3",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture3",void 0),qe([rt("diffuseTexture4")],XU.prototype,"_diffuseTexture4",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture4",void 0),qe([rt("diffuseTexture1")],XU.prototype,"_diffuseTexture5",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture5",void 0),qe([rt("diffuseTexture2")],XU.prototype,"_diffuseTexture6",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture6",void 0),qe([rt("diffuseTexture3")],XU.prototype,"_diffuseTexture7",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture7",void 0),qe([rt("diffuseTexture4")],XU.prototype,"_diffuseTexture8",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture8",void 0),qe([nt()],XU.prototype,"diffuseColor",void 0),qe([nt()],XU.prototype,"specularColor",void 0),qe([st()],XU.prototype,"specularPower",void 0),qe([st("disableLighting")],XU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],XU.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],XU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],XU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.MixMaterial",XU);bi.ShadersStore.normalPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef LIGHTING\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef LIGHTING\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse= baseColor.rgb;\n#endif\nvec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.normalVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class YU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.LIGHTING=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class QU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaBlendingForMesh(e){return this.needAlphaBlending()||e.visibility<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new YU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=!0,Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),r.LIGHTING=!this._disableLighting,ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),Qn(s,e,r,i),jn(s,r);const a="normal",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new QU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.NormalMaterial",e}getClassName(){return"NormalMaterial"}static Parse(e,t,i){return yt.Parse((()=>new QU(e.name,t)),e,t,i)}}qe([rt("diffuseTexture")],QU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],QU.prototype,"diffuseTexture",void 0),qe([nt()],QU.prototype,"diffuseColor",void 0),qe([st("disableLighting")],QU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],QU.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],QU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],QU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.NormalMaterial",QU);bi.ShadersStore.shadowOnlyPixelShader="precision highp float;uniform vec4 vEyePosition;uniform float alpha;uniform vec3 shadowColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0..1]\nvec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.shadowOnlyVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class jU extends Oa{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class KU extends Ra{constructor(e,t){super(e,t),this._needAlphaBlending=!0,this.shadowColor=Ce.Black()}needAlphaBlending(){return this._needAlphaBlending}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}get activeLight(){return this._activeLight}set activeLight(e){this._activeLight=e}_getFirstShadowLightForMesh(e){for(const t of e.lightSources)if(t.shadowEnabled)return t;return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new jU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(this._activeLight)for(const t of e.lightSources)if(t.shadowEnabled){if(this._activeLight===t)break;const i=e.lightSources.indexOf(this._activeLight);-1!==i&&(e.lightSources.splice(i,1),e.lightSources.splice(0,0,this._activeLight));break}eo(n,o,this,r,!!i),qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,1);const a=this._getFirstShadowLightForMesh(e)?.getShadowGenerator();if(this._needAlphaBlending=!0,a&&a.getClassName&&"CascadedShadowGenerator"===a.getClassName()){const e=a;this._needAlphaBlending=!e.autoCalcDepthBounds}if(ro(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,1),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),Qn(s,e,r,i),jn(s,r);const a="shadowOnly",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones","logarithmicDepthConstant"],c=[],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:1}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),s.lightsEnabled){Yn(s,t,this._activeEffect,r,1);const e=this._getFirstShadowLightForMesh(t);e&&(e._renderId=-1)}(s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE||r.SHADOWCSM0)&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i)}}clone(e){return yt.Clone((()=>new KU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.ShadowOnlyMaterial",e}getClassName(){return"ShadowOnlyMaterial"}static Parse(e,t,i){return yt.Parse((()=>new KU(e.name,t)),e,t,i)}}ee("BABYLON.ShadowOnlyMaterial",KU);bi.ShadersStore.simplePixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.simpleVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class $U extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class qU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new $U);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="simple",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new qU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SimpleMaterial",e}getClassName(){return"SimpleMaterial"}static Parse(e,t,i){return yt.Parse((()=>new qU(e.name,t)),e,t,i)}}qe([rt("diffuseTexture")],qU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],qU.prototype,"diffuseTexture",void 0),qe([nt("diffuse")],qU.prototype,"diffuseColor",void 0),qe([st("disableLighting")],qU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],qU.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],qU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],qU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.SimpleMaterial",qU);bi.ShadersStore.skyPixelShader="precision highp float;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\nuniform vec3 cameraPosition;uniform vec3 cameraOffset;uniform vec3 up;uniform float luminance;uniform float turbidity;uniform float rayleigh;uniform float mieCoefficient;uniform float mieDirectionalG;uniform vec3 sunPosition;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nconst float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float pn=0.035;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 K=vec3(0.686,0.678,0.666);const float v=4.0;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float EE=1000.0;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float cutoffAngle=pi/1.95;const float steepness=1.5;vec3 totalRayleigh(vec3 lambda)\n{return (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));}\nvec3 simplifiedRayleigh()\n{return 0.0005/vec3(94,40,18);}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{float c=(0.2*T )*10E-18;return 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;}\nfloat hgPhase(float cosTheta,float g)\n{return (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));}\nfloat sunIntensity(float zenithAngleCos)\n{return EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));}\nfloat A=0.15;float B=0.50;float C=0.10;float D=0.20;float EEE=0.02;float F=0.30;float W=1000.0;vec3 Uncharted2Tonemap(vec3 x)\n{return ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;}\n#if DITHER\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));vec3 sunDirection=normalize(sunPosition);float sunE=sunIntensity(dot(sunDirection,up));vec3 betaR=simplifiedRayleigh()*rayleighCoefficient;vec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;float zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));float sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));vec3 Fex=exp(-(betaR*sR+betaM*sM));float cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=betaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=betaM*mPhase;vec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));vec3 direction=normalize(vPositionW-cameraPosition);float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(sunE*19000.0*Fex)*sundisk;vec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));vec3 texColor=(Lin+L0);texColor*=0.04 ;texColor+=vec3(0.0,0.001,0.0025)*0.3;float g_fMaxLuminance=1.0;float fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;vec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);vec3 retColor=curr*whiteScale;/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if DITHER\nretColor.rgb+=dither(gl_FragCoord.xy,0.5);\n#endif\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.skyVertexShader="precision highp float;attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\nuniform mat4 world;uniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=viewProjection*world*vec4(position,1.0);vec4 worldPos=world*vec4(position,1.0);vPositionW=vec3(worldPos);\n#include\n#include\n#include\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class ZU extends Oa{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.DITHER=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class JU extends Ra{constructor(e,t){super(e,t),this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.sunPosition=new de(0,100,0),this.useSunPosition=!1,this.cameraOffset=de.Zero(),this.up=de.Up(),this.dithering=!1,this._cameraPosition=de.Zero(),this._skyOrientation=new pe}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new ZU);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(qn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,s),ro(e,s,!0,!1),s.IMAGEPROCESSINGPOSTPROCESS!==r.imageProcessingConfiguration.applyByPostProcess&&s.markAsMiscDirty(),s.DITHER!==this.dithering&&s.markAsMiscDirty(),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess,s.DITHER=this.dithering;const i=[ys.PositionKind];s.VERTEXCOLOR&&i.push(ys.ColorKind);const n="sky",o=["world","viewProjection","view","vFogInfos","vFogColor","logarithmicDepthConstant","pointSize","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset","up"];An(o);const a=s.toString();t.setEffect(r.getEngine().createEffect(n,i,o,[],a,e,this.onCompiled,this.onError),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n,i)&&(In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s)),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect);const o=s.activeCamera;if(o){const e=o.getWorldMatrix();this._cameraPosition.x=e.m[12],this._cameraPosition.y=e.m[13],this._cameraPosition.z=e.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this._activeEffect.setVector3("up",this.up),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){const e=Math.PI*(this.inclination-.5),t=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(t)*Math.cos(e),this.sunPosition.y=this.distance*Math.sin(-e),this.sunPosition.z=this.distance*Math.sin(t)*Math.cos(e),pe.FromUnitVectorsToRef(de.UpReadOnly,this.up,this._skyOrientation),this.sunPosition.rotateByQuaternionToRef(this._skyOrientation,this.sunPosition)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect,i)}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new JU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SkyMaterial",e}getClassName(){return"SkyMaterial"}static Parse(e,t,i){return yt.Parse((()=>new JU(e.name,t)),e,t,i)}}qe([st()],JU.prototype,"luminance",void 0),qe([st()],JU.prototype,"turbidity",void 0),qe([st()],JU.prototype,"rayleigh",void 0),qe([st()],JU.prototype,"mieCoefficient",void 0),qe([st()],JU.prototype,"mieDirectionalG",void 0),qe([st()],JU.prototype,"distance",void 0),qe([st()],JU.prototype,"inclination",void 0),qe([st()],JU.prototype,"azimuth",void 0),qe([lt()],JU.prototype,"sunPosition",void 0),qe([st()],JU.prototype,"useSunPosition",void 0),qe([lt()],JU.prototype,"cameraOffset",void 0),qe([lt()],JU.prototype,"up",void 0),qe([st()],JU.prototype,"dithering",void 0),ee("BABYLON.SkyMaterial",JU);bi.ShadersStore.terrainPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D textureSampler;uniform vec2 vTextureInfos;uniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;uniform sampler2D bump2Sampler;uniform sampler2D bump3Sampler;\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));return mat3(tangent*invmax,binormal*invmax,normal);}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{vec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;vec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;vec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;bump1Color.rgb*=mixColor.r;bump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);vec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);map=map*255./127.-128./127.;mat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);return normalize(TBN*map);}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);diffuse1Color.rgb*=baseColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);baseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.terrainVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class eG extends Oa{constructor(){super(),this.DIFFUSE=!1,this.BUMP=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class tG extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new eG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(r._needUVs=!0,lc.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady())return!1;if(!this.diffuseTexture2||!this.diffuseTexture2.isReady())return!1;if(!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;r.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&lc.BumpTextureEnabled){if(!this.bumpTexture1.isReady())return!1;if(!this.bumpTexture2.isReady())return!1;if(!this.bumpTexture3.isReady())return!1;r._needNormals=!0,r.BUMP=!0}}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="terrain",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],c=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler","logarithmicDepthConstant"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),lc.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),lc.BumpTextureEnabled&&s.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._bumpTexture1===e||this._bumpTexture2===e||this._bumpTexture3===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new tG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TerrainMaterial",e}getClassName(){return"TerrainMaterial"}static Parse(e,t,i){return yt.Parse((()=>new tG(e.name,t)),e,t,i)}}qe([rt("mixTexture")],tG.prototype,"_mixTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"mixTexture",void 0),qe([rt("diffuseTexture1")],tG.prototype,"_diffuseTexture1",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"diffuseTexture1",void 0),qe([rt("diffuseTexture2")],tG.prototype,"_diffuseTexture2",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"diffuseTexture2",void 0),qe([rt("diffuseTexture3")],tG.prototype,"_diffuseTexture3",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"diffuseTexture3",void 0),qe([rt("bumpTexture1")],tG.prototype,"_bumpTexture1",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"bumpTexture1",void 0),qe([rt("bumpTexture2")],tG.prototype,"_bumpTexture2",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"bumpTexture2",void 0),qe([rt("bumpTexture3")],tG.prototype,"_bumpTexture3",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"bumpTexture3",void 0),qe([nt()],tG.prototype,"diffuseColor",void 0),qe([nt()],tG.prototype,"specularColor",void 0),qe([st()],tG.prototype,"specularPower",void 0),qe([st("disableLighting")],tG.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],tG.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],tG.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],tG.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.TerrainMaterial",tG);bi.ShadersStore.triplanarPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;uniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;uniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;uniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(0.,0.,0.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);normalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.triplanarVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\nvec3 xtan=vec3(0,0,1);vec3 xbin=vec3(0,1,0);vec3 ytan=vec3(1,0,0);vec3 ybin=vec3(0,0,1);vec3 ztan=vec3(1,0,0);vec3 zbin=vec3(0,1,0);vec3 normalizedNormal=normalize(normal);normalizedNormal*=normalizedNormal;vec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);vec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);mat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nworldTangent=normalize((normalWorld*worldTangent).xyz);worldBinormal=normalize((normalWorld*worldBinormal).xyz);vec3 worldNormal=normalize((normalWorld*normalize(normal)).xyz);tangentSpace[0]=worldTangent;tangentSpace[1]=worldBinormal;tangentSpace[2]=worldNormal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class iG extends Oa{constructor(){super(),this.DIFFUSEX=!1,this.DIFFUSEY=!1,this.DIFFUSEZ=!1,this.BUMPX=!1,this.BUMPY=!1,this.BUMPZ=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.NONUNIFORMSCALING=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class sG extends Ra{constructor(e,t){super(e,t),this.tileSize=1,this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(.2,.2,.2),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new iG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&n.texturesEnabled){if(lc.DiffuseTextureEnabled){const e=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],t=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"];for(let i=0;i0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="triplanar",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","tileSize"],c=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ","logarithmicDepthConstant"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),this._mustRebind(s,n,i)&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTextureX===e||this._diffuseTextureY===e||this._diffuseTextureZ===e||this._normalTextureX===e||this._normalTextureY===e||this._normalTextureZ===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new sG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TriPlanarMaterial",e}getClassName(){return"TriPlanarMaterial"}static Parse(e,t,i){return yt.Parse((()=>new sG(e.name,t)),e,t,i)}}qe([rt()],sG.prototype,"mixTexture",void 0),qe([rt("diffuseTextureX")],sG.prototype,"_diffuseTextureX",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"diffuseTextureX",void 0),qe([rt("diffuseTexturY")],sG.prototype,"_diffuseTextureY",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"diffuseTextureY",void 0),qe([rt("diffuseTextureZ")],sG.prototype,"_diffuseTextureZ",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"diffuseTextureZ",void 0),qe([rt("normalTextureX")],sG.prototype,"_normalTextureX",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"normalTextureX",void 0),qe([rt("normalTextureY")],sG.prototype,"_normalTextureY",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"normalTextureY",void 0),qe([rt("normalTextureZ")],sG.prototype,"_normalTextureZ",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"normalTextureZ",void 0),qe([st()],sG.prototype,"tileSize",void 0),qe([nt()],sG.prototype,"diffuseColor",void 0),qe([nt()],sG.prototype,"specularColor",void 0),qe([st()],sG.prototype,"specularPower",void 0),qe([st("disableLighting")],sG.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],sG.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],sG.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],sG.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.TriPlanarMaterial",sG);bi.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform sampler2D normalSampler;uniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;uniform sampler2D reflectionSampler;const float LOG2=1.442695;uniform vec3 cameraPosition;uniform vec4 waterColor;uniform float colorBlendFactor;uniform vec4 waterColor2;uniform float colorBlendFactor2;uniform float bumpHeight;uniform float time;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));if (normalW.y<0.0) {normalW.y=-normalW.y;}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);vec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);float IfresnelTerm=1.0-fresnelTerm;refractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;reflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;baseColor=combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=max(dot(viewDirectionW,upVector),0.0);vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);baseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#elif defined(IMAGEPROCESSING)\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.waterVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;uniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\nuniform mat4 reflectionViewProjection;uniform vec2 windDirection;uniform float waveLength;uniform float time;uniform float windForce;uniform float waveHeight;uniform float waveSpeed;uniform float waveCount;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x==0.)\n{vNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{vNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\nfloat finalWaveCount=1.0/(waveCount*0.5);\n#ifdef USE_WORLD_COORDINATES\nvec3 p=worldPos.xyz;\n#else\nvec3 p=position;\n#endif\nfloat newY=(sin(((p.x/finalWaveCount)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+ (cos(((p.z/finalWaveCount)+ time*waveSpeed))*waveHeight*windDirection.y*5.0);p.y+=abs(newY);\n#ifdef USE_WORLD_COORDINATES\ngl_Position=viewProjection*vec4(p,1.0);\n#else\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#endif\n#ifdef REFLECTION\nvRefractionMapTexCoord.x=0.5*(gl_Position.w+gl_Position.x);vRefractionMapTexCoord.y=0.5*(gl_Position.w+gl_Position.y);vRefractionMapTexCoord.z=gl_Position.w;worldPos=reflectionViewProjection*finalWorld*vec4(position,1.0);vReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);vReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);vReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class rG extends Oa{constructor(){super(),this.BUMP=!1,this.REFLECTION=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class nG extends Ra{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new ue(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new ue(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new Ce(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new Ce(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new ds(16),this._mesh=null,this._reflectionTransform=fe.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);-1!==t&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);-1!==t&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&0===this._refractionRTT.refreshRate)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new rG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled)){if(this.bumpTexture&&lc.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;r._needUVs=!0,r.BUMP=!0}lc.ReflectionTextureEnabled&&(r.REFLECTION=!0)}if(eo(n,o,this,r,!!i),qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._areMiscDirty&&(r.FRESNELSEPARATE=this._fresnelSeparate,r.BUMPSUPERIMPOSE=this._bumpSuperimpose,r.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,r.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),r._needNormals=Zn(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(ro(e,r,!0,!0),this._mesh=e,this._waitingRenderList){for(let e=0;e0&&i.addCPUSkinningFallback(0,e);const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="water",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],c=["normalSampler","refractionSampler","reflectionSampler"],u=[];xs&&(xs.PrepareUniforms(h,r),xs.PrepareSamplers(c,r)),An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.bumpTexture&&lc.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),wn(r,this._activeEffect,s),lc.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(s.getProjectionMatrix()),a=s.getEngine().getDeltaTime();a!==this._lastDeltaTime&&(this._lastDeltaTime=a,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect,i)}_createRenderTargets(e,t){let i;this._refractionRTT=new pl(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=Yd.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=Yd.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0,this._reflectionRTT=new pl(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=Yd.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=Yd.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let s,r=null;const n=fe.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){r=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=ir.FromPositionAndNormal(new de(0,t+.05,0),new de(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),this.disableClipPlane||(e.clipPlane=r)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){r=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=ir.FromPositionAndNormal(new de(0,t-.05,0),new de(0,-1,0)),fe.ReflectionToRef(e.clipPlane,n)}s=e.getViewMatrix(),n.multiplyToRef(s,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=de.TransformCoordinates(e.activeCamera.position,n)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),e.clipPlane=r,e.setTransformMatrix(s,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._bumpTexture===e}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=t&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=t&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return yt.Clone((()=>new nG(e,this.getScene())),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew nG(e.name,t)),e,t,i);return s._waitingRenderList=e.renderList,s}static CreateDefaultMesh(e,t){return Uc(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}qe([rt("bumpTexture")],nG.prototype,"_bumpTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],nG.prototype,"bumpTexture",void 0),qe([nt()],nG.prototype,"diffuseColor",void 0),qe([nt()],nG.prototype,"specularColor",void 0),qe([st()],nG.prototype,"specularPower",void 0),qe([st("disableLighting")],nG.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],nG.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],nG.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],nG.prototype,"maxSimultaneousLights",void 0),qe([st()],nG.prototype,"windForce",void 0),qe([at()],nG.prototype,"windDirection",void 0),qe([st()],nG.prototype,"waveHeight",void 0),qe([st()],nG.prototype,"bumpHeight",void 0),qe([st("bumpSuperimpose")],nG.prototype,"_bumpSuperimpose",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],nG.prototype,"bumpSuperimpose",void 0),qe([st("fresnelSeparate")],nG.prototype,"_fresnelSeparate",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],nG.prototype,"fresnelSeparate",void 0),qe([st("bumpAffectsReflection")],nG.prototype,"_bumpAffectsReflection",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],nG.prototype,"bumpAffectsReflection",void 0),qe([nt()],nG.prototype,"waterColor",void 0),qe([st()],nG.prototype,"colorBlendFactor",void 0),qe([nt()],nG.prototype,"waterColor2",void 0),qe([st()],nG.prototype,"colorBlendFactor2",void 0),qe([st()],nG.prototype,"waveLength",void 0),qe([st()],nG.prototype,"waveSpeed",void 0),qe([st()],nG.prototype,"waveCount",void 0),qe([st()],nG.prototype,"disableClipPlane",void 0),qe([st("useWorldCoordinatesForWaveDeformation")],nG.prototype,"_useWorldCoordinatesForWaveDeformation",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],nG.prototype,"useWorldCoordinatesForWaveDeformation",void 0),ee("BABYLON.WaterMaterial",nG);var oG,aG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class lG{constructor(e,t,i,s,r,n,o,a,l,h){this.point=e,this.line=t,this.polyline=i,this.node=s,this.verbCurve=r,this.verbSurface=n,this.jscad=o,this.occt=a,this.tag=l,this.context=h,this.defaultBasicOptions=new gV.DrawBasicGeometryOptions,this.defaultNodeOptions={colorX:"#ff0000",colorY:"#00ff00",colorZ:"#0000ff",size:2}}drawAnyAsyncNoReturn(e){return aG(this,void 0,void 0,(function*(){this.drawAnyAsync(e)}))}drawAnyAsync(e){return aG(this,void 0,void 0,(function*(){const t=e.entity;return void 0===t||Array.isArray(t)&&0===t.length?Promise.resolve(void 0):this.detectJscadMesh(t)?this.handleJscadMesh(e):this.detectOcctShape(t)?this.handleOcctShape(e):this.detectOcctShapes(t)?this.handleOcctShapes(e):this.detectJscadMeshes(t)?this.handleJscadMeshes(e):Promise.resolve(this.drawAny(e))}))}updateAny(e){let t;if(e.babylonMesh&&e.babylonMesh.metadata)switch(e.babylonMesh.metadata.type){case gV.drawingTypes.point:t=this.handlePoint(e);break;case gV.drawingTypes.points:t=this.handlePoints(e);break;case gV.drawingTypes.line:t=this.handleLine(e);break;case gV.drawingTypes.lines:t=this.handleLines(e);break;case gV.drawingTypes.polyline:t=this.handlePolyline(e);break;case gV.drawingTypes.polylines:t=this.handlePolylines(e);break;case gV.drawingTypes.verbCurve:t=this.handleVerbCurve(e);break;case gV.drawingTypes.verbCurves:t=this.handleVerbCurves(e);break;case gV.drawingTypes.verbSurface:t=this.handleVerbSurface(e);break;case gV.drawingTypes.verbSurfaces:t=this.handleVerbSurfaces(e);break;case gV.drawingTypes.tag:t=this.handleTag(e);break;case gV.drawingTypes.tags:t=this.handleTags(e);break;case gV.drawingTypes.node:t=this.handleNode(e);break;case gV.drawingTypes.nodes:t=this.handleNodes(e)}return t}drawAnyNoReturn(e){this.drawAny(e)}drawAny(e){let t;const i=e.entity;return e.babylonMesh?t=this.updateAny(e):this.detectLine(i)?t=this.handleLine(e):this.detectPoint(i)?t=this.handlePoint(e):this.detectPolyline(i)?t=this.handlePolyline(e):this.detectNode(i)?t=this.handleNode(e):this.detectVerbCurve(i)?t=this.handleVerbCurve(e):this.detectVerbSurface(i)?t=this.handleVerbSurface(e):this.detectPolylines(i)?t=this.handlePolylines(e):this.detectLines(i)?t=this.handleLines(e):this.detectPoints(i)?t=this.handlePoints(e):this.detectNodes(i)?t=this.handleNodes(e):this.detectVerbCurves(i)?t=this.handleVerbCurves(e):this.detectVerbSurfaces(i)?t=this.handleVerbSurfaces(e):this.detectTag(i)?t=this.handleTag(e):this.detectTags(i)&&(t=this.handleTags(e)),t}drawGridMeshNoReturn(e){this.drawGridMesh(e)}drawGridMesh(e){try{const t=new GU(`groundMaterial${Math.random()}`,this.context.scene);t.majorUnitFrequency=e.majorUnitFrequency,t.minorUnitVisibility=e.minorUnitVisibility,t.gridRatio=e.gridRatio,t.backFaceCulling=e.backFaceCulling,t.mainColor=Ce.FromHexString(e.mainColor),t.lineColor=Ce.FromHexString(e.secondaryColor),t.opacity=e.opacity;const i=Gd.CreateGround(`bitbybit-ground${Math.random()}`,{width:e.width,height:e.height,subdivisions:e.subdivisions,updatable:!1},this.context.scene);return i.material=t,i}catch(e){return console.log("Error happened: ",e),new bo("error-ground",this.context.scene)}}optionsSimple(e){return e}optionsOcctShape(e){return e}optionsOcctShapeSimple(e){return e}optionsOcctShapeMaterial(e){return e}optionsBabylonNode(e){return e}handleTags(e){const t=e.options?e.options:{updatable:!1},i=this.tag.drawTags(Object.assign({tagsVariable:e.babylonMesh,tags:e.entity},t));return i.metadata={type:gV.drawingTypes.tags,options:t},i}handleTag(e){let t=e.options?e.options:{updatable:!1};!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.tag.drawTag(Object.assign({tagVariable:e.babylonMesh,tag:e.entity},t));return i.metadata={type:gV.drawingTypes.tag,options:t},i}handleVerbSurfaces(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbSurface.drawSurfacesMultiColour(Object.assign({surfacesMesh:e.babylonMesh,surfaces:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.verbSurfaces,t,i),i}handleVerbCurves(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbCurve.drawCurves(Object.assign({curvesMesh:e.babylonMesh,curves:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.verbCurves,t,i),i}handleNodes(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNodes(Object.assign({nodes:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.nodes,t,i),i}handlePoints(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.point.drawPoints(Object.assign({pointsMesh:e.babylonMesh,points:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.points,t,i),i}handleLines(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity.map((e=>({points:[e.start,e.end]})))},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.lines,t,i),i}handlePolylines(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.polylines,t,i),i}handleVerbSurface(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbSurface.drawSurface(Object.assign({surfaceMesh:e.babylonMesh,surface:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.verbSurface,t,i),i}handleVerbCurve(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbCurve.drawCurve(Object.assign({curveMesh:e.babylonMesh,curve:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.verbCurve,t,i),i}handleNode(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNode(Object.assign({node:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.node,t,i),i}handlePolyline(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolyline(Object.assign({polylineMesh:e.babylonMesh,polyline:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.polyline,t,i),i}handlePoint(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.point.drawPoint(Object.assign({pointMesh:e.babylonMesh,point:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.point,t,i),i}handleLine(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:[{points:[e.entity.start,e.entity.end]}]},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.line,t,i),i}handleJscadMeshes(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.jscad.drawSolidOrPolygonMeshes(Object.assign({jscadMesh:e.babylonMesh,meshes:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.jscadMeshes,t,e),e)))}handleOcctShape(e){let t=e.options?e.options:new rk.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.occt.drawShape(Object.assign(Object.assign({shape:e.entity},new gV.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.occt,t,e),e)))}handleOcctShapes(e){let t=e.options?e.options:new rk.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.occt.drawShapes(Object.assign(Object.assign({shapes:e.entity},new gV.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.occt,t,e),e)))}handleJscadMesh(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.jscad.drawSolidOrPolygonMesh(Object.assign({jscadMesh:e.babylonMesh,mesh:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.jscadMesh,t,e),e)))}applyGlobalSettingsAndMetadataAndShadowCasting(e,t,i){const s={type:e,options:t},r=this.context.scene.metadata.shadowGenerators;i.isPickable=!1,i.getChildMeshes().forEach((e=>{e.isPickable=!1})),r.length>0&&(i.receiveShadows=!0,r.forEach((e=>e.addShadowCaster(i))),i.getChildMeshes().forEach((e=>{e.receiveShadows=!0,r.forEach((t=>t.addShadowCaster(e)))}))),i.metadata=i.metadata?Object.assign(Object.assign({},i.metadata),s):s}detectPoint(e){return Array.isArray(e)&&3===e.length&&this.checkIfElementsInArrayAreNumbers(e)}detectPoints(e){return Array.isArray(e)&&this.checkIfElementsInArrayAreArrays(e)&&this.arraysInChildrenArraysContainNumbers(e)&&this.arraysInChildrenArraysAreOfLength3(e)}detectLine(e){return e.start&&e.end&&Array.isArray(e.start)&&Array.isArray(e.end)}detectLines(e){return Array.isArray(e)&&!e.some((e=>!this.detectLine(e)))}detectPolyline(e){return e.points&&Array.isArray(e.points)}detectPolylines(e){return Array.isArray(e)&&!e.some((e=>!this.detectPolyline(e)))}detectNode(e){return!Array.isArray(e)&&e.id&&e.id.includes("node")}detectNodes(e){return Array.isArray(e)&&!e.some((e=>!this.detectNode(e)))}detectVerbCurve(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.knots&&e._data.degree}detectVerbSurface(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.degreeU&&e._data.degreeV&&e._data.knotsU&&e._data.knotsV}detectVerbCurves(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbCurve(e)))}detectVerbSurfaces(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbSurface(e)))}detectJscadMesh(e){return!Array.isArray(e)&&(e.sides||e.polygons)}detectJscadMeshes(e){return Array.isArray(e)&&!e.some((e=>!this.detectJscadMesh(e)))}detectOcctShape(e){return"occ-shape"===(null==e?void 0:e.type)}detectOcctShapes(e){return Array.isArray(e)&&!e.some((e=>!this.detectOcctShape(e)))}detectTag(e){return!Array.isArray(e)&&e.text}detectTags(e){return Array.isArray(e)&&!e.some((e=>!this.detectTag(e)))}checkIfElementsInArrayAreNumbers(e){return!e.some((e=>isNaN(e)))}checkIfElementsInArrayAreArrays(e){return!e.some((e=>!Array.isArray(e)))}arraysInChildrenArraysContainNumbers(e){return!e.some((e=>!this.checkIfElementsInArrayAreNumbers(e)))}arraysInChildrenArraysAreOfLength3(e){return!e.some((e=>3!==e.length))}}class hG{constructor(e,t){this.context=e,this.geometryHelper=t}drawLines(e){const t=[],i=[];return e.lines.forEach(((s,r)=>{let n;t.push([new de(s.start[0],s.start[1],s.start[2]),new de(s.end[0],s.end[1],s.end[2])]),n=Array.isArray(e.colours)&&e.colours.length===e.lines.length?Ce.FromHexString(e.colours[r]):Array.isArray(e.colours)?Ce.FromHexString(e.colours[0]):Ce.FromHexString(e.colours),i.push([new Ee(n.r,n.g,n.b,e.opacity),new Ee(n.r,n.g,n.b,e.opacity)])})),e.linesMesh&&e.updatable?e.linesMesh.getTotalVertices()/2===t.length?e.linesMesh=Gd.CreateLineSystem(null,{lines:t,instance:e.linesMesh,colors:i,useVertexAlpha:!0,updatable:e.updatable},null):(e.linesMesh.dispose(),e.linesMesh=this.createLineSystemMesh(e.updatable,t,i)):e.linesMesh=this.createLineSystemMesh(e.updatable,t,i),this.geometryHelper.edgesRendering(e.linesMesh,e.size,e.opacity,e.colours),e.linesMesh}convertToNurbsCurve(e){return new this.context.verb.geom.Line(e.line.start,e.line.end)}convertLinesToNurbsCurves(e){return e.lines.map((e=>new this.context.verb.geom.Line(e.start,e.end)))}getStartPoint(e){return e.line.start}getEndPoint(e){return e.line.end}length(e){return this.context.verb.core.Vec.dist(e.line.start,e.line.end)}reverse(e){return{start:e.line.end,end:e.line.start}}transformLine(e){const t=e.transformation;let i=[e.line.start,e.line.end];return i=this.geometryHelper.transformControlPoints(t,i),{start:i[0],end:i[1]}}transformsForLines(e){return e.lines.map(((t,i)=>{const s=e.transformation[i];let r=[t.start,t.end];return r=this.geometryHelper.transformControlPoints(s,r),{start:r[0],end:r[1]}}))}create(e){return{start:e.start,end:e.end}}createAsync(e){return Promise.resolve({start:e.start,end:e.end})}getPointOnLine(e){const t=e.line.start,i=e.line.end,s=e.param,r=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];return[t[0]+s*r[0],t[1]+s*r[1],t[2]+s*r[2]]}linesBetweenPoints(e){const t=[];for(let i=1;i({start:t,end:e.endPoints[i]}))).filter((e=>0!==this.context.verb.core.Vec.dist(e.start,e.end)))}linesBetweenStartAndEndPointsAsync(e){return Promise.resolve(this.linesBetweenStartAndEndPoints(e))}createLineSystemMesh(e,t,i){return Gd.CreateLineSystem(`lines${Math.random()}`,{lines:t,colors:i,useVertexAlpha:!0,updatable:e},this.context.scene)}}class cG{getItem(e){if(e.index<0||e.index>=e.list.length)throw new Error("Index out of bounds");let t;return t=e.clone?structuredClone(e.list[e.index]):e.list[e.index],t}getSubList(e){let t;return t=e.clone?structuredClone(e.list.slice(e.indexStart,e.indexEnd)):e.list.slice(e.indexStart,e.indexEnd),t}getNthItem(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let s=0;s=r)t.forEach(((e,t)=>{!0===i[t]&&n.push(e)}));else{const e=[],o=Math.ceil(r/s);for(let t=0;t{!0===e[i]&&n.push(t)}))}return n}mergeElementsOfLists(e){const t=e.lists,i=e.level,s=[],r=[];t.forEach((e=>{const t=e.flat(i);s.push(t)}));const n=this.getLongestListLength({lists:s});for(let e=0;e0&&r.push(t)}let o=[];if(i>0)for(let e=0;e{e.length>t&&(t=e.length)})),t):void 0}reverse(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.reverse()}flipLists(e){if(e.list.length>0){const t=e.list[0].length;let i=!0;if(e.list.forEach((e=>{e.length!==t&&(i=!1)})),i){const i=[];for(let s=0;s{t.push(e[s])})),i.push(t)}return i}throw new Error("Lists are not of the same length")}throw new Error("List is empty")}groupNth(e){return(e=>{const{nrElements:t,list:i,keepRemainder:s}=e,r=t,n=[];let o=[];return i.forEach(((e,t)=>{o.push(e),(t+1)%r==0&&(n.push(o),o=[]),s&&t===i.length-1&&n.push(o)})),n})(e)}getListDepth(e){let t=0,i=!0,s=e.list;for(;i;){let e=!1;for(let t=0;t=0&&e.index<=t.length&&t.splice(e.index,0,e.item),t}addItemAtIndexes(e){let t=e.list;e.clone&&(t=structuredClone(e.list));let i=[...e.indexes];return i=i.filter((e=>e>=0&&e<=t.length)),i.sort(((e,t)=>e-t)),i.forEach(((i,s)=>{i>=0&&i+s<=t.length&&t.splice(i+s,0,e.item)})),t}addItemsAtIndexes(e){if(e.items.length!==e.indexes.length)throw new Error("Items and indexes must have the same length");for(let t=0;t0&&e.indexes[t-1]>e.indexes[t])throw new Error("Indexes must be in ascending order");let t=e.list;return e.clone&&(t=structuredClone(e.list)),[...e.indexes].forEach(((i,s)=>{i>=0&&i+s<=t.length&&t.splice(i+s,0,e.items[s])})),t}removeItemAtIndex(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.index>=0&&e.index<=t.length&&t.splice(e.index,1),t}removeNthItem(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let s=0;s{const s=e.points;return e.isClosed&&s.push(s[0]),e.color&&(Array.isArray(t)||(t=[]),Array.isArray(e.color)?t[i]=Ce.FromArray(e.color).toHexString():t[i]=e.color),s}));return this.geometryHelper.drawPolylines(e.polylinesMesh,i,e.updatable,e.size,e.opacity,t)}convertToNurbsCurve(e){return this.context.verb.geom.NurbsCurve.byPoints(e.polyline.points,1)}length(e){let t=0;for(let i=1;it.id===e.tagVariable.id));Object.keys(e.tag).forEach((i=>{t[i]=e.tag[i]})),t.needsUpdate=!0}else{const t=document.createElement("span"),i="_tag"+(new Date).getTime()+this.context.tagBag.length;e.tag.id=i,t.id=i,t.textContent=e.tag.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(t),e.tag.needsUpdate=!0,this.context.tagBag.push(e.tag)}return e.tag}drawTags(e){if(e.tagsVariable&&e.updatable){if(e.tagsVariable.length{const s=this.context.tagBag.find((e=>e.id===t.id)),r=e.tags[i];if(r)Object.keys(r).forEach((e=>{s[e]=r[e]})),s.needsUpdate=!0;else{this.context.tagBag=this.context.tagBag.filter((e=>e.id!==s.id));const e=document.getElementById(s.id);e.parentNode.removeChild(e)}}))}else{const t=[];e.tags.forEach(((i,s)=>{const r=document.createElement("span"),n="_tag"+(new Date).getTime()+this.context.tagBag.length;i.id=n,r.id=n,r.textContent=i.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(r),i.needsUpdate=!0,this.context.tagBag.push(i),t.push(i),e.tagsVariable=t}))}return e.tagsVariable}}class pG{constructor(e){this.context=e}angleBetween(e){return vr.FromRadians(this.context.verb.core.Vec.angleBetween(e.first,e.second)).degrees()}angleBetweenNormalized2d(e){return vr.FromRadians(this.context.verb.core.Vec.angleBetweenNormalized2d(e.first,e.second)).degrees()}positiveAngleBetween(e){return vr.FromRadians(this.context.verb.core.Vec.positiveAngleBetween(e.first,e.second,e.reference)).degrees()}addAll(e){return this.context.verb.core.Vec.addAll(e.vectors)}add(e){return this.context.verb.core.Vec.add(e.first,e.second)}all(e){return this.context.verb.core.Vec.all(e.vector)}cross(e){return this.context.verb.core.Vec.cross(e.first,e.second)}distSquared(e){return this.context.verb.core.Vec.distSquared(e.first,e.second)}dist(e){return this.context.verb.core.Vec.dist(e.first,e.second)}div(e){return this.context.verb.core.Vec.div(e.vector,e.scalar)}domain(e){return this.context.verb.core.Vec.domain(e.vector)}dot(e){return this.context.verb.core.Vec.dot(e.first,e.second)}finite(e){return this.context.verb.core.Vec.finite(e.vector)}isZero(e){return this.context.verb.core.Vec.isZero(e.vector)}lerp(e){return this.context.verb.core.Vec.lerp(e.fraction,e.first,e.second)}max(e){return this.context.verb.core.Vec.max(e.vector)}min(e){return this.context.verb.core.Vec.min(e.vector)}mul(e){return e.vector.map((t=>t*e.scalar))}neg(e){return this.context.verb.core.Vec.neg(e.vector)}normSquared(e){return this.context.verb.core.Vec.normSquared(e.vector)}norm(e){return this.context.verb.core.Vec.norm(e.vector)}normalized(e){return this.context.verb.core.Vec.normalized(e.vector)}onRay(e){return this.context.verb.core.Vec.onRay(e.point,e.vector,e.distance)}vectorXYZ(e){return[e.x,e.y,e.z]}vectorXY(e){return[e.x,e.y]}range(e){return this.context.verb.core.Vec.range(e.max)}signedAngleBetween(e){return vr.FromRadians(this.context.verb.core.Vec.signedAngleBetween(e.first,e.second,e.reference)).degrees()}span(e){return this.context.verb.core.Vec.span(e.min,e.max,e.step)}sub(e){return this.context.verb.core.Vec.sub(e.first,e.second)}sum(e){return this.context.verb.core.Vec.sum(e.vector)}}class fG{constructor(e){this.context=e,this.tolerance=1e-5,this.getArrayDepth=e=>Array.isArray(e)?1+Math.max(...e.map(this.getArrayDepth)):0}createOrUpdateSurfaceMesh(e,t,i,s,r,n){const o=()=>{const s=new cn;s.positions=e.positions,s.indices=e.indices,s.normals=e.normals,s.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;r&&(e=this.context.scene),t=new bo(`surface${Math.random()}`,e),o(),t.flipFaces(!1),s&&(t.material=s)}return s&&(t.material=s),n&&(t.isVisible=!1),t.isPickable=!1,t}createOrUpdateSurfacesMesh(e,t,i,s,r,n){const o=()=>{const s=e.pop(),r=new cn;r.positions=s.positions,r.indices=s.indices,r.normals=s.normals,r.uvs=s.uvs;const n=[];e.forEach((e=>{const t=new cn;t.positions=e.positions,t.indices=e.indices,t.normals=e.normals,t.uvs=e.uvs,n.push(t)})),r.merge(n),r.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;r&&(e=this.context.scene),t=new bo(`surface${Math.random()}`,e),o(),t.flipFaces(!1),s&&(t.material=s)}return s&&(t.material=s),n&&(t.isVisible=!1),t.isPickable=!1,t}transformControlPoints(e,t){return this.getFlatTransformations(e).forEach((e=>{t=this.transformPointsByMatrixArray(t,e)})),t}getFlatTransformations(e){let t=[];return 3===this.getArrayDepth(e)?e.forEach((e=>{t.push(...e)})):t=e,t}transformPointsByMatrixArray(e,t){const i=fe.FromArray(t);return this.transformPointsByMatrix(e,i)}transformPointsByMatrix(e,t){const i=[];for(const s of e){const e=new de(s[0],s[1],s[2]),r=de.TransformCoordinates(e,t);i.push([r.x,r.y,r.z])}return i}edgesRendering(e,t,i,s){e.enableEdgesRendering(),e.edgesWidth=t;const r=Array.isArray(s)?Ce.FromHexString(s[0]):Ce.FromHexString(s);e.color=r,e.edgesColor=new Ee(r.r,r.g,r.b,i)}drawPolyline(e,t,i,s,r,n){return this.drawPolylines(e,[t],i,s,r,n)}drawPolylines(e,t,i,s,r,n){const o=[];return t&&t.length>0?(t.forEach((e=>{o.push(e.map((e=>new de(e[0],e[1],e[2]))))})),e&&i?e.metadata.linesForRenderLengths.some(((e,t)=>e!==o[t].length))?(e.dispose(),(e=this.createLineSystem(i,o)).metadata={linesForRenderLengths:o.map((e=>e.length))}):e=Gd.CreateLineSystem("line-system"+Math.random(),{lines:o,instance:e,useVertexAlpha:!0,updatable:i},this.context.scene):(e=this.createLineSystem(i,o)).metadata={linesForRenderLengths:o.map((e=>e.length))},this.edgesRendering(e,s,r,n),e):void 0}createLineSystem(e,t){return Gd.CreateLineSystem(`lineSystem${Math.random()}`,{lines:t,useVertexAlpha:!0,updatable:e},this.context.scene)}removeConsecutiveDuplicates(e,t=!0){const i=[];if(e.length>1){for(let t=1;ti[0])))):i=e.points.map((()=>e.colours)),e.pointsMesh&&e.updatable?e.pointsMesh.getChildMeshes().length===t.length?this.updatePointsInstances(e.pointsMesh,t):(e.pointsMesh.dispose(),e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable)):e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable),e.pointsMesh}updatePointsInstances(e,t){const i=e.getChildMeshes(),s={};t.forEach(((e,t)=>{s[t]=new de(e[0],e[1],e[2])})),i.forEach((e=>{e.position=s[e.metadata.index]}))}setUpPositionsAndColours(e,t){const i=[],s=[];return t.length===e.length?e.forEach(((e,r)=>{i.push(...e),s.push(t[r].r,t[r].g,t[r].b,1)})):e.forEach(((e,r)=>{i.push(...e),s.push(t[0].r,t[0].g,t[0].b,1)})),{positions:i,colors:s}}createPointSpheresMesh(e,t,i,s,r,n){const o=t.map(((e,t)=>({position:e,color:i[t],index:t}))),a=Array.from(new Set(i)),l=a.map(((e,t)=>{const i=new yc(`mat${Math.random()}`,this.context.scene);i.disableLighting=!0,i.emissiveColor=Ce.FromHexString(e),i.alpha=s;const r=o.filter((t=>t.color===e));return{hex:a,material:i,positions:r}})),h=new bo(e,this.context.scene);return l.forEach((e=>{const t=Gd.CreateSphere(`sphere${Math.random()}`,{diameter:r,segments:6,updatable:n},this.context.scene);t.material=e.material,t.isVisible=!1,e.positions.forEach(((e,i)=>{const s=t.createInstance(`sphere-${i}-${Math.random()}`);s.position=new de(e.position[0],e.position[1],e.position[2]),s.metadata={index:e.index},s.parent=h,s.isVisible=!0}))})),h}}class mG{constructor(e,t,i){this.context=e,this.geometryHelper=t,this.line=i}drawPoint(e){return this.geometryHelper.drawPoint(e)}drawPoints(e){return this.geometryHelper.drawPoints(e)}drawPointsAsync(e){return Promise.resolve(this.drawPoints(e))}transformPoint(e){const t=e.transformation;let i=[e.point];return i=this.geometryHelper.transformControlPoints(t,i),i[0]}transformPoints(e){return this.geometryHelper.transformControlPoints(e.transformation,e.points)}transformsForPoints(e){if(e.points.length!==e.transformation.length)throw new Error("You must provide equal nr of points and transformations");return e.points.map(((t,i)=>this.geometryHelper.transformControlPoints(e.transformation[i],[t])[0]))}closestPointFromPointsDistance(e){return this.closestPointFromPointData(e).distance}closestPointFromPointsIndex(e){return this.closestPointFromPointData(e).index}closestPointFromPoints(e){return this.closestPointFromPointData(e).point}distance(e){const t=e.endPoint[0]-e.startPoint[0],i=e.endPoint[1]-e.startPoint[1],s=e.endPoint[2]-e.startPoint[2];return Math.sqrt(t*t+i*i+s*s)}distancesToPoints(e){return e.endPoints.map((t=>this.distance({startPoint:e.startPoint,endPoint:t})))}multiplyPoint(e){const t=[];for(let i=0;i{t.push(e[0]),i.push(e[1]),s.push(e[2])})),[t.reduce(((e,t)=>e+t),0)/e.points.length,i.reduce(((e,t)=>e+t),0)/e.points.length,s.reduce(((e,t)=>e+t),0)/e.points.length]}pointXYZ(e){return[e.x,e.y,e.z]}pointXY(e){return[e.x,e.y]}spiral(e){const t=e.phi,i=Math.log(t)/(Math.PI/e.widening),s=[],r=e.radius/e.numberPoints;for(let t=0;t{i[r]=[s[0]-e,s[1]-t,0]}))}return e.pointsOnGround&&i.forEach(((e,t)=>{i[t]=[e[0],0,e[1]]})),i}closestPointFromPointData(e){let t,i,s=Number.MAX_SAFE_INTEGER;for(let r=0;r{e(t)}))}}class vG{create(e){return e.text}split(e){return e.text.split(e.separator)}replaceAll(e){return e.text.split(e.search).join(e.replaceWith)}join(e){return e.list.join(e.separator)}toString(e){return e.item.toString()}toStringEach(e){return e.list.map((e=>e.toString()))}}class xG{constructor(){}}class bG{constructor(){this.assetManager=new xG}getFile(e){return this.assetManager.getAsset(e.fileName)}getLocalFile(e){return this.assetManager.getLocalAsset(e.fileName)}createObjectURL(e){return URL.createObjectURL(e.file)}createObjectURLs(e){return e.files.map((e=>URL.createObjectURL(e)))}}class TG{constructor(e){this.context=e}hexColor(e){return e.color}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.color);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:void 0}rgbToHex(e){const t=e.r,i=e.g,s=e.b;return`#${Number(16777216+65536*t+256*i+s).toString(16).substring(1,7)}`}hexToRgbMapped(e){const t=this.hexToRgb(e);return{r:this.context.remap(t.r,0,255,e.from,e.to),g:this.context.remap(t.g,0,255,e.from,e.to),b:this.context.remap(t.b,0,255,e.from,e.to)}}getRedParam(e){return this.hexToRgbMapped(e).r}getGreenParam(e){return this.hexToRgbMapped(e).g}getBlueParam(e){return this.hexToRgbMapped(e).b}rgbToRed(e){return e.rgb.r}rgbToGreen(e){return e.rgb.g}rgbToBlue(e){return e.rgb.b}}class yG{constructor(){this.canvasZoneClass="canvasZone",this.tolerance=1e-5,this.snapTolerance=1e-5,this.tagBag=[],this.timeoutBag=[],this.intervalBag=[],this.renderLoopBag=[],this.keyDownBag=[],this.keyUpBag=[],this.keyPressBag=[],this.currentlyPressedKeys=[]}getFile(e){return new Promise(((t,i)=>{if(e){const s=new FileReader;s.readAsText(e,"UTF-8"),s.onload=e=>{const i=e.target.result;t(i)},s.onerror=e=>{i()}}else i()}))}remap(e,t,i,s,r){return(e-t)/(i-t)*(r-s)+s}}!function(e){e[e.loading=0]="loading",e[e.loaded=1]="loaded",e[e.initialised=2]="initialised",e[e.computing=3]="computing"}(oG||(oG={}));class SG{constructor(){this.jscadWorkerState=new ak,this.promisesMade=[]}jscadWorkerAlreadyInitialised(){return!!this.jscadWorker}setJscadWorker(e){this.jscadWorker=e,this.jscadWorker.onmessage=({data:e})=>{if("jscad-initialised"===e)this.jscadWorkerState.next({state:oG.initialised});else if("busy"===e)this.jscadWorkerState.next({state:oG.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.jscadWorkerState.next({state:oG.loaded}):this.jscadWorkerState.next({state:oG.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,s={uid:i},r=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=r,this.promisesMade.push(s),this.jscadWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),r}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}var CG=i(258);class EG{constructor(e){this.context=e}stringify(e){return JSON.stringify(e.json)}parse(e){return JSON.parse(e.text)}query(e){return this.context.jsonpath.query(e.json,e.query)}setValue(e){const t=Object.assign({},structuredClone(e.json));return this.context.jsonpath.value(t,e.path,e.value),t}setValuesOnPaths(e){const t=Object.assign({},structuredClone(e.json));return e.paths.forEach(((i,s)=>{this.context.jsonpath.value(t,i,e.values[s])})),t}paths(e){return this.context.jsonpath.paths(e.json,e.query)}pathsAsStrings(e){return this.context.jsonpath.paths(e.json,e.query).map((e=>this.context.jsonpath.stringify(e)))}createEmpty(){return{}}previewAndSaveJson(e){e.json&&this.context.promptPrintSave({text:e.json,isJson:!0,hidden:!1})}previewJson(e){e.json&&this.context.promptPrint({text:e.json,isJson:!0,hidden:!1})}}var AG=i(615);class PG{boolean(e){return e.boolean}randomBooleans(e){const t=[];for(let i=0;i{if(ie.thresholdTotalFalse)t.push(!1);else{const s=i-e.thresholdTotalTrue,r=(e.thresholdTotalFalse-e.thresholdTotalTrue)/e.nrLevels,n=Math.ceil(s/r)/e.nrLevels;Math.random()>n?t.push(!0):t.push(!1)}})),t}thresholdBooleanList(e){const t=[];return e.numbers.forEach((i=>{i!e)):t}thresholdGapsBooleanList(e){const t=[];return e.numbers.forEach((i=>{let s=!1;e.gapThresholds.forEach((e=>{const r=e[0],n=e[1];i>=r&&i<=n&&(t.push(!0),s=!0)})),s||t.push(!1)})),e.inverse?t.map((e=>!e)):t}not(e){return!e.boolean}notList(e){return e.booleans.map((e=>!e))}compare(e){switch(e.operator){case"==":return e.first==e.second;case"!=":return e.first!=e.second;case"===":return e.first===e.second;case"!==":return e.first!==e.second;case"<":return e.first":return e.first>e.second;case">=":return e.first>=e.second;default:return!1}}valueGate(e){return e.boolean?e.value:void 0}firstDefinedValueGate(e){let t;return t=void 0!==e.value1?e.value1:void 0!==e.value2?e.value2:void 0,t}}class RG{constructor(){this.context=new yG,this.jscadWorkerManager=new SG,this.occtWorkerManager=new hk;const e=new fG(this.context);this.color=new TG(this.context),this.babylon=new XV(this.context,e,this.color),this.vector=new pG(this.context),this.line=new hG(this.context,e),this.point=new mG(this.context,e,this.line),this.polyline=new dG(this.context,e),this.verb=new PU(this.context,e),this.jscad=new cU(this.jscadWorkerManager,this.context,e),this.tag=new _G(this.context),this.time=new gG(this.context),this.occt=new fU(this.context,this.occtWorkerManager,e,this.jscad.text,this.vector),this.asset=new bG,this.math=new uG,this.logic=new PG,this.json=new EG(this.context),this.text=new vG,this.lists=new cG,this.draw=new lG(this.point,this.line,this.polyline,this.babylon.node,this.verb.curve,this.verb.surface,this.jscad,this.occt,this.tag,this.context)}init(e,t,i,s){this.context.scene=e,s&&(this.context.havokPlugin=s);const r={geom:CG.geom,core:CG.core};this.context.verb=r,this.context.jsonpath=AG,t&&this.occtWorkerManager.setOccWorker(t),i&&this.jscadWorkerManager.setJscadWorker(i)}}const IG="assets/textures";class MG{constructor(e){this.name="",this.scene=void 0,this.wAng=0,this.uScale=1,this.vScale=1,this.color=void 0,this.albedoTextureUrl=void 0,this.microSurfaceTextureUrl=void 0,this.bumpTextureUrl=void 0,this.metallic=.1,this.roughness=.9,this.zOffset=2,Object.keys(this).forEach((t=>this[t]=e[t]))}}class OG{static simpleBlackMaterial(e){const t=new Um("blackMaterial"+Math.random(),e);return t.albedoColor=new Ce(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2,t}static rock1Material(e,t,i){const s=new MG({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.rock1.default.albedo,bumpTextureUrl:OG.textures.rock1.microSurfaceTexture,microSurfaceTextureUrl:OG.textures.rock1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static wood1Material(e,t,i){const s=new MG({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.wood1.light.albedo,bumpTextureUrl:OG.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static wood2Material(e,t,i){const s=new MG({name:"wood2",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.wood2.light.albedo,microSurfaceTextureUrl:OG.textures.wood2.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static wood3Material(e,t,i){const s=new MG({name:"wood3",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.wood1.dark.albedo,microSurfaceTextureUrl:OG.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static brownPlanks(e,t,i){const s=new MG({name:"brownPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.brownPlanks.light.albedo,microSurfaceTextureUrl:OG.textures.brownPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static woodenPlanks(e,t,i){const s=new MG({name:"woodenPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.woodenPlanks.light.albedo,microSurfaceTextureUrl:OG.textures.woodenPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static glass(e,t){const i=new Um("faceGlassMaterial"+Math.random(),e);return i.albedoColor=Ce.FromHexString(t),i.ambientColor=Ce.FromHexString("#ffffff"),i.metallic=.8,i.roughness=.1,i.zOffset=1,i.alpha=.5,i}static brushedConcrete(e,t,i){const s=new MG({name:"brushedConcrete",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.brushedConcrete.grey.albedo,microSurfaceTextureUrl:OG.textures.brushedConcrete.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static metal1(e,t,i){const s=new MG({name:"metal1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.metal1.light.albedo,microSurfaceTextureUrl:OG.textures.metal1.microSurfaceTexture,bumpTextureUrl:OG.textures.metal1.light.roughness,metallic:.3,roughness:.6,zOffset:2});return OG.createMaterial(s)}static roughPlastic(e,t){const i=new MG({name:"roughPlastic-"+t,color:t,scene:e,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(i)}static createMaterial(e){const t=new Um(e.name,e.scene);return e.color&&(t.albedoColor=Ce.FromHexString(e.color)),e.albedoTextureUrl&&(t.albedoTexture=OG.createTexture(e.albedoTextureUrl,e)),e.microSurfaceTextureUrl&&(t.microSurfaceTexture=OG.createTexture(e.microSurfaceTextureUrl,e)),e.bumpTextureUrl&&(t.bumpTexture=OG.createTexture(e.bumpTextureUrl,e)),t.metallic=e.metallic,t.roughness=e.roughness,t.zOffset=e.zOffset,t}static createTexture(e,t){const i=new Vo(e,t.scene);return i.uScale=t.uScale,i.vScale=t.vScale,i.wAng=t.wAng,i}}OG.textures={wood1:{microSurfaceTexture:`${IG}/Wood048_1K/Wood048_1K_NormalGL.jpg`,light:{albedo:`${IG}/Wood048_1K/Wood048_1K_Light.jpg`},dark:{albedo:`${IG}/Wood048_1K/Wood048_1K_Color_Dark.jpg`}},wood2:{microSurfaceTexture:`${IG}/Wood084_1K/Wood084A_1K_NormalGL.jpg`,light:{albedo:`${IG}/Wood084_1K/Wood084A_1K_Color.jpg`}},metal1:{microSurfaceTexture:`${IG}/metal_1/Metal029_1K_Displacement.jpg`,light:{albedo:`${IG}/metal_1/Metal029_1K_Color.jpg`,normalGL:`${IG}/metal_1/Metal029_1K_NormalGL.jpg`,roughness:`${IG}/metal_1/Metal029_1K_Roughness.jpg`,metalness:`${IG}/metal_1/Metal029_1K_Metalness.jpg`}},brownPlanks:{microSurfaceTexture:`${IG}/brown_planks/brown_planks_05_nor_gl_1k.jpg`,light:{albedo:`${IG}/brown_planks/brown_planks_05_diff_1k.jpg`}},woodenPlanks:{microSurfaceTexture:`${IG}/wooden_planks/wooden_planks_nor_gl_1k.jpg`,light:{albedo:`${IG}/wooden_planks/wooden_planks_diff_1k.jpg`}},brushedConcrete:{microSurfaceTexture:`${IG}/brushed_concrete/brushed_concrete_03_nor_gl_1k.jpg`,sand:{albedo:`${IG}/brushed_concrete/brushed_concrete_03_diff_1k.jpg`},grey:{albedo:`${IG}/brushed_concrete/brushed_concrete_03_diff_grey_1k.jpg`}},rock1:{microSurfaceTexture:`${IG}/Rock044_1K/Rock044_1K_NormalGL.jpg`,default:{albedo:`${IG}/Rock044_1K/Rock044_1K_Color.jpg`,roughness:`${IG}/Rock044_1K/Rock044_1K_Roughness.jpg`}}};var DG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class wG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return DG(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.wingtipVilla",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},chimney:{shape:t.shapes.find((e=>e.id===t.data.chimney.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return DG(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const s=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),r=s.getChildMeshes(),n=r[0],o=r[1],a=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),l=a.getChildMeshes(),h=l[0],c=l[1],u=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),d=u.getChildMeshes(),_=d[0],p=d[1],f=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),m=f.getChildMeshes(),g=m[0],v=m[1],x=yield this.draw.drawAnyAsync({entity:e.chimney.shape,options:i}),b=x.getChildMeshes(),T=b[0],y=b[1],S=new Vo("assets/textures/Wood048_1K/Wood048_1K_Red.jpg",this.context.scene),C=new Vo("assets/textures/Wood048_1K/Wood048_1K_Color_Dark.jpg",this.context.scene),E=new Vo("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);S.uScale=.3,S.vScale=.3,S.wAng=Math.PI/2,C.uScale=.3,C.vScale=.3,C.wAng=Math.PI/2,E.uScale=.3,E.vScale=.3,E.wAng=Math.PI/2;const A=new Um("wood-red",this.context.scene);A.albedoTexture=S,A.microSurfaceTexture=E,A.metallic=0,A.roughness=1,A.zOffset=2;const P=new Um("wood-dark",this.context.scene);return P.albedoTexture=C,P.microSurfaceTexture=E,P.metallic=0,P.roughness=1,P.zOffset=2,n.material=A,h.material=OG.wood1Material(this.context.scene,Math.PI/2,.3),_.material=A,g.material=A,T.material=P,n.parent=t,h.parent=t,_.parent=t,g.parent=t,T.parent=t,o.parent=t,c.parent=t,p.parent=t,v.parent=t,y.parent=t,s.dispose(),u.dispose(),a.dispose(),f.dispose(),x.dispose(),t}))}dispose(e){return DG(this,void 0,void 0,(function*(){const t=[e.compound,e.chimney.shape,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}}var NG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class FG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}dispose(e){return NG(this,void 0,void 0,(function*(){const t=[e.compound,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}create(e){return NG(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.chirpyChalet",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return NG(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const s=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),r=s.getChildMeshes()[0],n=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),o=n.getChildMeshes()[0],a=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),l=a.getChildMeshes()[0],h=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),c=h.getChildMeshes()[0],u=new Vo("assets/textures/Wood048_1K/Wood048_1K_Color.jpg",this.context.scene),d=new Vo("assets/textures/Wood048_1K/Wood048_1K_Light.jpg",this.context.scene),_=new Vo("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);d.uScale=.3,d.vScale=.3,d.wAng=Math.PI/2,u.uScale=.3,u.vScale=.3,u.wAng=Math.PI/2,_.uScale=.3,_.vScale=.3,_.wAng=Math.PI/2;const p=new Um("roof",this.context.scene);p.albedoTexture=u,p.microSurfaceTexture=_,p.metallic=0,p.roughness=1,p.zOffset=2;const f=new Um("walls",this.context.scene);return f.albedoTexture=d,f.microSurfaceTexture=_,f.metallic=0,f.roughness=1,f.zOffset=2,r.material=p,o.material=f,l.material=p,c.material=p,s.setParent(t),a.setParent(t),n.setParent(t),h.setParent(t),t}))}}class BG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.wingtipVilla=new wG(this.occWorkerManager,this.context,this.draw,this.occt),this.chirpyChalet=new FG(this.occWorkerManager,this.context,this.draw,this.occt)}}class LG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.birdhouses=new BG(this.occWorkerManager,this.context,this.draw,this.occt)}}var kG,VG,UG,GG,zG,WG,HG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class XG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return HG(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.serenitySwirl",e);return t?{type:t.data.type,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return HG(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new Um("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ce(1,1,1),n.ambientColor=Ce.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}dispose(e){return HG(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}!function(e){e.low="low",e.middle="middle",e.high="high"}(kG||(kG={}));class YG{constructor(){this.lod=kG.low}}class QG{}class jG{constructor(e,t,i,s,r,n,o,a,l){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.addRadiusNarrow=i),void 0!==s&&(this.addRadiusWide=s),void 0!==r&&(this.addMiddleHeight=r),void 0!==n&&(this.addTopHeight=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l)}}class KG{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class $G{}class qG{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=kG.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==i&&(this.archCenterThickness=i),void 0!==s&&(this.edgesThickness=s),void 0!==r&&(this.thickness=r),void 0!==n&&(this.baseHeight=n),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.origin=h),void 0!==c&&(this.direction=c),void 0!==u&&(this.scale=u)}}class ZG{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class JG{}class ez{}class tz{}class iz{constructor(e,t,i,s,r,n,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==i&&(this.fullModel=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.decorationThickness=r),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class sz{constructor(){this.type="parametric-model",this.name="eternalLove"}}class rz{}class nz{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.fillet=r),void 0!==n&&(this.nrOfHandles=n),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.scale=h),void 0!==c&&(this.origin=c),void 0!==u&&(this.direction=u)}}class oz{constructor(){this.type="parametric-model",this.name="calmCup"}}class az{}class lz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==s&&(this.radiusMidOffset=s),void 0!==r&&(this.rotationTopAngle=r),void 0!==n&&(this.rotationMidAngle=n),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==l&&(this.nrSkinCellDivisionsTop=l),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==c&&(this.skinCellOuterHeight=c),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==_&&(this.skinCellTopHeight=_),void 0!==p&&(this.thickness=p),void 0!==f&&(this.bottomThickness=f),void 0!==m&&(this.precision=m),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==x&&(this.origin=x),void 0!==b&&(this.direction=b)}}class hz{constructor(){this.type="parametric-model",this.name="dragonCup"}}class cz{}class uz{}class dz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==i&&(this.widthBack=i),void 0!==s&&(this.widthFront=s),void 0!==r&&(this.length=r),void 0!==n&&(this.backOffset=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.phoneHeight=h),void 0!==c&&(this.phoneWidth=c),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdges=_),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class _z{constructor(){this.type="parametric-model",this.name="phoneNest"}}class pz extends QG{}class fz{}class mz extends QG{}class gz{}class vz{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class xz{}class bz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==i&&(this.nrSides=i),void 0!==s&&(this.nrOffsets=s),void 0!==r&&(this.height=r),void 0!==n&&(this.coverHeight=n),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==l&&(this.radiusOffset=l),void 0!==h&&(this.thickness=h),void 0!==c&&(this.ornamentalThickness=c),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==_&&(this.fillet=_),void 0!==p&&(this.precision=p),void 0!==f&&(this.rotation=f),void 0!==m&&(this.scale=m),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class Tz{constructor(){this.type="parametric-model",this.name="spicyBox"}}class yz{}class Sz{}class Cz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x,b,T,y,S,C,E,A,P,R,I){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=kG.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==i&&(this.terraceWidth=i),void 0!==s&&(this.widthSecondWing=s),void 0!==r&&(this.lengthSecondWing=r),void 0!==n&&(this.heightWalls=n),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==l&&(this.roofOffset=l),void 0!==h&&(this.roofInsideOverhang=h),void 0!==c&&(this.roofMaxDistAttachmentBeams=c),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==_&&(this.roofOutsideOverhang=_),void 0!==p&&(this.columnSize=p),void 0!==f&&(this.ceilingBeamHeight=f),void 0!==m&&(this.ceilingBeamWidth=m),void 0!==g&&(this.nrCeilingBeamsBetweenColumns=g),void 0!==v&&(this.distBetweenColumns=v),void 0!==x&&(this.floorHeight=x),void 0!==b&&(this.groundLevel=b),void 0!==T&&(this.facadePanelThickness=T),void 0!==y&&(this.windowWidthOffset=y),void 0!==S&&(this.windowHeightOffset=S),void 0!==C&&(this.windowFrameThickness=C),void 0!==E&&(this.windowGlassFrameThickness=E),void 0!==A&&(this.lod=A),void 0!==P&&(this.skinOpacity=P),void 0!==R&&(this.rotation=R),void 0!==I&&(this.origin=I)}}class Ez{constructor(){this.type="parametric-model",this.name="zenHideout"}}class Az{}class Pz{}class Rz{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class Iz{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class Mz extends Iz{}class Oz extends Rz{}class Dz{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class wz{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class Nz extends Dz{}class Fz extends wz{}class Bz{}class Lz{}class kz{}class Vz{}class Uz{}class Gz{}class zz{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class Wz extends zz{}class Hz{}class Xz{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=kG.high,this.center=[0,0,0],this.direction=[0,1,0]}}class Yz extends Xz{}class Qz{}class jz{}class Kz{constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class $z{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.holeDiameter=r),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.rotation=c),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class qz{constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class Zz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.holeDiameter=r),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.roofAngle=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class Jz{constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class eW{}class tW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==i&&(this.backRestHeight=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r),void 0!==n&&(this.thickness=n),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.precision=h),void 0!==c&&(this.drawEdges=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==_&&(this.origin=_),void 0!==p&&(this.direction=p)}}class iW{constructor(){this.type="parametric-model",this.name="snakeChair"}}class sW extends QG{}class rW{}class nW extends QG{}class oW{}class aW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class lW{}class hW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.topThickness=s),void 0!==r&&(this.topOffset=r),void 0!==n&&(this.bottomThickness=n),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==l&&(this.radiusLegBottom=l),void 0!==h&&(this.nrLegPairs=h),void 0!==c&&(this.precision=c),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==_&&(this.scale=_),void 0!==p&&(this.origin=p),void 0!==f&&(this.direction=f)}}class cW{constructor(){this.type="parametric-model",this.name="elegantTable"}}class uW extends QG{}class dW{}class _W extends QG{}class pW extends QG{}class fW{constructor(){this.index=0}}class mW{}class gW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class vW{}class xW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.chamfer=s),void 0!==r&&(this.topThickness=r),void 0!==n&&(this.topGlassOffset=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==l&&(this.shelfTopOffset=l),void 0!==h&&(this.shelfThickness=h),void 0!==c&&(this.legWidth=c),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdges=_),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class bW{constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class TW extends QG{}class yW{}class SW extends QG{}class CW extends QG{}class EW extends QG{}class AW{constructor(){this.index=0}}class PW{}class RW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class IW{}class MW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.supportLength=s),void 0!==r&&(this.shelfHeight=r),void 0!==n&&(this.thickness=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==l&&(this.nrOrnamentPlanks=l),void 0!==h&&(this.ornamentDepth=h),void 0!==c&&(this.filletRadius=c),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==_&&(this.rotation=_),void 0!==p&&(this.scale=p),void 0!==f&&(this.origin=f),void 0!==m&&(this.direction=m)}}class OW{constructor(){this.type="parametric-model",this.name="snakeTable"}}class DW extends QG{}class wW{}class NW extends QG{}class FW{}class BW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(VG||(VG={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(UG||(UG={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(GG||(GG={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(zG||(zG={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(WG||(WG={}));const LW=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class kW{constructor(e,t,i,s,r,n,o,a,l){this.text="bitbybit.dev",this.fontType=VG.Roboto,this.fontVariant=UG.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=WG.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==i&&(this.fontVariant=i),void 0!==s&&(this.fontSize=s),void 0!==r&&(this.height=r),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==l&&(this.originAlignment=l)}}class VW{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.facePlanar=!1,this.faceTextVar=GG.separatedExtrusion,this.text="bitbybit.dev",this.fontType=VG.Roboto,this.fontVariant=UG.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=WG.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.faceTextVar=i),void 0!==s&&(this.text=s),void 0!==r&&(this.fontType=r),void 0!==n&&(this.fontVariant=n),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.originParamU=h),void 0!==c&&(this.originParamV=c),void 0!==u&&(this.originAlignment=u)}}class UW{constructor(){this.type="parametric-model",this.name="text3d"}}class GW{constructor(){this.index=0}}class zW{}class WW{}class HW{constructor(e,t,i,s,r,n,o,a,l,h){this.faceTextVar=GG.separatedExtrusion,this.text="bitbybit.dev",this.fontType=VG.Roboto,this.fontVariant=UG.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=WG.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==i&&(this.fontType=i),void 0!==s&&(this.fontVariant=s),void 0!==r&&(this.fontSize=r),void 0!==n&&(this.height=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==l&&(this.originParamV=l),void 0!==h&&(this.originAlignment=h)}}class XW{constructor(e,t,i){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.definitions=i)}}class YW{constructor(e,t,i,s){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==s&&(this.height=s)}}class QW{constructor(e,t,i,s,r,n,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==i&&(this.uNumber=i),void 0!==s&&(this.vNumber=s),void 0!==r&&(this.affectMinHeight=r),void 0!==n&&(this.affectMaxHeight=n),void 0!==o&&(this.precision=o)}}class jW{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class KW{constructor(){this.index=0}}class $W{}class qW{}class ZW{}class JW{}class eH{constructor(){this.faceIndex=0}}class tH{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class iH{constructor(){this.faceIndex=0,this.uIndex=0}}class sH{constructor(){this.faceIndex=0,this.vIndex=0}}class rH{}class nH{}var oH;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(oH||(oH={}));class aH{static parse(e,t){var i;const s=[e],r=new Set;for(;s.length>0;){const e=s.pop();if("object"==typeof e&&null!==e&&!r.has(e))if(r.add(e),Array.isArray(e))for(let t=0;tt.id===e.shapes[r])))||void 0===i?void 0:i.shape)}for(const t in e)s.push(e[t])}}return e}}var lH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class hH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return lH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.arabicArchway",e);if(t){const e=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},e),{type:t.data.type,name:t.data.name,compound:t.compound,shapes:t.shapes,originalInputs:t.data.originalInputs})}}))}drawModel(e,t=.003){return lH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;this.materials||(this.materials=this.createMaterials(e.originalInputs.lod)),s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?e.originalInputs.lod===kG.high&&"compound"===t?i(void 0):this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,t)=>{const s=o[t];if(s){if(s.parent=i,void 0!==this.materials[e]){const t=s.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}s.name=e,s.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=s}})),i}))}dispose(e){return lH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}disposeMaterials(){this.materials&&Object.keys(this.materials).forEach((e=>{const t=this.materials[e];t&&t.dispose()}))}createMaterials(e){const t=new ez;return e===kG.high?t.compound=this.createBaseMaterial():t.compound=this.createOpaqueMaterial(),t.vasePartsCompound=this.createBaseMaterial(),t.glassPartsCompound=this.createGlassMaterial(),t.vaseBaseCompound=this.createBaseMaterial(),t}createOpaqueMaterial(){const e=new Um("opaqueMat"+Math.random(),this.context.scene);return e.albedoColor=new Ce(1,1,1),e.ambientColor=Ce.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e.backFaceCulling=!1,e.alpha=.3,e}createBaseMaterial(){const e=new Um("faceMaterial"+Math.random(),this.context.scene);return e.albedoColor=new Ce(1,1,1),e.ambientColor=Ce.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e}createGlassMaterial(){const e=new Um("faceGlassMaterial"+Math.random(),this.context.scene);return e.albedoColor=new Ce(0,0,.05),e.ambientColor=Ce.FromHexString("#ffffff"),e.metallic=.8,e.roughness=.1,e.zOffset=1,e.alpha=.5,e}}class cH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.serenitySwirl=new XG(this.occWorkerManager,this.context,this.draw,this.occt),this.arabicArchway=new hH(this.occWorkerManager,this.context,this.draw,this.occt)}}var uH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class dH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return uH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.eternalLove",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return uH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new Um("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ce(1,.9,1),n.ambientColor=Ce.FromHexString("#ff00ff"),n.metallic=.8,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}dispose(e){return uH(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}class _H{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.eternalLove=new dH(this.occWorkerManager,this.context,this.draw,this.occt)}}var pH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class fH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return pH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.calmCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e){return pH(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new Um("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=new Ce(1,1,1),r.ambientColor=Ce.FromHexString("#ffffff"),r.metallic=.8,r.roughness=.7,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}dispose(e){return pH(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}var mH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class gH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return mH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.dragonCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}getCompoundShape(e){return e.model.compound}drawModel(e){return mH(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#617bff",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new Um("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=Ce.FromHexString("#2b00ff"),r.ambientColor=Ce.FromHexString("#ffffff"),r.metallic=.9,r.roughness=.3,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}}class vH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.calmCup=new fH(this.occWorkerManager,this.context,this.draw,this.occt),this.dragonCup=new gH(this.occWorkerManager,this.context,this.draw,this.occt)}}var xH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class bH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return xH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.phoneNest",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}drawOptions(e){return e}drawModel(e,t){return xH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#ffffff",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?("phone"===t&&(s.edgeColour="#000000"),this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)}))):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return xH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="phone-nest-",t=new fz,i=OG.wood3Material(this.context.scene,Math.PI/2,1);i.name=e+i.name,t.main=i;const s=OG.glass(this.context.scene,"#000000");return s.name=e+s.name,t.phone=s,t}}class TH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.phoneNest=new bH(this.occWorkerManager,this.context,this.draw,this.occt)}}class yH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.vases=new cH(this.occWorkerManager,this.context,this.draw,this.occt),this.cups=new vH(this.occWorkerManager,this.context,this.draw,this.occt),this.medals=new _H(this.occWorkerManager,this.context,this.draw,this.occt),this.desktop=new TH(this.occWorkerManager,this.context,this.draw,this.occt)}}var SH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class CH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return SH(this,void 0,void 0,(function*(){void 0===this.materials&&(this.materials=this.createMaterials()),void 0===this.skin&&(this.skin=this.createSkin());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.zenHideout",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e,t=.003){return SH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;if(s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.06,s.precision=t,e.originalInputs.lod===kG.high&&e.drawingPart){const t={},r=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((s=>{s.isVisible=!1,s.getChildMeshes().forEach((e=>e.isVisible=!1)),!0===this.skin[t]&&(s.visibility=e.originalInputs.skinOpacity,s.getChildMeshes().forEach((t=>t.visibility=e.originalInputs.skinOpacity))),i(s)}),(()=>{i(void 0)})):i(void 0)})))),n=yield Promise.all(r);Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const r=n[s];if(r){if(r.parent=i,void 0!==this.materials[e]){const t=r.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}r.name=e,r.isVisible=!0,r.getChildMeshes().forEach((e=>e.isVisible=!0)),t[e]=r}}))}else if(e.originalInputs.lod===kG.middle){const t=new Um("brepMaterial"+Math.random(),this.context.scene);t.albedoColor=new Ce(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s});r.getChildMeshes()[0].material=t,r.material=t,r.parent=i}else e.originalInputs.lod===kG.low&&(s.edgeColour="#e89668",s.edgeWidth=10,(yield this.draw.drawAnyAsync({entity:e.compound,options:s})).parent=i);return i}))}dispose(e){return SH(this,void 0,void 0,(function*(){const t=e.shapes.map((e=>e.shape));yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="zen-hideout-",t=new Pz,i=new zv(e+"windowGlassCompound",this.context.scene);i.alpha=.2,i.metallic=.9,i.roughness=.1,i.baseColor=new Ce(.9,.9,1),i.zOffset=2,t.windowGlassCompound=i;const s=new zv(e+"windowGlassCompound",this.context.scene);s.metallic=.1,s.roughness=.8,s.baseColor=new Ce(.05,.05,.05),s.zOffset=2,t.windowFrameCompound=s;const r=new zv(e+"glassFramesCompound",this.context.scene);r.metallic=.1,r.roughness=.8,r.baseColor=new Ce(0,0,0),r.zOffset=2,t.glassFramesCompound=r;const n=OG.metal1(this.context.scene,0,.3);t.roofCoverFirstCompound=n,t.roofCoverSecondCompound=n;const o=OG.wood1Material(this.context.scene,0,1);t.beamsCompound=o,t.columnsCompound=o;const a=OG.woodenPlanks(this.context.scene,0,1);t.firstFloorExteriorPanelsCompound=a;const l=new zv(e+"firstFloorInteriorPanelsCompound",this.context.scene);l.metallic=.1,l.roughness=.8,l.baseColor=new Ce(.1,.1,.1),l.zOffset=2,t.firstFloorInteriorPanelsCompound=l;const h=OG.wood3Material(this.context.scene,Math.PI/2,1);t.roofExteriorPanelsCompound=h;const c=new zv(e+"roofInteriorPanelsCompound",this.context.scene);c.metallic=.1,c.roughness=.8,c.baseColor=new Ce(.3,.3,.3),c.zOffset=2,t.roofInteriorPanelsCompound=c;const u=OG.wood2Material(this.context.scene,0,.5);t.floorCompound=u;const d=new zv(e+"ceilingCompound",this.context.scene);d.metallic=.3,d.roughness=.7,d.baseColor=new Ce(1,1,1),d.zOffset=2,t.ceilingCompound=d;const _=OG.brushedConcrete(this.context.scene,0,1);return t.stairsCompound=_,t}createSkin(){return{windowGlassCompound:!0,glassFramesCompound:!1,windowFrameCompound:!1,beamsCompound:!1,columnsCompound:!1,firstFloorExteriorPanelsCompound:!0,firstFloorInteriorPanelsCompound:!0,roofExteriorPanelsCompound:!0,roofInteriorPanelsCompound:!0,roofCoverFirstCompound:!0,roofCoverSecondCompound:!0,floorCompound:!0,ceilingCompound:!0,stairsCompound:!1}}}class EH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.zenHideout=new CH(this.occWorkerManager,this.context,this.draw,this.occt)}}class AH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.houses=new EH(this.occWorkerManager,this.context,this.draw,this.occt)}}class PH{lodEnum(e){return e.lod}}var RH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class IH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return RH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.elegantTable",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return RH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#bc7e5b",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return RH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="elegant-table-",t=new dW,i=OG.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i;const s=OG.wood1Material(this.context.scene,Math.PI/2,2);s.name=e+i.name,t.topBase=s;const r=OG.wood1Material(this.context.scene,0,1);return r.name=e+i.name,t.legs=r,t}}var MH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class OH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return MH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.goodCoffeeTable",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return MH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#bc7e5b",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return MH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="good-coffee-table-",t=new yW,i=OG.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i,t.legs=i,t.shelf=i;const s=OG.glass(this.context.scene,"#000000");return s.name=e+i.name,t.topGlass=s,t}}var DH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class wH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return DH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeTable",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getGlassShape(e){return e.model.mainPart.shapes.glass}getMainShape(e){return e.model.mainPart.shapes.main}getTopCenterPoint(e){return e.model.mainPart.topCenter}drawOptions(e){return e}drawModel(e,t){return DH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#000000",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return DH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="snake-table-",t=new wW,i=OG.roughPlastic(this.context.scene,"#ffffff");i.name=e+i.name,t.main=i;const s=OG.glass(this.context.scene,"#000000");return s.name=e+s.name,t.glass=s,t}}class NH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.elegantTable=new IH(this.occWorkerManager,this.context,this.draw,this.occt),this.goodCoffeeTable=new OH(this.occWorkerManager,this.context,this.draw,this.occt),this.snakeTable=new wH(this.occWorkerManager,this.context,this.draw,this.occt)}}var FH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class BH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return FH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeChair",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getSittingWireShape(e){return e.model.mainPart.shapes.sittingWire}getSittingAreaCenterPoint(e){return e.model.mainPart.sittingCenter}drawOptions(e){return e}drawModel(e,t){return FH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#000000",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return FH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e=new rW,t=OG.roughPlastic(this.context.scene,"#ffffff");return t.name="snake-chair-"+t.name,e.main=t,e}}class LH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.snakeChair=new BH(this.occWorkerManager,this.context,this.draw,this.occt)}}class kH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.chairs=new LH(this.occWorkerManager,this.context,this.draw,this.occt),this.tables=new NH(this.occWorkerManager,this.context,this.draw,this.occt)}}class VH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.kidsCorner=new LG(this.occWorkerManager,this.context,this.draw,this.occt),this.threeDPrinting=new yH(this.occWorkerManager,this.context,this.draw,this.occt),this.architecture=new AH(this.occWorkerManager,this.context,this.draw,this.occt),this.furniture=new kH(this.occWorkerManager,this.context,this.draw,this.occt),this.enums=new PH}}var UH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class GH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return UH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3d",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextOnFace(e){return UH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3dFace",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextsOnFace(e){return UH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.texts3dFace",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}definition3dTextOnFace(e){return e}drawModel(e,t=.003){return UH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new Um("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ce(1,1,1),n.ambientColor=Ce.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}getCompoundShape(e){return e.model.compound}getCharacterShape(e){if(e.index<0||e.index>=e.model.characterParts.length)throw new Error("Index is out of bounds.");return e.model.characterParts[e.index].shapes.compound}getCharacterShapes(e){return e.model.characterParts.map((e=>e.shapes.compound))}getCharacterCenterCoordinates(e){return e.model.characterCenterCoordinates}getFaceCutout(e){if(e.model.faceParts){const t=e.model.faceParts.filter((e=>e.type===zG.cutout)).map((e=>e.shapes.face));if(t.length>0)return t[0];throw new Error("No cutout was found.")}throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAllFacesOfCutout(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===zG.cutout||e.type===zG.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getCutoutsInsideCharacters(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===zG.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAdvanceWidth(e){return e.model.advanceWidth}}var zH,WH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class HH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}createPyramidSimple(e){return WH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimple",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createPyramidSimpleAffectors(e){return WH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimpleAffectors",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e){return WH(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=1,i.precision=e.originalInputs.precision;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new Um("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=new Ce(1,1,1),r.ambientColor=Ce.FromHexString("#ffffff"),r.metallic=.3,r.roughness=.6,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}getCompoundShape(e){return e.model.compound}getCompoundShapeOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t.shapes.compound;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getAllPyramidCells(e){return e.model.faceParts.map((e=>e.cells)).flat()}getAllPyramidCellsOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex));throw new Error("Face index is out of range")}getAllPyramidUCellsOnFaceAtV(e){if(e.model.faceParts&&e.faceIndext.vIndex===e.vIndex));throw new Error("Face index is out of range")}getCellOnIndex(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getTopPointsOfCells(e){return e.cells.map((e=>e.topPoint))}getCenterPointsOfCells(e){return e.cells.map((e=>e.centerPoint))}getCornerPointsOfCells(e){return e.cells.map((e=>[e.cornerPoint1,e.cornerPoint2,e.cornerPoint3,e.cornerPoint4].filter((e=>void 0!==e))))}getCornerPointOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerPoint1:1===e.index?t.cornerPoint2:2===e.index?t.cornerPoint3:3===e.index?t.cornerPoint4:void 0));throw new Error("Corner index is out of range")}getCornerNormalOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerNormal1:1===e.index?t.cornerNormal2:2===e.index?t.cornerNormal3:3===e.index?t.cornerNormal4:void 0));throw new Error("Corner index is out of range")}getCornerNormalsOfCells(e){return e.cells.map((e=>[e.cornerNormal1,e.cornerNormal2,e.cornerNormal3,e.cornerNormal4].filter((e=>void 0!==e))))}getCompoundShapesOfCells(e){return e.cells.map((e=>e.shapes.compound))}getFaceShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.face1:1===e.index?t.shapes.face2:2===e.index?t.shapes.face3:3===e.index?t.shapes.face4:void 0));throw new Error("Face index is out of range")}getWireShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.wire1:1===e.index?t.shapes.wire2:2===e.index?t.shapes.wire3:3===e.index?t.shapes.wire4:void 0));throw new Error("Wire index is out of range")}getStartPolylineWireU(e){if(e.faceIndex>=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0&&"string"!=typeof t[e])for(var i=function(i){var s=t[e][i];"object"==typeof s&&null!==s&&s.then&&(s.then((function(s){return t[e][i]=s,s})),n.push(t[e][i]))},s=0;s0&&e.startedAsyncTask(i,s,"#eeeeff"),n.length>0?[2,Promise.all(n).then((function(t){return e.finishedAsyncTask(i,s),t}))]:[2,null]}))}))},e.finishedAsyncTask=function(e,t){},e.startedAsyncTask=function(e,t,i){},e.runtimeValidation=function(e,t){},e.validate=function(e,t,i){},e.handleBlockException=function(e,t){},e.errorHappened=function(e,t,i){},e.updateListInputs=function(e){Object.keys(e).forEach((function(t){if(Array.isArray(e[t])){var i=[];e[t].forEach((function(e){if(e&&e.result){var t=e.result;e.transformers&&e.transformers.length&&e.transformers.forEach((function(e){e.type===KH.flat&&(t=t.flat())})),t instanceof Array?i.push.apply(i,t):i.push(t)}})),e[t]=i}}))},e.executeBasedOnTypeAsync=function(e,t,i){return qH(this,void 0,void 0,(function(){var s,r,n,o,a,l,h,c,u;return ZH(this,(function(d){switch(d.label){case 0:if(t)return[3,5];l=this.performActionOnAllVariationsSimplified(e,i),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,Promise.all(l)];case 2:return s=d.sent(),[3,4];case 3:throw r=d.sent(),new Error(r);case 4:return[3,9];case 5:if(!t)return[3,9];for(n=Object.keys(e),o=n.map((function(t){return e[t]})),a=this.normalizeListsToEqualLength(o),l=[],h=function(e){var t={};n.forEach((function(i,s){t[i]=o[s][e]})),l.push(i(t))},c=0;ct&&(t=e.length)})),t},e.drawNodeMeshes=function(e,t){return qH(this,void 0,void 0,(function(){var i,s=this;return ZH(this,(function(r){switch(r.label){case 0:return i=e.map((function(e){return qH(s,void 0,void 0,(function(){var i,s,r;return ZH(this,(function(n){switch(n.label){case 0:return i=e.result,s=[],i instanceof Array&&i.length>0&&i[0]&&i[0].hash?i.forEach((function(e){var i=t.draw.drawAnyAsync({entity:e,options:void 0});s.push(i)})):(r=t.draw.drawAnyAsync({entity:i,options:void 0}),s.push(r)),[4,Promise.all(s)];case 1:return[2,n.sent()]}}))}))})),[4,Promise.all(i)];case 1:return r.sent(),[2]}}))}))},e}(),iX=function(){function e(e){this.context=e}return e.prototype.handleTags=function(e,t,i,s){var r=this;!t&&this.context.tagBag.length>0&&this.context.tagBag.find((function(e){return e.needsUpdate}))&&(t=!0),t&&this.context.tagBag.length>0&&this.context.tagBag.forEach((function(t){var n=document.querySelector("#"+t.id),o=new de(t.position[0],t.position[1],t.position[2]);n.textContent=t.text;var a=i.getRenderWidth()/2,l=i.getRenderHeight()/2,h=de.Project(o,fe.IdentityReadOnly,s.getTransformMatrix(),e.viewport.toGlobal(a,l)),c=de.Distance(e.position,o),u=t.adaptDepth?Math.ceil(r.context.remap(c,0,100,t.size,3)):t.size;h.x>0&&h.x0&&h.y0&&h.z<1&&u>3?n.style="".concat("position: absolute; transform: translate(-50%, -50%); font-weight: 400;"," font-size: ").concat(u,"px; color: ").concat(t.colour,"; left: ").concat(h.x,"px; top: ").concat(h.y,"px; display: inline;"):n.style="display: none;"}))},e.prototype.removeTagsIfNeeded=function(){this.tagsExist()&&this.context.tagBag.forEach((function(e){var t=document.getElementById(e.id);t.parentNode.removeChild(t)})),this.context.tagBag=[]},e.prototype.tagsExist=function(){return this.context.tagBag.length>0},e}(),sX=function(){return sX=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0?JSON.stringify(s):"{}",';\n let bitbybitRunnerResult = {};\n const runContext = "runner";\n const mockBitbybitRunnerInputs = (inputs) => {\n }\n const getBitbybitRunnerInputs = () => {\n return bitbybitRunnerInputs;\n }\n const setBitbybitRunnerResult = (result) => {\n bitbybitRunnerResult = result;\n }\n const setBitbybitRunnerResultValue = (prop, value) => {\n bitbybitRunnerResult[prop] = value;\n }\n\n const bitbybit = this.bitbybit;\n const Bit = this.Bit;\n Bit.mockBitbybitRunnerInputs = mockBitbybitRunnerInputs;\n Bit.getBitbybitRunnerInputs = getBitbybitRunnerInputs;\n Bit.setBitbybitRunnerResult = setBitbybitRunnerResult;\n Bit.setBitbybitRunnerResultValue = setBitbybitRunnerResultValue;\n\n const BitByBit = this.BitByBit;\n const errorHandle = this.errorHandle;\n const BABYLON = this.BABYLON;\n BABYLON.GUI = this.GUI;\n const resolve = this.resolve;\n\n await ').concat(r.script,"\n if(bitbybitRunnerResult !== undefined){\n resolve(bitbybitRunnerResult);\n } else {\n resolve(undefined);\n }\n }\n \n bitbybitRunnerStart();\n "),a={HS:tX,BitByBitContextHelperService:hX.context},l={bitbybit:hX,BABYLON:e,GUI:t,Bit:uX,BitByBit:a,errorHandle:n},[2,new Promise((function(e){return l.resolve=e,new Function(o).apply(l)}))]}))}))}function mX(){if(hX.context.scene.dispose(),oX.enablePhysics){var e=new zE(!0,aX);hX.context.havokPlugin=e}var t=document.getElementById(oX.canvasId);xX(hX.context.engine,t),cX.removeTagsIfNeeded(),hX.context.intervalBag.forEach((function(e){return clearInterval(e)})),hX.context.timeoutBag.forEach((function(e){return clearTimeout(e)})),hX.context.intervalBag.length=0,hX.context.timeoutBag.length=0,hX.context.renderLoopBag.length=0,hX.context.keyPressBag.length=0,hX.context.keyDownBag.length=0,hX.context.keyUpBag.length=0}function gX(){return rX(this,void 0,void 0,(function(){return nX(this,(function(e){return[2,hX.occtWorkerManager.cleanAllCache()]}))}))}function vX(){return rX(this,void 0,void 0,(function(){return nX(this,(function(e){return[2,hX.jscadWorkerManager.cleanAllCache()]}))}))}function xX(e,t){var i=new dr(e);i.clearColor=new Ee(26/255,28/255,31/255,1),new xn("root",i);var s=new Th("Camera",0,10,10,new de(0,0,0),i);s.setPosition(new de(0,10,-20)),s.attachControl(t,!0),s.lowerRadiusLimit=0,s.minZ=0;var r=new cu("HemiLight",new de(0,1,0),i);return r.intensityMode=yo.INTENSITYMODE_ILLUMINANCE,r.intensity=1,i.ambientColor=new Ce(.1,.1,.1),i.metadata={shadowGenerators:[]},hX.context.scene=i,hX.context.engine=e,dX=!1,s.onProjectionMatrixChangedObservable.add((function(){dX=!0})),s.onViewMatrixChangedObservable.add((function(){dX=!0})),i.registerBeforeRender(TX),i.registerAfterRender((function(){cX.handleTags(s,dX,hX.context.engine,i),dX=!1})),{scene:i,camera:s}}var bX=0;function TX(){var e=Date.now(),t=e-bX;bX=e,hX.context.renderLoopBag.forEach((function(e){return e(t)}))}})(),s})())); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bitbybitRunner=t():e.bitbybitRunner=t()}(this,(()=>(()=>{var e={615:(e,t,i)=>{e.exports=function e(t,i,s){function r(o,a){if(!i[o]){if(!t[o]){if(n)return n(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};t[o][0].call(h.exports,(function(e){return r(t[o][1][e]||e)}),h,h.exports,e,t,i,s)}return i[o].exports}for(var n=void 0,o=0;o=48&&e<=57}function T(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function y(e){return"01234567".indexOf(e)>=0}function S(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(e)>=0}function C(e){return 10===e||13===e||8232===e||8233===e}function E(e){return 64==e||36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||92===e||e>=128&&a.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function A(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||92===e||e>=128&&a.NonAsciiIdentifierPart.test(String.fromCharCode(e))}function P(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}}function R(e){return"eval"===e||"arguments"===e}function I(e){if(c&&P(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e||"let"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function M(e,t,i,s,r){var n;x("number"==typeof i,"Comment must have valid position"),g.lastCommentStart>=i||(g.lastCommentStart=i,n={type:e,value:t},v.range&&(n.range=[i,s]),v.loc&&(n.loc=r),v.comments.push(n),v.attachComment&&(v.leadingComments.push(n),v.trailingComments.push(n)))}function O(e){var t,i,s,r;for(t=u-e,i={start:{line:d,column:u-_-e}};u=p&&j({},o.UnexpectedToken,"ILLEGAL");else if(42===i){if(47===h.charCodeAt(u+1))return++u,++u,void(v.comments&&(s=h.slice(e+2,u-2),t.end={line:d,column:u-_},M("Block",s,e,u,t)));++u}else++u;j({},o.UnexpectedToken,"ILLEGAL")}function w(){var e,t;for(t=0===u;u>>="===(r=h.substr(u,4))?(u+=4,{type:t.Punctuator,value:r,lineNumber:d,lineStart:_,start:n,end:u}):">>>"===(s=r.substr(0,3))||"<<="===s||">>="===s?(u+=3,{type:t.Punctuator,value:s,lineNumber:d,lineStart:_,start:n,end:u}):l===(i=s.substr(0,2))[1]&&"+-<>&|".indexOf(l)>=0||"=>"===i?(u+=2,{type:t.Punctuator,value:i,lineNumber:d,lineStart:_,start:n,end:u}):"<>=!+-*%&|^/".indexOf(l)>=0?(++u,{type:t.Punctuator,value:l,lineNumber:d,lineStart:_,start:n,end:u}):void j({},o.UnexpectedToken,"ILLEGAL")}function k(){var e,i,s;if(x(b((s=h[u]).charCodeAt(0))||"."===s,"Numeric literal must start with a decimal digit or a decimal point"),i=u,e="","."!==s){if(e=h[u++],s=h[u],"0"===e){if("x"===s||"X"===s)return++u,function(e){for(var i="";u0&&(s=v.tokens[v.tokens.length-1]).range[0]===e&&"Punctuator"===s.type&&("/"!==s.value&&"/="!==s.value||v.tokens.pop()),v.tokens.push({type:"RegularExpression",value:i.literal,range:[e,u],loc:t})),i}function G(){var e,i,r;return w(),u>=p?{type:t.EOF,lineNumber:d,lineStart:_,start:u,end:u}:E(e=h.charCodeAt(u))?(i=u,{type:1===(r=92===h.charCodeAt(u)?F():B()).length?t.Identifier:I(r)?t.Keyword:"null"===r?t.NullLiteral:"true"===r||"false"===r?t.BooleanLiteral:t.Identifier,value:r,lineNumber:d,lineStart:_,start:i,end:u}):40===e||41===e||59===e?L():39===e||34===e?function(){var e,i,s,r,n,a,l,c,f="",m=!1;for(l=d,c=_,x("'"===(e=h[u])||'"'===e,"String literal must starts with a quote"),i=u,++u;u=0&&u=0?L():U()}return U()}return"Keyword"===e.type?U():L()}():L()}function z(){var e,s,r;return w(),e={start:{line:d,column:u-_}},s=G(),e.end={line:d,column:u-_},s.type!==t.EOF&&(r=h.slice(s.start,s.end),v.tokens.push({type:i[s.type],value:r,range:[s.start,s.end],loc:e})),s}function W(){var e;return u=(e=m).end,d=e.lineNumber,_=e.lineStart,m=void 0!==v.tokens?z():G(),u=e.end,d=e.lineNumber,_=e.lineStart,e}function H(){var e,t,i;e=u,t=d,i=_,m=void 0!==v.tokens?z():G(),u=e,d=t,_=i}function X(e,t){this.line=e,this.column=t}function Y(e,t,i,s){this.start=new X(e,t),this.end=new X(i,s)}function Q(){var e,t,i,s;return e=u,t=d,i=_,w(),s=d!==t,u=e,d=t,_=i,s}function j(e,t){var i,s=Array.prototype.slice.call(arguments,2),r=t.replace(/%(\d)/g,(function(e,t){return x(t":case"<=":case">=":case"instanceof":s=7;break;case"in":s=i?7:0;break;case"<<":case">>":case">>>":s=8;break;case"+":case"-":s=9;break;case"*":case"/":case"%":s=11}return s}function fe(){var e,t,i,s,r;return r=m,e=function(){var e,t,i,s,r,n,o,a,l,h;if(e=m,l=_e(),0===(r=pe(s=m,g.allowIn)))return l;for(s.prec=r,W(),t=[e,m],n=[l,s,o=_e()];(r=pe(m,g.allowIn))>0;){for(;n.length>2&&r<=n[n.length-2].prec;)o=n.pop(),a=n.pop().value,l=n.pop(),i=f.createBinaryExpression(a,l,o),t.pop(),e=t[t.length-1],f.markEnd(i,e),n.push(i);(s=W()).prec=r,n.push(s),t.push(m),i=_e(),n.push(i)}for(i=n[h=n.length-1],t.pop();h>1;)i=f.createBinaryExpression(n[h-1].value,n[h-2],i),h-=2,e=t.pop(),f.markEnd(i,e);return i}(),J("?")&&(W(),t=g.allowIn,g.allowIn=!0,i=me(),g.allowIn=t,q(":"),s=me(),e=f.createConditionalExpression(e,i,s),f.markEnd(e,r)),e}function me(){var e,i,s,n,a,l;return e=m,a=m,n=i=fe(),m.type===t.Punctuator&&("="===(l=m.value)||"*="===l||"/="===l||"%="===l||"+="===l||"-="===l||"<<="===l||">>="===l||">>>="===l||"&="===l||"^="===l||"|="===l)&&(ie(i)||K({},o.InvalidLHSInAssignment),c&&i.type===r.Identifier&&R(i.name)&&K(e,o.StrictLHSAssignment),e=W(),s=me(),n=f.markEnd(f.createAssignmentExpression(e.value,i,s),a)),n}function ge(){var e,t=m;if(e=me(),J(",")){for(e=f.createSequenceExpression([e]);u",i[t.Identifier]="Identifier",i[t.Keyword]="Keyword",i[t.NullLiteral]="Null",i[t.NumericLiteral]="Numeric",i[t.Punctuator]="Punctuator",i[t.StringLiteral]="String",i[t.RegularExpression]="RegularExpression",s=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="],r={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement"},n={Data:1,Get:2,Set:4},o={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalReturn:"Illegal return statement",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode"},a={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")},l={name:"SyntaxTree",processComment:function(e){var t,i;if(!(e.type===r.Program&&e.body.length>0)){for(v.trailingComments.length>0?v.trailingComments[0].range[0]>=e.range[1]?(i=v.trailingComments,v.trailingComments=[]):v.trailingComments.length=0:v.bottomRightStack.length>0&&v.bottomRightStack[v.bottomRightStack.length-1].trailingComments&&v.bottomRightStack[v.bottomRightStack.length-1].trailingComments[0].range[0]>=e.range[1]&&(i=v.bottomRightStack[v.bottomRightStack.length-1].trailingComments,delete v.bottomRightStack[v.bottomRightStack.length-1].trailingComments);v.bottomRightStack.length>0&&v.bottomRightStack[v.bottomRightStack.length-1].range[0]>=e.range[0];)t=v.bottomRightStack.pop();t?t.leadingComments&&t.leadingComments[t.leadingComments.length-1].range[1]<=e.range[0]&&(e.leadingComments=t.leadingComments,delete t.leadingComments):v.leadingComments.length>0&&v.leadingComments[v.leadingComments.length-1].range[1]<=e.range[0]&&(e.leadingComments=v.leadingComments,v.leadingComments=[]),i&&(e.trailingComments=i),v.bottomRightStack.push(e)}},markEnd:function(e,t){return v.range&&(e.range=[t.start,u]),v.loc&&(e.loc=new Y(void 0===t.startLineNumber?t.lineNumber:t.startLineNumber,t.start-(void 0===t.startLineStart?t.lineStart:t.startLineStart),d,u-_),this.postProcess(e)),v.attachComment&&this.processComment(e),e},postProcess:function(e){return v.source&&(e.loc.source=v.source),e},createArrayExpression:function(e){return{type:r.ArrayExpression,elements:e}},createAssignmentExpression:function(e,t,i){return{type:r.AssignmentExpression,operator:e,left:t,right:i}},createBinaryExpression:function(e,t,i){return{type:"||"===e||"&&"===e?r.LogicalExpression:r.BinaryExpression,operator:e,left:t,right:i}},createBlockStatement:function(e){return{type:r.BlockStatement,body:e}},createBreakStatement:function(e){return{type:r.BreakStatement,label:e}},createCallExpression:function(e,t){return{type:r.CallExpression,callee:e,arguments:t}},createCatchClause:function(e,t){return{type:r.CatchClause,param:e,body:t}},createConditionalExpression:function(e,t,i){return{type:r.ConditionalExpression,test:e,consequent:t,alternate:i}},createContinueStatement:function(e){return{type:r.ContinueStatement,label:e}},createDebuggerStatement:function(){return{type:r.DebuggerStatement}},createDoWhileStatement:function(e,t){return{type:r.DoWhileStatement,body:e,test:t}},createEmptyStatement:function(){return{type:r.EmptyStatement}},createExpressionStatement:function(e){return{type:r.ExpressionStatement,expression:e}},createForStatement:function(e,t,i,s){return{type:r.ForStatement,init:e,test:t,update:i,body:s}},createForInStatement:function(e,t,i){return{type:r.ForInStatement,left:e,right:t,body:i,each:!1}},createFunctionDeclaration:function(e,t,i,s){return{type:r.FunctionDeclaration,id:e,params:t,defaults:i,body:s,rest:null,generator:!1,expression:!1}},createFunctionExpression:function(e,t,i,s){return{type:r.FunctionExpression,id:e,params:t,defaults:i,body:s,rest:null,generator:!1,expression:!1}},createIdentifier:function(e){return{type:r.Identifier,name:e}},createIfStatement:function(e,t,i){return{type:r.IfStatement,test:e,consequent:t,alternate:i}},createLabeledStatement:function(e,t){return{type:r.LabeledStatement,label:e,body:t}},createLiteral:function(e){return{type:r.Literal,value:e.value,raw:h.slice(e.start,e.end)}},createMemberExpression:function(e,t,i){return{type:r.MemberExpression,computed:"["===e,object:t,property:i}},createNewExpression:function(e,t){return{type:r.NewExpression,callee:e,arguments:t}},createObjectExpression:function(e){return{type:r.ObjectExpression,properties:e}},createPostfixExpression:function(e,t){return{type:r.UpdateExpression,operator:e,argument:t,prefix:!1}},createProgram:function(e){return{type:r.Program,body:e}},createProperty:function(e,t,i){return{type:r.Property,key:t,value:i,kind:e}},createReturnStatement:function(e){return{type:r.ReturnStatement,argument:e}},createSequenceExpression:function(e){return{type:r.SequenceExpression,expressions:e}},createSwitchCase:function(e,t){return{type:r.SwitchCase,test:e,consequent:t}},createSwitchStatement:function(e,t){return{type:r.SwitchStatement,discriminant:e,cases:t}},createThisExpression:function(){return{type:r.ThisExpression}},createThrowStatement:function(e){return{type:r.ThrowStatement,argument:e}},createTryStatement:function(e,t,i,s){return{type:r.TryStatement,block:e,guardedHandlers:t,handlers:i,finalizer:s}},createUnaryExpression:function(e,t){return"++"===e||"--"===e?{type:r.UpdateExpression,operator:e,argument:t,prefix:!0}:{type:r.UnaryExpression,operator:e,argument:t,prefix:!0}},createVariableDeclaration:function(e,t){return{type:r.VariableDeclaration,declarations:e,kind:t}},createVariableDeclarator:function(e,t){return{type:r.VariableDeclarator,id:e,init:t}},createWhileStatement:function(e,t){return{type:r.WhileStatement,test:e,body:t}},createWithStatement:function(e,t){return{type:r.WithStatement,object:e,body:t}}},e.version="1.2.2",e.tokenize=function(e,i){var s;"string"==typeof e||e instanceof String||(e=String(e)),f=l,u=0,d=(h=e).length>0?1:0,_=0,p=h.length,m=null,g={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1,lastCommentStart:-1},v={},(i=i||{}).tokens=!0,v.tokens=[],v.tokenize=!0,v.openParenToken=-1,v.openCurlyToken=-1,v.range="boolean"==typeof i.range&&i.range,v.loc="boolean"==typeof i.loc&&i.loc,"boolean"==typeof i.comment&&i.comment&&(v.comments=[]),"boolean"==typeof i.tolerant&&i.tolerant&&(v.errors=[]);try{if(H(),m.type===t.EOF)return v.tokens;for(W();m.type!==t.EOF;)try{W()}catch(e){if(v.errors){v.errors.push(e);break}throw e}Oe(),s=v.tokens,void 0!==v.comments&&(s.comments=v.comments),void 0!==v.errors&&(s.errors=v.errors)}catch(e){throw e}finally{v={}}return s},e.parse=function(e,t){var i,s;s=String,"string"==typeof e||e instanceof String||(e=s(e)),f=l,u=0,d=(h=e).length>0?1:0,_=0,p=h.length,m=null,g={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1,lastCommentStart:-1},v={},void 0!==t&&(v.range="boolean"==typeof t.range&&t.range,v.loc="boolean"==typeof t.loc&&t.loc,v.attachComment="boolean"==typeof t.attachComment&&t.attachComment,v.loc&&null!==t.source&&void 0!==t.source&&(v.source=s(t.source)),"boolean"==typeof t.tokens&&t.tokens&&(v.tokens=[]),"boolean"==typeof t.comment&&t.comment&&(v.comments=[]),"boolean"==typeof t.tolerant&&t.tolerant&&(v.errors=[]),v.attachComment&&(v.range=!0,v.comments=[],v.bottomRightStack=[],v.trailingComments=[],v.leadingComments=[]));try{i=Me(),void 0!==v.comments&&(i.comments=v.comments),void 0!==v.tokens&&(Oe(),i.tokens=v.tokens),void 0!==v.errors&&(i.errors=v.errors)}catch(e){throw e}finally{v={}}return i},e.Syntax=function(){var e,t={};for(e in"function"==typeof Object.create&&(t=Object.create(null)),r)r.hasOwnProperty(e)&&(t[e]=r[e]);return"function"==typeof Object.freeze&&Object.freeze(t),t}()}))},{}],1:[function(e,t,i){(function(s){var r=function(){var e={trace:function(){},yy:{},symbols_:{error:2,JSON_PATH:3,DOLLAR:4,PATH_COMPONENTS:5,LEADING_CHILD_MEMBER_EXPRESSION:6,PATH_COMPONENT:7,MEMBER_COMPONENT:8,SUBSCRIPT_COMPONENT:9,CHILD_MEMBER_COMPONENT:10,DESCENDANT_MEMBER_COMPONENT:11,DOT:12,MEMBER_EXPRESSION:13,DOT_DOT:14,STAR:15,IDENTIFIER:16,SCRIPT_EXPRESSION:17,INTEGER:18,END:19,CHILD_SUBSCRIPT_COMPONENT:20,DESCENDANT_SUBSCRIPT_COMPONENT:21,"[":22,SUBSCRIPT:23,"]":24,SUBSCRIPT_EXPRESSION:25,SUBSCRIPT_EXPRESSION_LIST:26,SUBSCRIPT_EXPRESSION_LISTABLE:27,",":28,STRING_LITERAL:29,ARRAY_SLICE:30,FILTER_EXPRESSION:31,QQ_STRING:32,Q_STRING:33,$accept:0,$end:1},terminals_:{2:"error",4:"DOLLAR",12:"DOT",14:"DOT_DOT",15:"STAR",16:"IDENTIFIER",17:"SCRIPT_EXPRESSION",18:"INTEGER",19:"END",22:"[",24:"]",28:",",30:"ARRAY_SLICE",31:"FILTER_EXPRESSION",32:"QQ_STRING",33:"Q_STRING"},productions_:[0,[3,1],[3,2],[3,1],[3,2],[5,1],[5,2],[7,1],[7,1],[8,1],[8,1],[10,2],[6,1],[11,2],[13,1],[13,1],[13,1],[13,1],[13,1],[9,1],[9,1],[20,3],[21,4],[23,1],[23,1],[26,1],[26,3],[27,1],[27,1],[27,1],[25,1],[25,1],[25,1],[29,1],[29,1]],performAction:function(e,i,s,r,n,o,a){r.ast||(r.ast=t,t.initialize());var l=o.length-1;switch(n){case 1:return r.ast.set({expression:{type:"root",value:o[l]}}),r.ast.unshift(),r.ast.yield();case 2:return r.ast.set({expression:{type:"root",value:o[l-1]}}),r.ast.unshift(),r.ast.yield();case 3:return r.ast.unshift(),r.ast.yield();case 4:return r.ast.set({operation:"member",scope:"child",expression:{type:"identifier",value:o[l-1]}}),r.ast.unshift(),r.ast.yield();case 5:case 6:case 11:case 13:case 18:case 21:case 22:case 23:break;case 7:r.ast.set({operation:"member"}),r.ast.push();break;case 8:r.ast.set({operation:"subscript"}),r.ast.push();break;case 9:case 19:r.ast.set({scope:"child"});break;case 10:case 20:r.ast.set({scope:"descendant"});break;case 12:r.ast.set({scope:"child",operation:"member"});break;case 14:r.ast.set({expression:{type:"wildcard",value:o[l]}});break;case 15:r.ast.set({expression:{type:"identifier",value:o[l]}});break;case 16:r.ast.set({expression:{type:"script_expression",value:o[l]}});break;case 17:r.ast.set({expression:{type:"numeric_literal",value:parseInt(o[l])}});break;case 24:o[l].length>1?r.ast.set({expression:{type:"union",value:o[l]}}):this.$=o[l];break;case 25:this.$=[o[l]];break;case 26:this.$=o[l-2].concat(o[l]);break;case 27:this.$={expression:{type:"numeric_literal",value:parseInt(o[l])}},r.ast.set(this.$);break;case 28:this.$={expression:{type:"string_literal",value:o[l]}},r.ast.set(this.$);break;case 29:this.$={expression:{type:"slice",value:o[l]}},r.ast.set(this.$);break;case 30:this.$={expression:{type:"wildcard",value:o[l]}},r.ast.set(this.$);break;case 31:this.$={expression:{type:"script_expression",value:o[l]}},r.ast.set(this.$);break;case 32:this.$={expression:{type:"filter_expression",value:o[l]}},r.ast.set(this.$);break;case 33:case 34:this.$=o[l]}},table:[{3:1,4:[1,2],6:3,13:4,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{1:[3]},{1:[2,1],5:10,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,3],5:21,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,12],12:[2,12],14:[2,12],22:[2,12]},{1:[2,14],12:[2,14],14:[2,14],22:[2,14]},{1:[2,15],12:[2,15],14:[2,15],22:[2,15]},{1:[2,16],12:[2,16],14:[2,16],22:[2,16]},{1:[2,17],12:[2,17],14:[2,17],22:[2,17]},{1:[2,18],12:[2,18],14:[2,18],22:[2,18]},{1:[2,2],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,5],12:[2,5],14:[2,5],22:[2,5]},{1:[2,7],12:[2,7],14:[2,7],22:[2,7]},{1:[2,8],12:[2,8],14:[2,8],22:[2,8]},{1:[2,9],12:[2,9],14:[2,9],22:[2,9]},{1:[2,10],12:[2,10],14:[2,10],22:[2,10]},{1:[2,19],12:[2,19],14:[2,19],22:[2,19]},{1:[2,20],12:[2,20],14:[2,20],22:[2,20]},{13:23,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{13:24,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9],22:[1,25]},{15:[1,29],17:[1,30],18:[1,33],23:26,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{1:[2,4],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,6],12:[2,6],14:[2,6],22:[2,6]},{1:[2,11],12:[2,11],14:[2,11],22:[2,11]},{1:[2,13],12:[2,13],14:[2,13],22:[2,13]},{15:[1,29],17:[1,30],18:[1,33],23:38,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{24:[1,39]},{24:[2,23]},{24:[2,24],28:[1,40]},{24:[2,30]},{24:[2,31]},{24:[2,32]},{24:[2,25],28:[2,25]},{24:[2,27],28:[2,27]},{24:[2,28],28:[2,28]},{24:[2,29],28:[2,29]},{24:[2,33],28:[2,33]},{24:[2,34],28:[2,34]},{24:[1,41]},{1:[2,21],12:[2,21],14:[2,21],22:[2,21]},{18:[1,33],27:42,29:34,30:[1,35],32:[1,36],33:[1,37]},{1:[2,22],12:[2,22],14:[2,22],22:[2,22]},{24:[2,26],28:[2,26]}],defaultActions:{27:[2,23],29:[2,30],30:[2,31],31:[2,32]},parseError:function(e,t){if(!t.recoverable)throw new Error(e);this.trace(e)},parse:function(e){var t=this,i=[0],s=[null],r=[],n=this.table,o="",a=0,l=0,h=0,c=r.slice.call(arguments,1);this.lexer.setInput(e),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,void 0===this.lexer.yylloc&&(this.lexer.yylloc={});var u=this.lexer.yylloc;r.push(u);var d,_=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError?this.parseError=this.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var p,f,m,g,v,x,b,T,y,S={};;){if(m=i[i.length-1],this.defaultActions[m]?g=this.defaultActions[m]:(null==p&&(d=void 0,"number"!=typeof(d=t.lexer.lex()||1)&&(d=t.symbols_[d]||d),p=d),g=n[m]&&n[m][p]),void 0===g||!g.length||!g[0]){var C;for(x in y=[],n[m])this.terminals_[x]&&x>2&&y.push("'"+this.terminals_[x]+"'");C=this.lexer.showPosition?"Parse error on line "+(a+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+y.join(", ")+", got '"+(this.terminals_[p]||p)+"'":"Parse error on line "+(a+1)+": Unexpected "+(1==p?"end of input":"'"+(this.terminals_[p]||p)+"'"),this.parseError(C,{text:this.lexer.match,token:this.terminals_[p]||p,line:this.lexer.yylineno,loc:u,expected:y})}if(g[0]instanceof Array&&g.length>1)throw new Error("Parse Error: multiple actions possible at state: "+m+", token: "+p);switch(g[0]){case 1:i.push(p),s.push(this.lexer.yytext),r.push(this.lexer.yylloc),i.push(g[1]),p=null,f?(p=f,f=null):(l=this.lexer.yyleng,o=this.lexer.yytext,a=this.lexer.yylineno,u=this.lexer.yylloc,h>0&&h--);break;case 2:if(b=this.productions_[g[1]][1],S.$=s[s.length-b],S._$={first_line:r[r.length-(b||1)].first_line,last_line:r[r.length-1].last_line,first_column:r[r.length-(b||1)].first_column,last_column:r[r.length-1].last_column},_&&(S._$.range=[r[r.length-(b||1)].range[0],r[r.length-1].range[1]]),void 0!==(v=this.performAction.apply(S,[o,l,a,this.yy,g[1],s,r].concat(c))))return v;b&&(i=i.slice(0,-1*b*2),s=s.slice(0,-1*b),r=r.slice(0,-1*b)),i.push(this.productions_[g[1]][0]),s.push(S.$),r.push(S._$),T=n[i[i.length-2]][i[i.length-1]],i.push(T);break;case 3:return!0}}return!0}},t={initialize:function(){this._nodes=[],this._node={},this._stash=[]},set:function(e){for(var t in e)this._node[t]=e[t];return this._node},node:function(e){return arguments.length&&(this._node=e),this._node},push:function(){this._nodes.push(this._node),this._node={}},unshift:function(){this._nodes.unshift(this._node),this._node={}},yield:function(){var e=this._nodes;return this.initialize(),e}},i={EOF:1,parseError:function(e,t){if(!this.yy.parser)throw new Error(e);this.yy.parser.parseError(e,t)},setInput:function(e){return this._input=e,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},unput:function(e){var t=e.length,i=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t-1),this.offset-=t;var s=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),i.length-1&&(this.yylineno-=i.length-1);var r=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:i?(i.length===s.length?this.yylloc.first_column:0)+s[s.length-i.length].length-i[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[r[0],r[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(e){this.unput(this.match.slice(e))},pastInput:function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?"...":"")+e.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var e=this.pastInput(),t=new Array(e.length+1).join("-");return e+this.upcomingInput()+"\n"+t+"^"},test_match:function(e,t){var i,s,r;if(this.options.backtrack_lexer&&(r={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(r.yylloc.range=this.yylloc.range.slice(0))),(s=e[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=s.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:s?s[s.length-1].length-s[s.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],i=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),i)return i;if(this._backtrack){for(var n in r)this[n]=r[n];return!1}return!1},next:function(){if(this.done)return this.EOF;var e,t,i,s;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var r=this._currentRules(),n=0;nt[0].length)){if(t=i,s=n,this.options.backtrack_lexer){if(!1!==(e=this.test_match(i,r[n])))return e;if(this._backtrack){t=!1;continue}return!1}if(!this.options.flex)break}return t?!1!==(e=this.test_match(t,r[s]))&&e:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(e){this.conditionStack.push(e)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(e){return(e=this.conditionStack.length-1-Math.abs(e||0))>=0?this.conditionStack[e]:"INITIAL"},pushState:function(e){this.begin(e)},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(e,t,i,s){switch(i){case 0:return 4;case 1:return 14;case 2:return 12;case 3:return 15;case 4:return 16;case 5:return 22;case 6:return 24;case 7:return 28;case 8:return 30;case 9:return 18;case 10:return t.yytext=t.yytext.substr(1,t.yyleng-2),32;case 11:return t.yytext=t.yytext.substr(1,t.yyleng-2),33;case 12:return 17;case 13:return 31}},rules:[/^(?:\$)/,/^(?:\.\.)/,/^(?:\.)/,/^(?:\*)/,/^(?:[a-zA-Z_]+[a-zA-Z0-9_]*)/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?:((-?(?:0|[1-9][0-9]*)))?\:((-?(?:0|[1-9][0-9]*)))?(\:((-?(?:0|[1-9][0-9]*)))?)?)/,/^(?:(-?(?:0|[1-9][0-9]*)))/,/^(?:"(?:\\["bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*")/,/^(?:'(?:\\['bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^'\\])*')/,/^(?:\(.+?\)(?=\]))/,/^(?:\?\(.+?\)(?=\]))/],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13],inclusive:!0}}};function s(){this.yy={}}return e.lexer=i,s.prototype=e,e.Parser=s,new s}();void 0!==e&&void 0!==i&&(i.parser=r,i.Parser=r.Parser,i.parse=function(){return r.parse.apply(r,arguments)},i.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),s.exit(1));var r=e("fs").readFileSync(e("path").normalize(t[1]),"utf8");return i.parser.parse(r)},void 0!==t&&e.main===t&&i.main(s.argv.slice(1)))}).call(this,e("_process"))},{_process:14,fs:12,path:13}],2:[function(e,t,i){t.exports={identifier:"[a-zA-Z_]+[a-zA-Z0-9_]*",integer:"-?(?:0|[1-9][0-9]*)",qq_string:'"(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^"\\\\])*"',q_string:"'(?:\\\\['bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^'\\\\])*'"}},{}],3:[function(e,t,i){var s=e("./dict"),r=e("fs"),n={lex:{macros:{esc:"\\\\",int:s.integer},rules:[["\\$","return 'DOLLAR'"],["\\.\\.","return 'DOT_DOT'"],["\\.","return 'DOT'"],["\\*","return 'STAR'"],[s.identifier,"return 'IDENTIFIER'"],["\\[","return '['"],["\\]","return ']'"],[",","return ','"],["({int})?\\:({int})?(\\:({int})?)?","return 'ARRAY_SLICE'"],["{int}","return 'INTEGER'"],[s.qq_string,"yytext = yytext.substr(1,yyleng-2); return 'QQ_STRING';"],[s.q_string,"yytext = yytext.substr(1,yyleng-2); return 'Q_STRING';"],["\\(.+?\\)(?=\\])","return 'SCRIPT_EXPRESSION'"],["\\?\\(.+?\\)(?=\\])","return 'FILTER_EXPRESSION'"]]},start:"JSON_PATH",bnf:{JSON_PATH:[["DOLLAR",'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()'],["DOLLAR PATH_COMPONENTS",'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()'],["LEADING_CHILD_MEMBER_EXPRESSION","yy.ast.unshift(); return yy.ast.yield()"],["LEADING_CHILD_MEMBER_EXPRESSION PATH_COMPONENTS",'yy.ast.set({ operation: "member", scope: "child", expression: { type: "identifier", value: $1 }}); yy.ast.unshift(); return yy.ast.yield()']],PATH_COMPONENTS:[["PATH_COMPONENT",""],["PATH_COMPONENTS PATH_COMPONENT",""]],PATH_COMPONENT:[["MEMBER_COMPONENT",'yy.ast.set({ operation: "member" }); yy.ast.push()'],["SUBSCRIPT_COMPONENT",'yy.ast.set({ operation: "subscript" }); yy.ast.push() ']],MEMBER_COMPONENT:[["CHILD_MEMBER_COMPONENT",'yy.ast.set({ scope: "child" })'],["DESCENDANT_MEMBER_COMPONENT",'yy.ast.set({ scope: "descendant" })']],CHILD_MEMBER_COMPONENT:[["DOT MEMBER_EXPRESSION",""]],LEADING_CHILD_MEMBER_EXPRESSION:[["MEMBER_EXPRESSION",'yy.ast.set({ scope: "child", operation: "member" })']],DESCENDANT_MEMBER_COMPONENT:[["DOT_DOT MEMBER_EXPRESSION",""]],MEMBER_EXPRESSION:[["STAR",'yy.ast.set({ expression: { type: "wildcard", value: $1 } })'],["IDENTIFIER",'yy.ast.set({ expression: { type: "identifier", value: $1 } })'],["SCRIPT_EXPRESSION",'yy.ast.set({ expression: { type: "script_expression", value: $1 } })'],["INTEGER",'yy.ast.set({ expression: { type: "numeric_literal", value: parseInt($1) } })'],["END",""]],SUBSCRIPT_COMPONENT:[["CHILD_SUBSCRIPT_COMPONENT",'yy.ast.set({ scope: "child" })'],["DESCENDANT_SUBSCRIPT_COMPONENT",'yy.ast.set({ scope: "descendant" })']],CHILD_SUBSCRIPT_COMPONENT:[["[ SUBSCRIPT ]",""]],DESCENDANT_SUBSCRIPT_COMPONENT:[["DOT_DOT [ SUBSCRIPT ]",""]],SUBSCRIPT:[["SUBSCRIPT_EXPRESSION",""],["SUBSCRIPT_EXPRESSION_LIST",'$1.length > 1? yy.ast.set({ expression: { type: "union", value: $1 } }) : $$ = $1']],SUBSCRIPT_EXPRESSION_LIST:[["SUBSCRIPT_EXPRESSION_LISTABLE","$$ = [$1]"],["SUBSCRIPT_EXPRESSION_LIST , SUBSCRIPT_EXPRESSION_LISTABLE","$$ = $1.concat($3)"]],SUBSCRIPT_EXPRESSION_LISTABLE:[["INTEGER",'$$ = { expression: { type: "numeric_literal", value: parseInt($1) } }; yy.ast.set($$)'],["STRING_LITERAL",'$$ = { expression: { type: "string_literal", value: $1 } }; yy.ast.set($$)'],["ARRAY_SLICE",'$$ = { expression: { type: "slice", value: $1 } }; yy.ast.set($$)']],SUBSCRIPT_EXPRESSION:[["STAR",'$$ = { expression: { type: "wildcard", value: $1 } }; yy.ast.set($$)'],["SCRIPT_EXPRESSION",'$$ = { expression: { type: "script_expression", value: $1 } }; yy.ast.set($$)'],["FILTER_EXPRESSION",'$$ = { expression: { type: "filter_expression", value: $1 } }; yy.ast.set($$)']],STRING_LITERAL:[["QQ_STRING","$$ = $1"],["Q_STRING","$$ = $1"]]}};r.readFileSync&&(n.moduleInclude=r.readFileSync(e.resolve("../include/module.js")),n.actionInclude=r.readFileSync(e.resolve("../include/action.js"))),t.exports=n},{"./dict":2,fs:12}],4:[function(e,t,i){var s=e("./aesprim"),r=e("./slice"),n=e("static-eval"),o=e("underscore").uniq,a=function(){return this.initialize.apply(this,arguments)};function l(t,i,r){var n=e("./index"),o=_(s.parse(i).body[0].expression,{"@":t.value}),a=r.replace(/\{\{\s*value\s*\}\}/g,o),l=n.nodes(t.value,a);return l.forEach((function(e){e.path=t.path.concat(e.path.slice(1))})),l}function h(e){return Array.isArray(e)}function c(e){return function(t,i,s,r){var n=t.value,o=t.path,a=[],l=function(t,n){var o;h(t)?(t.forEach((function(e,t){a.length>=r||s(t,e,i)&&a.push({path:n.concat(t),value:e})})),t.forEach((function(t,i){a.length>=r||e&&l(t,n.concat(i))}))):(o=t)&&!(o instanceof Array)&&o instanceof Object&&(this.keys(t).forEach((function(e){a.length>=r||s(e,t[e],i)&&a.push({path:n.concat(e),value:t[e]})})),this.keys(t).forEach((function(i){a.length>=r||e&&l(t[i],n.concat(i))})))}.bind(this);return l(n,o),a}}function u(e){return function(t,i,s){return this.descend(i,t.expression.value,e,s)}}function d(e){return function(t,i,s){return this.traverse(i,t.expression.value,e,s)}}function _(){try{return n.apply(this,arguments)}catch(e){}}function p(e){return e=e.filter((function(e){return e})),o(e,(function(e){return e.path.map((function(e){return String(e).replace("-","--")})).join("-")}))}function f(e){var t=String(e);return t.match(/^-?[0-9]+$/)?parseInt(t):null}a.prototype.initialize=function(){this.traverse=c(!0),this.descend=c()},a.prototype.keys=Object.keys,a.prototype.resolve=function(e){var t=[e.operation,e.scope,e.expression.type].join("-"),i=this._fns[t];if(!i)throw new Error("couldn't resolve key: "+t);return i.bind(this)},a.prototype.register=function(e,t){if(!t instanceof Function)throw new Error("handler must be a function");this._fns[e]=t},a.prototype._fns={"member-child-identifier":function(e,t){var i=e.expression.value,s=t.value;if(s instanceof Object&&i in s)return[{value:s[i],path:t.path.concat(i)}]},"member-descendant-identifier":d((function(e,t,i){return e==i})),"subscript-child-numeric_literal":u((function(e,t,i){return e===i})),"member-child-numeric_literal":u((function(e,t,i){return String(e)===String(i)})),"subscript-descendant-numeric_literal":d((function(e,t,i){return e===i})),"member-child-wildcard":u((function(){return!0})),"member-descendant-wildcard":d((function(){return!0})),"subscript-descendant-wildcard":d((function(){return!0})),"subscript-child-wildcard":u((function(){return!0})),"subscript-child-slice":function(e,t){if(h(t.value)){var i=e.expression.value.split(":").map(f),s=t.value.map((function(e,i){return{value:e,path:t.path.concat(i)}}));return r.apply(null,[s].concat(i))}},"subscript-child-union":function(e,t){var i=[];return e.expression.value.forEach((function(e){var s={operation:"subscript",scope:"child",expression:e.expression},r=this.resolve(s)(s,t);r&&(i=i.concat(r))}),this),p(i)},"subscript-descendant-union":function(t,i,s){var r=e(".."),n=this,o=[];return r.nodes(i,"$..*").slice(1).forEach((function(e){o.length>=s||t.expression.value.forEach((function(t){var i={operation:"subscript",scope:"child",expression:t.expression},s=n.resolve(i)(i,e);o=o.concat(s)}))})),p(o)},"subscript-child-filter_expression":function(e,t,i){var r=e.expression.value.slice(2,-1),n=s.parse(r).body[0].expression;return this.descend(t,null,(function(e,t){return _(n,{"@":t})}),i)},"subscript-descendant-filter_expression":function(e,t,i){var r=e.expression.value.slice(2,-1),n=s.parse(r).body[0].expression;return this.traverse(t,null,(function(e,t){return _(n,{"@":t})}),i)},"subscript-child-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$[{{value}}]")},"member-child-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$.{{value}}")},"member-descendant-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$..value")}},a.prototype._fns["subscript-child-string_literal"]=a.prototype._fns["member-child-identifier"],a.prototype._fns["member-descendant-numeric_literal"]=a.prototype._fns["subscript-descendant-string_literal"]=a.prototype._fns["member-descendant-identifier"],t.exports=a},{"..":"jsonpath","./aesprim":"./aesprim","./index":5,"./slice":7,"static-eval":15,underscore:12}],5:[function(e,t,i){var s=e("assert"),r=e("./dict"),n=e("./parser"),o=e("./handlers"),a=function(){this.initialize.apply(this,arguments)};function l(e){return"[object String]"==Object.prototype.toString.call(e)}a.prototype.initialize=function(){this.parser=new n,this.handlers=new o},a.prototype.parse=function(e){return s.ok(l(e),"we need a path"),this.parser.parse(e)},a.prototype.parent=function(e,t){s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path");var i=this.nodes(e,t)[0];return i.path.pop(),this.value(e,i.path)},a.prototype.apply=function(e,t,i){s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),s.equal(typeof i,"function","fn needs to be function");var r=this.nodes(e,t).sort((function(e,t){return t.path.length-e.path.length}));return r.forEach((function(t){var s=t.path.pop(),r=this.value(e,this.stringify(t.path)),n=t.value=i.call(e,r[s]);r[s]=n}),this),r},a.prototype.value=function(e,t,i){if(s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),arguments.length>=3){var r=this.nodes(e,t).shift();if(!r)return this._vivify(e,t,i);var n=r.path.slice(-1).shift();this.parent(e,this.stringify(r.path))[n]=i}return this.query(e,this.stringify(t),1).shift()},a.prototype._vivify=function(e,t,i){var r=this;s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path");var n=this.parser.parse(t).map((function(e){return e.expression.value})),o=function(t,i){var s=t.pop(),n=r.value(e,t);n||(o(t.concat(),"string"==typeof s?{}:[]),n=r.value(e,t)),n[s]=i};return o(n,i),this.query(e,t)[0]},a.prototype.query=function(e,t,i){return s.ok(e instanceof Object,"obj needs to be an object"),s.ok(l(t),"we need a path"),this.nodes(e,t,i).map((function(e){return e.value}))},a.prototype.paths=function(e,t,i){return s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),this.nodes(e,t,i).map((function(e){return e.path}))},a.prototype.nodes=function(e,t,i){if(s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),0===i)return[];var r=this.parser.parse(t),n=this.handlers,o=[{path:["$"],value:e}],a=[];return r.length&&"root"==r[0].expression.type&&r.shift(),r.length?(r.forEach((function(e,t){if(!(a.length>=i)){var s=n.resolve(e),l=[];o.forEach((function(n){if(!(a.length>=i)){var o=s(e,n,i);t==r.length-1?a=a.concat(o||[]):l=l.concat(o||[])}})),o=l}})),i?a.slice(0,i):a):o},a.prototype.stringify=function(e){s.ok(e,"we need a path");var t="$",i={"descendant-member":"..{{value}}","child-member":".{{value}}","descendant-subscript":"..[{{value}}]","child-subscript":"[{{value}}]"};return(e=this._normalize(e)).forEach((function(e){if("root"!=e.expression.type){var s,r=[e.scope,e.operation].join("-"),n=i[r];if(s="string_literal"==e.expression.type?JSON.stringify(e.expression.value):e.expression.value,!n)throw new Error("couldn't find template "+r);t+=n.replace(/{{value}}/,s)}})),t},a.prototype._normalize=function(e){if(s.ok(e,"we need a path"),"string"==typeof e)return this.parser.parse(e);if(Array.isArray(e)&&"string"==typeof e[0]){var t=[{expression:{type:"root",value:"$"}}];return e.forEach((function(e,i){if("$"!=e||0!==i)if("string"==typeof e&&e.match("^"+r.identifier+"$"))t.push({operation:"member",scope:"child",expression:{value:e,type:"identifier"}});else{var s="number"==typeof e?"numeric_literal":"string_literal";t.push({operation:"subscript",scope:"child",expression:{value:e,type:s}})}})),t}if(Array.isArray(e)&&"object"==typeof e[0])return e;throw new Error("couldn't understand path "+e)},a.Handlers=o,a.Parser=n;var h=new a;h.JSONPath=a,t.exports=h},{"./dict":2,"./handlers":4,"./parser":6,assert:8}],6:[function(e,t,i){var s=e("./grammar"),r=e("../generated/parser"),n=function(){var e=new r.Parser,t=e.parseError;return e.yy.parseError=function(){e.yy.ast&&e.yy.ast.initialize(),t.apply(e,arguments)},e};n.grammar=s,t.exports=n},{"../generated/parser":1,"./grammar":3}],7:[function(e,t,i){function s(e){return String(e).match(/^[0-9]+$/)?parseInt(e):Number.isFinite(e)?parseInt(e,10):0}t.exports=function(e,t,i,r){if("string"==typeof t)throw new Error("start cannot be a string");if("string"==typeof i)throw new Error("end cannot be a string");if("string"==typeof r)throw new Error("step cannot be a string");var n=e.length;if(0===r)throw new Error("step cannot be zero");if(r=r?s(r):1,i=i<0?n+i:i,t=s(0===(t=t<0?n+t:t)?0:t||(r>0?0:n-1)),i=s(0===i?0:i||(r>0?n:-1)),t=r>0?Math.max(0,t):Math.min(n,t),i=r>0?Math.min(i,n):Math.max(-1,i),r>0&&i<=t)return[];if(r<0&&t<=i)return[];for(var o=[],a=t;a!=i&&!(r<0&&a<=i||r>0&&a>=i);a+=r)o.push(e[a]);return o}},{}],8:[function(e,t,i){var s=e("util/"),r=Array.prototype.slice,n=Object.prototype.hasOwnProperty,o=t.exports=c;function a(e,t){return s.isUndefined(t)?""+t:s.isNumber(t)&&!isFinite(t)||s.isFunction(t)||s.isRegExp(t)?t.toString():t}function l(e,t){return s.isString(e)?e.length=0;a--)if(l[a]!=h[a])return!1;for(a=l.length-1;a>=0;a--)if(!u(e[o=l[a]],t[o]))return!1;return!0}(e,t):e==t}function d(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function _(e,t){return!(!e||!t)&&("[object RegExp]"==Object.prototype.toString.call(t)?t.test(e):e instanceof t||!0===t.call({},e))}function p(e,t,i,r){var n;s.isString(i)&&(r=i,i=null);try{t()}catch(e){n=e}if(r=(i&&i.name?" ("+i.name+").":".")+(r?" "+r:"."),e&&!n&&h(n,i,"Missing expected exception"+r),!e&&_(n,i)&&h(n,i,"Got unwanted exception"+r),e&&n&&i&&!_(n,i)||!e&&n)throw n}o.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=function(e){return l(JSON.stringify(e.actual,a),128)+" "+e.operator+" "+l(JSON.stringify(e.expected,a),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||h;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var i=new Error;if(i.stack){var s=i.stack,r=t.name,n=s.indexOf("\n"+r);if(n>=0){var o=s.indexOf("\n",n+1);s=s.substring(o+1)}this.stack=s}}},s.inherits(o.AssertionError,Error),o.fail=h,o.ok=c,o.equal=function(e,t,i){e!=t&&h(e,t,i,"==",o.equal)},o.notEqual=function(e,t,i){e==t&&h(e,t,i,"!=",o.notEqual)},o.deepEqual=function(e,t,i){u(e,t)||h(e,t,i,"deepEqual",o.deepEqual)},o.notDeepEqual=function(e,t,i){u(e,t)&&h(e,t,i,"notDeepEqual",o.notDeepEqual)},o.strictEqual=function(e,t,i){e!==t&&h(e,t,i,"===",o.strictEqual)},o.notStrictEqual=function(e,t,i){e===t&&h(e,t,i,"!==",o.notStrictEqual)},o.throws=function(e,t,i){p.apply(this,[!0].concat(r.call(arguments)))},o.doesNotThrow=function(e,t){p.apply(this,[!1].concat(r.call(arguments)))},o.ifError=function(e){if(e)throw e};var f=Object.keys||function(e){var t=[];for(var i in e)n.call(e,i)&&t.push(i);return t}},{"util/":11}],9:[function(e,t,i){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}},{}],10:[function(e,t,i){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],11:[function(e,t,s){(function(t,i){var r=/%[sdj%]/g;s.format=function(e){if(!g(e)){for(var t=[],i=0;i=n)return e;switch(e){case"%s":return String(s[i++]);case"%d":return Number(s[i++]);case"%j":try{return JSON.stringify(s[i++])}catch(e){return"[Circular]"}default:return e}})),l=s[i];i=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),p(t)?i.showHidden=t:t&&s._extend(i,t),v(i.showHidden)&&(i.showHidden=!1),v(i.depth)&&(i.depth=2),v(i.colors)&&(i.colors=!1),v(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=l),c(i,e,i.depth)}function l(e,t){var i=a.styles[t];return i?"["+a.colors[i][0]+"m"+e+"["+a.colors[i][1]+"m":e}function h(e,t){return e}function c(e,t,i){if(e.customInspect&&t&&S(t.inspect)&&t.inspect!==s.inspect&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(i,e);return g(r)||(r=c(e,r,i)),r}var n=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(g(t)){var i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}return m(t)?e.stylize(""+t,"number"):p(t)?e.stylize(""+t,"boolean"):f(t)?e.stylize("null","null"):void 0}(e,t);if(n)return n;var o=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,i){t[e]=!0})),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),y(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return u(t);if(0===o.length){if(S(t)){var l=t.name?": "+t.name:"";return e.stylize("[Function"+l+"]","special")}if(x(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(T(t))return e.stylize(Date.prototype.toString.call(t),"date");if(y(t))return u(t)}var h,b="",C=!1,E=["{","}"];return _(t)&&(C=!0,E=["[","]"]),S(t)&&(b=" [Function"+(t.name?": "+t.name:"")+"]"),x(t)&&(b=" "+RegExp.prototype.toString.call(t)),T(t)&&(b=" "+Date.prototype.toUTCString.call(t)),y(t)&&(b=" "+u(t)),0!==o.length||C&&0!=t.length?i<0?x(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),h=C?function(e,t,i,s,r){for(var n=[],o=0,a=t.length;o60?i[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}(h,b,E)):E[0]+b+E[1]}function u(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,i,s,r,n){var o,a,l;if((l=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?a=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(a=e.stylize("[Setter]","special")),P(s,r)||(o="["+r+"]"),a||(e.seen.indexOf(l.value)<0?(a=f(i)?c(e,l.value,null):c(e,l.value,i-1)).indexOf("\n")>-1&&(a=n?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),v(o)){if(n&&r.match(/^\d+$/))return a;(o=JSON.stringify(""+r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+a}function _(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function f(e){return null===e}function m(e){return"number"==typeof e}function g(e){return"string"==typeof e}function v(e){return void 0===e}function x(e){return b(e)&&"[object RegExp]"===C(e)}function b(e){return"object"==typeof e&&null!==e}function T(e){return b(e)&&"[object Date]"===C(e)}function y(e){return b(e)&&("[object Error]"===C(e)||e instanceof Error)}function S(e){return"function"==typeof e}function C(e){return Object.prototype.toString.call(e)}function E(e){return e<10?"0"+e.toString(10):e.toString(10)}s.debuglog=function(e){if(v(n)&&(n=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!o[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var i=t.pid;o[e]=function(){var t=s.format.apply(s,arguments);console.error("%s %d: %s",e,i,t)}}else o[e]=function(){};return o[e]},s.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},s.isArray=_,s.isBoolean=p,s.isNull=f,s.isNullOrUndefined=function(e){return null==e},s.isNumber=m,s.isString=g,s.isSymbol=function(e){return"symbol"==typeof e},s.isUndefined=v,s.isRegExp=x,s.isObject=b,s.isDate=T,s.isError=y,s.isFunction=S,s.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},s.isBuffer=e("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function P(e,t){return Object.prototype.hasOwnProperty.call(e,t)}s.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[E(e.getHours()),E(e.getMinutes()),E(e.getSeconds())].join(":"),[e.getDate(),A[e.getMonth()],t].join(" ")),s.format.apply(s,arguments))},s.inherits=e("inherits"),s._extend=function(e,t){if(!t||!b(t))return e;for(var i=Object.keys(t),s=i.length;s--;)e[i[s]]=t[i[s]];return e}}).call(this,e("_process"),void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":10,_process:14,inherits:9}],12:[function(e,t,i){},{}],13:[function(e,t,i){(function(e){function t(e,t){for(var i=0,s=e.length-1;s>=0;s--){var r=e[s];"."===r?e.splice(s,1):".."===r?(e.splice(s,1),i++):i&&(e.splice(s,1),i--)}if(t)for(;i--;i)e.unshift("..");return e}function s(e,t){if(e.filter)return e.filter(t);for(var i=[],s=0;s=-1&&!r;n--){var o=n>=0?arguments[n]:e.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(i=o+"/"+i,r="/"===o.charAt(0))}return(r?"/":"")+(i=t(s(i.split("/"),(function(e){return!!e})),!r).join("/"))||"."},i.normalize=function(e){var n=i.isAbsolute(e),o="/"===r(e,-1);return(e=t(s(e.split("/"),(function(e){return!!e})),!n).join("/"))||n||(e="."),e&&o&&(e+="/"),(n?"/":"")+e},i.isAbsolute=function(e){return"/"===e.charAt(0)},i.join=function(){var e=Array.prototype.slice.call(arguments,0);return i.normalize(s(e,(function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e})).join("/"))},i.relative=function(e,t){function s(e){for(var t=0;t=0&&""===e[i];i--);return t>i?[]:e.slice(t,i-t+1)}e=i.resolve(e).substr(1),t=i.resolve(t).substr(1);for(var r=s(e.split("/")),n=s(t.split("/")),o=Math.min(r.length,n.length),a=o,l=0;l=1;--n)if(47===(t=e.charCodeAt(n))){if(!r){s=n;break}}else r=!1;return-1===s?i?"/":".":i&&1===s?"/":e.slice(0,s)},i.basename=function(e,t){var i=function(e){"string"!=typeof e&&(e+="");var t,i=0,s=-1,r=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!r){i=t+1;break}}else-1===s&&(r=!1,s=t+1);return-1===s?"":e.slice(i,s)}(e);return t&&i.substr(-1*t.length)===t&&(i=i.substr(0,i.length-t.length)),i},i.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,i=0,s=-1,r=!0,n=0,o=e.length-1;o>=0;--o){var a=e.charCodeAt(o);if(47!==a)-1===s&&(r=!1,s=o+1),46===a?-1===t?t=o:1!==n&&(n=1):-1!==t&&(n=-1);else if(!r){i=o+1;break}}return-1===t||-1===s||0===n||1===n&&t===s-1&&t===i+1?"":e.slice(t,s)};var r=function(e,t,i){return e.substr(t,i)}}).call(this,e("_process"))},{_process:14}],14:[function(e,t,i){var s,r,n=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function l(e){if(s===setTimeout)return setTimeout(e,0);if((s===o||!s)&&setTimeout)return s=setTimeout,setTimeout(e,0);try{return s(e,0)}catch(t){try{return s.call(null,e,0)}catch(t){return s.call(this,e,0)}}}!function(){try{s="function"==typeof setTimeout?setTimeout:o}catch(e){s=o}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var h,c=[],u=!1,d=-1;function _(){u&&h&&(u=!1,h.length?c=h.concat(c):d=-1,c.length&&p())}function p(){if(!u){var e=l(_);u=!0;for(var t=c.length;t;){for(h=c,c=[];++d1)for(var i=1;i"===_?h>d:">="===_?h>=d:"|"===_?h|d:"&"===_?h&d:"^"===_?h^d:"&&"===_?h&&d:"||"===_?h||d:i}if("Identifier"===r.type)return{}.hasOwnProperty.call(t,r.name)?t[r.name]:i;if("ThisExpression"===r.type)return{}.hasOwnProperty.call(t,"this")?t.this:i;if("CallExpression"===r.type){var p=e(r.callee);if(p===i)return i;if("function"!=typeof p)return i;var f=r.callee.object?e(r.callee.object):i;f===i&&(f=null);var m=[];for(l=0,h=r.arguments.length;l{e.exports=function(){var e={},t=this,i=(new Function("try {return this===window;}catch(e){ return false;}"),new Function("try {return this===global;}catch(e){return false;}")),s=new Function("try {return typeof importScripts === 'function';}catch(e){return false;}");if(i()&&s(),i()||s()){var r=t;if(s()){onmessage=function(e){if(e.data.className&&e.data.methodName){var i=(s=e.data.className,r=e.data.methodName,n=t,s.split(".").forEach((function(e){n&&(n=n[e])})),n?n[r]:null);if(!i)return console.error("could not find "+e.data.className+"."+e.data.methodName);postMessage({result:i.apply(null,e.data.args),id:e.data.id})}var s,r,n}}}return function(e,t,i){"use strict";t.geom=t.geom||{},t.exe=t.exe||{},t.eval=t.eval||{},t.core=t.core||{},t.promhx=t.promhx||{};var s={},r=function(){return P.__string_rec(this,"")};function n(e,t){function i(){}i.prototype=e;var s=new i;for(var r in t)s[r]=t[r];return t.toString!==Object.prototype.toString&&(s.toString=t.toString),s}var o=function(){};s.HxOverrides=o,o.__name__=["HxOverrides"],o.strDate=function(e){switch(e.length){case 8:var t=e.split(":"),i=new Date;return i.setTime(0),i.setUTCHours(t[0]),i.setUTCMinutes(t[1]),i.setUTCSeconds(t[2]),i;case 10:var s=e.split("-");return new Date(s[0],s[1]-1,s[2],0,0,0);case 19:var r=e.split(" "),n=r[0].split("-"),o=r[1].split(":");return new Date(n[0],n[1]-1,n[2],o[0],o[1],o[2]);default:throw new A("Invalid date format : "+e)}},o.cca=function(e,t){var i=e.charCodeAt(t);if(i==i)return i},o.substr=function(e,t,i){return null!=t&&0!=t&&null!=i&&i<0?"":(null==i&&(i=e.length),t<0?(t=e.length+t)<0&&(t=0):i<0&&(i=e.length+i-t),e.substr(t,i))},o.iter=function(e){return{cur:0,arr:e,hasNext:function(){return this.cur0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n),n=0),this.serialize(e[d]))}n>0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n)),this.buf.b+="h";break;case l:this.buf.b+="l";for(var _=e.h,f=null;null!=_;){var m;f=_[0],_=_[1],m=f,this.serialize(m)}this.buf.b+="h";break;case Date:var v=e;this.buf.b+="v",this.buf.add(v.getTime());break;case y:this.buf.b+="b";for(var T=e,C=T.keys();C.hasNext();){var E=C.next();this.serializeString(E),this.serialize(null!=ft[E]?T.getReserved(E):T.h[E])}this.buf.b+="h";break;case x:this.buf.b+="q";for(var R=e,I=R.keys();I.hasNext();){var M=I.next();this.buf.b+=":",this.buf.b+=null==M?"null":""+M,this.serialize(R.h[M])}this.buf.b+="h";break;case b:this.buf.b+="M";for(var O=e,D=O.keys();D.hasNext();){var w=D.next(),N=h.field(w,"__id__");h.deleteField(w,"__id__"),this.serialize(w),w.__id__=N,this.serialize(O.h[w.__id__])}this.buf.b+="h";break;case S:for(var F=e,B=0,L=F.length-2,k=new u,V=g.BASE64;B>2)),k.add(V.charAt(63&(U<<4|G>>4))),k.add(V.charAt(63&(G<<2|z>>6))),k.add(V.charAt(63&z))}if(B==L){var W=F.get(B++),H=F.get(B++);k.add(V.charAt(W>>2)),k.add(V.charAt(63&(W<<4|H>>4))),k.add(V.charAt(H<<2&63))}else if(B==L+1){var X=F.get(B++);k.add(V.charAt(X>>2)),k.add(V.charAt(X<<4&63))}var Y=k.b;this.buf.b+="s",null==Y.length?this.buf.b+="null":this.buf.b+=""+Y.length,this.buf.b+=":",this.buf.b+=null==Y?"null":""+Y;break;default:this.useCache&&this.cache.pop(),null!=e.hxSerialize?(this.buf.b+="C",this.serializeString(p.getClassName(r)),this.useCache&&this.cache.push(e),e.hxSerialize(this),this.buf.b+="g"):(this.buf.b+="c",this.serializeString(p.getClassName(r)),this.useCache&&this.cache.push(e),this.serializeFields(e))}break;case 4:if(P.__instanceof(e,_t)){var Q=p.getClassName(e);this.buf.b+="A",this.serializeString(Q)}else if(P.__instanceof(e,pt))this.buf.b+="B",this.serializeString(p.getEnumName(e));else{if(this.useCache&&this.serializeRef(e))return;this.buf.b+="o",this.serializeFields(e)}break;case 7:var j=t[2];if(this.useCache){if(this.serializeRef(e))return;this.cache.pop()}this.useEnumIndex?this.buf.b+="j":this.buf.b+="w",this.serializeString(p.getEnumName(j)),this.useEnumIndex?(this.buf.b+=":",this.buf.b+=c.string(e[1])):this.serializeString(e[0]),this.buf.b+=":";var K=e.length;this.buf.b+=c.string(K-2);for(var $=2;$57)break;e=10*e+(s-48),this.pos++}else{if(this.pos!=i)break;t=!0,this.pos++}}return t&&(e*=-1),e},readFloat:function(){for(var e=this.pos;;){var t=this.buf.charCodeAt(this.pos);if(!(t>=43&&t<58||101==t||69==t))break;this.pos++}return c.parseFloat(o.substr(this.buf,e,this.pos-e))},unserializeObject:function(e){for(;;){if(this.pos>=this.length)throw new A("Invalid object");if(103==this.buf.charCodeAt(this.pos))break;var t=this.unserialize();if("string"!=typeof t)throw new A("Invalid object key");var i=this.unserialize();e[t]=i}this.pos++},unserializeEnum:function(e,t){if(58!=this.get(this.pos++))throw new A("Invalid enum format");var i=this.readDigits();if(0==i)return p.createEnum(e,t);for(var s=[];i-- >0;)s.push(this.unserialize());return p.createEnum(e,t,s)},unserialize:function(){switch(this.get(this.pos++)){case 110:return null;case 116:return!0;case 102:return!1;case 122:return 0;case 105:return this.readDigits();case 100:return this.readFloat();case 121:var e=this.readDigits();if(58!=this.get(this.pos++)||this.length-this.pos=this.cache.length)throw new A("Invalid reference");return this.cache[a];case 82:var h=this.readDigits();if(h<0||h>=this.scache.length)throw new A("Invalid string reference");return this.scache[h];case 120:throw new A(this.unserialize());case 99:var c=this.unserialize(),u=this.resolver.resolveClass(c);if(null==u)throw new A("Class not found "+c);var _=p.createEmptyInstance(u);return this.cache.push(_),this.unserializeObject(_),_;case 119:var f=this.unserialize(),m=this.resolver.resolveEnum(f);if(null==m)throw new A("Enum not found "+f);var g=this.unserializeEnum(m,this.unserialize());return this.cache.push(g),g;case 106:var T=this.unserialize(),C=this.resolver.resolveEnum(T);if(null==C)throw new A("Enum not found "+T);this.pos++;var E=this.readDigits(),P=p.getEnumConstructs(C)[E];if(null==P)throw new A("Unknown enum index "+T+"@"+E);var R=this.unserializeEnum(C,P);return this.cache.push(R),R;case 108:var I=new l;for(this.cache.push(I),this.buf;104!=this.buf.charCodeAt(this.pos);)I.add(this.unserialize());return this.pos++,I;case 98:var M=new y;for(this.cache.push(M),this.buf;104!=this.buf.charCodeAt(this.pos);){var O=this.unserialize();M.set(O,this.unserialize())}return this.pos++,M;case 113:var D=new x;this.cache.push(D),this.buf;for(var w=this.get(this.pos++);58==w;){var N=this.readDigits();D.set(N,this.unserialize()),w=this.get(this.pos++)}if(104!=w)throw new A("Invalid IntMap format");return D;case 77:var F=new b;for(this.cache.push(F),this.buf;104!=this.buf.charCodeAt(this.pos);){var B=this.unserialize();F.set(B,this.unserialize())}return this.pos++,F;case 118:var L;if(this.buf.charCodeAt(this.pos)>=48&&this.buf.charCodeAt(this.pos)<=57&&this.buf.charCodeAt(this.pos+1)>=48&&this.buf.charCodeAt(this.pos+1)<=57&&this.buf.charCodeAt(this.pos+2)>=48&&this.buf.charCodeAt(this.pos+2)<=57&&this.buf.charCodeAt(this.pos+3)>=48&&this.buf.charCodeAt(this.pos+3)<=57&&45==this.buf.charCodeAt(this.pos+4)){var k=o.substr(this.buf,this.pos,19);L=o.strDate(k),this.pos+=19}else{var V=this.readFloat(),U=new Date;U.setTime(V),L=U}return this.cache.push(L),L;case 115:var G=this.readDigits(),z=this.buf;if(58!=this.get(this.pos++)||this.length-this.pos>2)+(Y>=2?Y-1:0);for(var Q=X+(G-Y),j=S.alloc(H),K=0;X>4);var Z=W[d.fastCodeAt(z,X++)];j.set(K++,q<<4|Z>>2);var J=W[d.fastCodeAt(z,X++)];j.set(K++,Z<<6|J)}if(Y>=2){var ee=W[d.fastCodeAt(z,X++)],te=W[d.fastCodeAt(z,X++)];if(j.set(K++,ee<<2|te>>4),3==Y){var ie=W[d.fastCodeAt(z,X++)];j.set(K++,te<<4|ie>>2)}}return this.pos+=G,this.cache.push(j),j;case 67:var se=this.unserialize(),re=this.resolver.resolveClass(se);if(null==re)throw new A("Class not found "+se);var ne=p.createEmptyInstance(re);if(this.cache.push(ne),ne.hxUnserialize(this),103!=this.get(this.pos++))throw new A("Invalid custom data");return ne;case 65:var oe=this.unserialize(),ae=this.resolver.resolveClass(oe);if(null==ae)throw new A("Class not found "+oe);return ae;case 66:var le=this.unserialize(),he=this.resolver.resolveEnum(le);if(null==he)throw new A("Enum not found "+le);return he}throw this.pos--,new A("Invalid char "+this.buf.charAt(this.pos)+" at position "+this.pos)},__class__:v};var x=function(){this.h={}};s["haxe.ds.IntMap"]=x,x.__name__=["haxe","ds","IntMap"],x.__interfaces__=[f],x.prototype={set:function(e,t){this.h[e]=t},remove:function(e){return!!this.h.hasOwnProperty(e)&&(delete this.h[e],!0)},keys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(0|t);return o.iter(e)},__class__:x};var b=function(){this.h={},this.h.__keys__={}};s["haxe.ds.ObjectMap"]=b,b.__name__=["haxe","ds","ObjectMap"],b.__interfaces__=[f],b.prototype={set:function(e,t){var i=e.__id__||(e.__id__=++b.count);this.h[i]=t,this.h.__keys__[i]=e},keys:function(){var e=[];for(var t in this.h.__keys__)this.h.hasOwnProperty(t)&&e.push(this.h.__keys__[t]);return o.iter(e)},__class__:b};var T=s["haxe.ds.Option"]={__ename__:["haxe","ds","Option"],__constructs__:["Some","None"]};T.Some=function(e){var t=["Some",0,e];return t.__enum__=T,t.toString=r,t},T.None=["None",1],T.None.toString=r,T.None.__enum__=T;var y=function(){this.h={}};s["haxe.ds.StringMap"]=y,y.__name__=["haxe","ds","StringMap"],y.__interfaces__=[f],y.prototype={set:function(e,t){null!=ft[e]?this.setReserved(e,t):this.h[e]=t},get:function(e){return null!=ft[e]?this.getReserved(e):this.h[e]},setReserved:function(e,t){null==this.rh&&(this.rh={}),this.rh["$"+e]=t},getReserved:function(e){return null==this.rh?null:this.rh["$"+e]},keys:function(){var e=this.arrayKeys();return o.iter(e)},arrayKeys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(t);if(null!=this.rh)for(var t in this.rh)36==t.charCodeAt(0)&&e.push(t.substr(1));return e},__class__:y};var S=function(e){this.length=e.byteLength,this.b=new gt(e),this.b.bufferValue=e,e.hxBytes=this,e.bytes=this.b};s["haxe.io.Bytes"]=S,S.__name__=["haxe","io","Bytes"],S.alloc=function(e){return new S(new mt(e))},S.prototype={get:function(e){return this.b[e]},set:function(e,t){this.b[e]=255&t},__class__:S};var C=s["haxe.io.Error"]={__ename__:["haxe","io","Error"],__constructs__:["Blocked","Overflow","OutsideBounds","Custom"]};C.Blocked=["Blocked",0],C.Blocked.toString=r,C.Blocked.__enum__=C,C.Overflow=["Overflow",1],C.Overflow.toString=r,C.Overflow.__enum__=C,C.OutsideBounds=["OutsideBounds",2],C.OutsideBounds.toString=r,C.OutsideBounds.__enum__=C,C.Custom=function(e){var t=["Custom",3,e];return t.__enum__=C,t.toString=r,t};var E=function(){};s["haxe.io.FPHelper"]=E,E.__name__=["haxe","io","FPHelper"],E.i32ToFloat=function(e){var t=e>>>23&255,i=8388607&e;return 0==i&&0==t?0:(1-(e>>>31<<1))*(1+Math.pow(2,-23)*i)*Math.pow(2,t-127)},E.floatToI32=function(e){if(0==e)return 0;var t;t=e<0?-e:e;var i=Math.floor(Math.log(t)/.6931471805599453);return i<-127?i=-127:i>128&&(i=128),(e<0?-2147483648:0)|i+127<<23|8388607&Math.round(8388608*(t/Math.pow(2,i)-1))},E.i64ToDouble=function(e,t){var i=(t>>20&2047)-1023,s=4294967296*(1048575&t)+2147483648*(e>>>31)+(2147483647&e);return 0==s&&-1023==i?0:(1-(t>>>31<<1))*(1+Math.pow(2,-52)*s)*Math.pow(2,i)},E.doubleToI64=function(e){var t=E.i64tmp;if(0==e)t.low=0,t.high=0;else{var i;i=e<0?-e:e;var s,r=Math.floor(Math.log(i)/.6931471805599453),n=4503599627370496*(i/Math.pow(2,r)-1),o=0|(s=Math.round(n)),a=s/4294967296|0;t.low=o,t.high=(e<0?-2147483648:0)|r+1023<<20|a}return t};var A=function(e){Error.call(this),this.val=e,this.message=String(e),Error.captureStackTrace&&Error.captureStackTrace(this,A)};s["js._Boot.HaxeError"]=A,A.__name__=["js","_Boot","HaxeError"],A.__super__=Error,A.prototype=n(Error.prototype,{__class__:A});var P=function(){};s["js.Boot"]=P,P.__name__=["js","Boot"],P.getClass=function(e){if(e instanceof Array&&null==e.__enum__)return Array;var t=e.__class__;if(null!=t)return t;var i=P.__nativeClassName(e);return null!=i?P.__resolveNativeClass(i):null},P.__string_rec=function(e,t){if(null==e)return"null";if(t.length>=5)return"<...>";var i=typeof e;switch("function"==i&&(e.__name__||e.__ename__)&&(i="object"),i){case"object":if(e instanceof Array){if(e.__enum__){if(2==e.length)return e[0];var s=e[0]+"(";t+="\t";for(var r=2,n=e.length;r0?",":"")+P.__string_rec(e[c],t)}return l+"]"}var u;try{u=e.toString}catch(e){return e instanceof A&&(e=e.val),"???"}if(null!=u&&u!=Object.toString&&"function"==typeof u){var d=e.toString();if("[object Object]"!=d)return d}var _=null,p="{\n";t+="\t";var f=null!=e.hasOwnProperty;for(var _ in e)f&&!e.hasOwnProperty(_)||"prototype"!=_&&"__class__"!=_&&"__super__"!=_&&"__interfaces__"!=_&&"__properties__"!=_&&(2!=p.length&&(p+=", \n"),p+=t+_+" : "+P.__string_rec(e[_],t));return p+"\n"+(t=t.substring(1))+"}";case"function":return"";case"string":return e;default:return String(e)}},P.__interfLoop=function(e,t){if(null==e)return!1;if(e==t)return!0;var i=e.__interfaces__;if(null!=i)for(var s=0,r=i.length;se.byteLength)throw new A(C.OutsideBounds)};s["js.html.compat.DataView"]=I,I.__name__=["js","html","compat","DataView"],I.prototype={getInt8:function(e){var t=this.buf.a[this.offset+e];return t>=128?t-256:t},getUint8:function(e){return this.buf.a[this.offset+e]},getInt16:function(e,t){var i=this.getUint16(e,t);return i>=32768?i-65536:i},getUint16:function(e,t){return t?this.buf.a[this.offset+e]|this.buf.a[this.offset+e+1]<<8:this.buf.a[this.offset+e]<<8|this.buf.a[this.offset+e+1]},getInt32:function(e,t){var i=this.offset+e,s=this.buf.a[i++],r=this.buf.a[i++],n=this.buf.a[i++],o=this.buf.a[i++];return t?s|r<<8|n<<16|o<<24:o|n<<8|r<<16|s<<24},getUint32:function(e,t){var i=this.getInt32(e,t);return i<0?i+4294967296:i},getFloat32:function(e,t){return E.i32ToFloat(this.getInt32(e,t))},getFloat64:function(e,t){var i=this.getInt32(e,t),s=this.getInt32(e+4,t);return E.i64ToDouble(t?i:s,t?s:i)},setInt8:function(e,t){this.buf.a[e+this.offset]=t<0?t+128&255:255&t},setUint8:function(e,t){this.buf.a[e+this.offset]=255&t},setInt16:function(e,t,i){this.setUint16(e,t<0?t+65536:t,i)},setUint16:function(e,t,i){var s=e+this.offset;i?(this.buf.a[s]=255&t,this.buf.a[s++]=t>>8&255):(this.buf.a[s++]=t>>8&255,this.buf.a[s]=255&t)},setInt32:function(e,t,i){this.setUint32(e,t,i)},setUint32:function(e,t,i){var s=e+this.offset;i?(this.buf.a[s++]=255&t,this.buf.a[s++]=t>>8&255,this.buf.a[s++]=t>>16&255,this.buf.a[s++]=t>>>24):(this.buf.a[s++]=t>>>24,this.buf.a[s++]=t>>16&255,this.buf.a[s++]=t>>8&255,this.buf.a[s++]=255&t)},setFloat32:function(e,t,i){this.setUint32(e,E.floatToI32(t),i)},setFloat64:function(e,t,i){var s=E.doubleToI64(t);i?(this.setUint32(e,s.low),this.setUint32(e,s.high)):(this.setUint32(e,s.high),this.setUint32(e,s.low))},__class__:I};var M=function(){};s["js.html.compat.Uint8Array"]=M,M.__name__=["js","html","compat","Uint8Array"],M._new=function(e,t,i){var s;if("number"==typeof e){s=[];for(var r=0;ri.byteLength)throw new A("set() outside of range");for(var r=0,n=e.byteLength;ri.byteLength)throw new A("set() outside of range");for(var l=0,h=a.length;l0||t.handleError(e._errorVal),e._resolved&&!e._pending)try{t.handleResolve(i(e._val))}catch(e){e instanceof A&&(e=e.val),t.handleError(e)}},O.linkAll=function(e,t){for(var i=function(i,s,r){if(0==i.length||O.allFulfilled(i)){for(var n,o=[],a=nt(e)();a.hasNext();){var l=a.next();o.push(l==s?r:l._val)}n=o,t.handleResolve(n)}},s=nt(e)();s.hasNext();){var r=s.next();r._update.push({async:t,linkf:function(e,t,i){return function(s){e(t,i,s)}}(i,function(t){for(var i=[],s=nt(e)();s.hasNext();){var n=s.next();n!=r&&i.push(n)}return i}(),r)})}O.allFulfilled(e)&&t.handleResolve(function(t){for(var i=[],s=nt(e)();s.hasNext();){var r=s.next();i.push(r._val)}return i}())},O.pipeLink=function(e,t,i){var s=!1,r=function(e){if(!s){s=!0;var r=i(e);r._update.push({async:t,linkf:lt(t,t.handleResolve)}),O.immediateLinkUpdate(r,t,(function(e){return e}))}};if(e._update.push({async:t,linkf:r}),e._resolved&&!e._pending)try{r(e._val)}catch(e){e instanceof A&&(e=e.val),t.handleError(e)}},O.allResolved=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._resolved)return!1;return!0},O.allFulfilled=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._fulfilled)return!1;return!0},O.prototype={catchError:function(e){return this._error.push(e),this},errorThen:function(e){return this._errorMap=e,this},isResolved:function(){return this._resolved},isErrored:function(){return this._errored},isErrorHandled:function(){return this._error.length>0},isErrorPending:function(){return this._errorPending},isFulfilled:function(){return this._fulfilled},isPending:function(){return this._pending},handleResolve:function(e){this._resolve(e)},_resolve:function(e){var t,i,s=this;this._pending?B.enqueue((t=lt(this,this._resolve),i=e,function(){t(i)})):(this._resolved=!0,this._pending=!0,B.queue.add((function(){s._val=e;for(var t=0,i=s._update;t0)for(var i=0,s=t._error;i0))throw new A(e);for(var n=0,o=t._update;n0&&null!=(t=B.queue.pop());)t();return B.queue.isEmpty()},B.clear=function(){B.queue=new l},B.f=function(){var e=B.queue.pop();null!=e&&e(),B.queue.isEmpty()||B.continueOnNextLoop()},B.continueOnNextLoop=function(){null!=B.nextLoop?B.nextLoop(B.f):setImmediate(B.f)};var L=s["promhx.error.PromiseError"]={__ename__:["promhx","error","PromiseError"],__constructs__:["AlreadyResolved","DownstreamNotFullfilled"]};L.AlreadyResolved=function(e){var t=["AlreadyResolved",0,e];return t.__enum__=L,t.toString=r,t},L.DownstreamNotFullfilled=function(e){var t=["DownstreamNotFullfilled",1,e];return t.__enum__=L,t.toString=r,t};var k=function(){};s["verb.Verb"]=k,k.__name__=["verb","Verb"],k.main=function(){e.log("verb 2.1.0")};var V=function(){};s["verb.core.ArrayExtensions"]=V,V.__name__=["verb","core","ArrayExtensions"],V.alloc=function(e,t){if(!(t<0))for(;e.length0;){for(var s=e.pop(),r=!0,n=0;ne)return 0;if(t>e-t&&(t=e-t),U.memo_exists(e,t))return U.get_memo(e,t);for(var i=1,s=e,r=1,n=t+1;re)return 0;t>e-t&&(t=e-t);for(var i=1,s=1,r=t+1;s=l&&o<=h||a>=l&&a<=h||l>=o&&l<=a||h>=o&&h<=a},G.prototype={fromPoint:function(e){return new G([e])},add:function(e){if(!this.initialized)return this.dim=e.length,this.min=e.slice(0),this.max=e.slice(0),this.initialized=!0,this;for(var t=0,i=this.dim;tthis.max[s]&&(this.max[s]=e[s]),e[s]e&&(e=n,t=r)}return t},getAxisLength:function(e){return e<0||e>this.dim-1?0:Math.abs(this.min[e]-this.max[e])},intersect:function(e,t){if(!this.initialized)return null;var i=this.min,s=this.max,r=e.min,n=e.max;if(!this.intersects(e,t))return null;for(var o=[],a=[],l=0,h=this.dim;l0?1:-1})),s=Math.floor(e.length/2),(r=new ue(e[s],n,i)).left=this.buildTree(e.slice(0,s),t+1,r),r.right=this.buildTree(e.slice(s+1),t+1,r),r)},nearest:function(e,t,i){var s,r=this,n=new he((function(e){return-e.item1})),o=null;s=o=function(i){for(var s,a,l,h,c=i.dimension,u=r.distanceFunction(e,i.kdPoint.point),d=[],_=0,p=r.dim;_t&&n.pop()},m=0,g=r.dim;m0&&(this.content[0]=t,this.sinkDown(0)),e},peek:function(){return this.content[0]},remove:function(e){for(var t=this.content.length,i=0;i0;){var i=Math.floor((e+1)/2)-1,s=this.content[i];if(!(this.scoreFunction(t)=0;){for(o=[],a=e[c],d=r-1;d>=0;){for(l=a[s-1]*t[s-1][d],u=s-2;u>=1;)h=u-1,l+=a[u]*t[u][d]+a[h]*t[h][d],u-=2;0==u&&(l+=a[0]*t[0][d]),o[d]=l,d--}n[c]=o,c--}return n},ge.add=function(e,t){for(var i=[],s=0,r=e.length;s=0;){for(n=a[i],s=i+1;ss?1:-1}));for(var l=[],h=0,c=r.length;h=.1*m*n||isNaN(u));)m*=.5,++x;if(m*g20)throw new A("Numerical gradient fails");if(d[m]=t[m]+g,r=e(d),d[m]=t[m]-g,n=e(d),d[m]=t[m],isNaN(r)||isNaN(n))g/=16;else{if(_[m]=(r-n)/(2*g),o=t[m]-g,a=t[m],l=t[m]+g,h=(r-s)/g,c=(s-n)/g,u=Ae.max([Math.abs(_[m]),Math.abs(s),Math.abs(r),Math.abs(n),Math.abs(o),Math.abs(a),Math.abs(l),1e-8]),!(Math.min(Ae.max([Math.abs(h-_[m]),Math.abs(c-_[m]),Math.abs(h-c)])/u,g/u)>.001))break;g/=16}}return _},Te.tensor=function(e,t){for(var i,s,r=e.length,n=t.length,o=[],a=r-1;a>=0;){i=[],s=e[a];for(var l=n-1;l>=3;)i[l]=s*t[l],i[--l]=s*t[l],i[--l]=s*t[l],i[--l]=s*t[l],--l;for(;l>=0;)i[l]=s*t[l],--l;o[a]=i,a--}return o};var ye=function(e,t,i,s,r,n){this.solution=e,this.value=t,this.gradient=i,this.invHessian=s,this.iterations=r,this.message=n};s["verb.core.MinimizationResult"]=ye,ye.__name__=["verb","core","MinimizationResult"],ye.prototype={__class__:ye};var Se=function(){};s["verb.core.ISerializable"]=Se,Se.__name__=["verb","core","ISerializable"],Se.prototype={__class__:Se};var Ce=t.core.Deserializer=function(){};s["verb.core.Deserializer"]=Ce,Ce.__name__=["verb","core","Deserializer"],Ce.deserialize=function(e){return new v(e).unserialize()};var Ee=t.core.Trig=function(){};s["verb.core.Trig"]=Ee,Ee.__name__=["verb","core","Trig"],Ee.isPointInPlane=function(e,t,i){return Math.abs(Ae.dot(Ae.sub(e,t.origin),t.normal))o?{u:r,pt:i}:{u:s+(r-s)*c/o,pt:Ae.add(a,Ae.mul(c,l))}};var Ae=t.core.Vec=function(){};s["verb.core.Vec"]=Ae,Ae.__name__=["verb","core","Vec"],Ae.angleBetween=function(e,t){return Math.acos(Ae.dot(e,t)/(Ae.norm(e)*Ae.norm(t)))},Ae.positiveAngleBetween=function(e,t,i){var s=Ae.cross(e,t),r=Ae.norm(e)*Ae.norm(t),n=Ae.dot(e,t),o=Ae.norm(s)/r,a=n/r,l=Math.atan2(o,a),h=Ae.dot(i,s);return Math.abs(h)0?l:-l},Ae.signedAngleBetween=function(e,t,i){var s=Ae.cross(e,t),r=Ae.norm(e)*Ae.norm(t),n=Ae.dot(e,t),o=Ae.norm(s)/r,a=n/r,l=Math.atan2(o,a);return Ae.dot(i,s)>0?l:2*Math.PI-l},Ae.angleBetweenNormalized2d=function(e,t){var i=e[0]*t[1]-e[1]*t[0];return Math.atan2(i,Ae.dot(e,t))},Ae.domain=function(e){return V.last(e)-V.first(e)},Ae.range=function(e){for(var t=[],i=0,s=0;st&&i>0)return[];if(t>e&&i<0)return[];for(var s=[],r=e;r<=t;)s.push(r),r+=i;return s},Ae.neg=function(e){return e.map((function(e){return-e}))},Ae.min=function(e){return a.fold(e,(function(e,t){return Math.min(e,t)}),1/0)},Ae.max=function(e){return a.fold(e,(function(e,t){return Math.max(e,t)}),-1/0)},Ae.all=function(e){return a.fold(e,(function(e,t){return t&&e}),!0)},Ae.finite=function(e){return e.map((function(e){return isFinite(e)}))},Ae.onRay=function(e,t,i){return Ae.add(e,Ae.mul(i,t))},Ae.lerp=function(e,t,i){return Ae.add(Ae.mul(e,t),Ae.mul(1-e,i))},Ae.normalized=function(e){return Ae.div(e,Ae.norm(e))},Ae.cross=function(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]},Ae.dist=function(e,t){return Ae.norm(Ae.sub(e,t))},Ae.distSquared=function(e,t){return Ae.normSquared(Ae.sub(e,t))},Ae.sum=function(e){return a.fold(e,(function(e,t){return t+e}),0)},Ae.addAll=function(e){var t=nt(e)();if(!t.hasNext())return null;var i=t.next().length;return a.fold(e,(function(e,t){return Ae.add(t,e)}),Ae.rep(i,0))},Ae.addAllMutate=function(e){for(var t=e[0],i=1,s=e.length;iz.TOLERANCE)return!1}return!0},Ae.sortedSetUnion=function(e,t){for(var i=[],s=0,r=0;s=e.length)i.push(t[r]),r++;else if(r>=t.length)i.push(e[s]),s++;else{var n=e[s]-t[r];Math.abs(n)0?(i.push(t[r]),r++):(i.push(e[s]),s++)}return i},Ae.sortedSetSub=function(e,t){for(var i=[],s=0,r=0;s=t.length?(i.push(e[s]),s++):Math.abs(e[s]-t[r])z.EPSILON&&(i=new Re(r,0),t.push(i)),i.inc()}return t},Pe.isRationalSurfaceClosed=function(e,t){var i;null==t&&(t=!0);for(var s=0,r=(i=t?e.controlPoints:ge.transpose(e.controlPoints))[0].length;sh&&(A=d?[l+(A[0]-h),A[1]]:[h-z.EPSILON,A[1]]),A[1]u&&(A=_?[A[0],c+(A[0]-u)]:[A[0],u-z.EPSILON]),Ae.norm(Ae.mul(A[0]-r[0],i[1][0]))+Ae.norm(Ae.mul(A[1]-r[1],i[0][1]))x&&(A=b?v+(A-x):x),Ae.norm(Ae.mul(A-T,p[1]))(r=null!=s?s:Pe.rationalBezierCurveArcLength(e)))return V.last(e.knots);var n,o=e.knots[0],a=0,l=V.last(e.knots),h=r,c=0,u=0;for(n=null!=i?i:2*z.TOLERANCE;h-a>n;)c=(o+l)/2,(u=Pe.rationalBezierCurveArcLength(e,c))>t?(l=c,h=u):(o=c,a=u);return(o+l)/2},Pe.rationalCurveArcLength=function(e,t,i){null==i&&(i=16),null==t&&(t=V.last(e.knots));for(var s=Fe.decomposeCurveIntoBeziers(e),r=0,n=s[0],o=0;rz.EPSILON)return!1}i=V.last(e);for(var o=e.length-t-1,a=e.length;oz.EPSILON)return!1}return Ie.isNonDecreasing(e)},Ie.isNonDecreasing=function(e){for(var t=V.first(e),i=0,s=e.length;ir)return n;for(var o,a=t,l=0,h=a,c=0,u=0;l=t[l+1];)l++;o.push(l),n.push(De.basisFunctionsGivenKnotSpanIndex(l,a,e,t)),a+=r}return new q(o,n)},De.regularlySpacedDerivativeBasisFunctions=function(e,t,i){for(var s=t.length-e-2,r=(V.last(t)-t[0])/i,n=[],o=[],a=t[0],l=De.knotSpanGivenN(s,e,a,t),h=i+1,c=0;c=t[l+1];)l++;o.push(l),n.push(De.derivativeBasisFunctionsGivenNI(l,a,e,s,t)),a+=r}return new q(o,n)},De.surfacePointGivenBasesKnotSpans=function(e,t,i,s,r,n,o,a){for(var l,h=Ae.zeros1d(a),c=s-e,u=r-t,d=0,_=t+1;d<_;){var p=d++;l=Ae.zeros1d(a);for(var f=0,m=e+1;f=M&&(m[v][0]=m[g][0]/n[T+1][b],x=m[v][0]*n[b][T]);for(var O=b>=-1?1:-b,D=1+(P-1<=T?M-1:i-P);Os[e+1]-z.EPSILON)return e;if(i=s[o+1];)iz.EPSILON})),(function(e,t){var i=Ae.sub(e.min.uv0,t.min.uv0),s=Ae.dot(i,i),r=Ae.sub(e.max.uv0,t.max.uv0),n=Ae.dot(r,r),o=Ae.sub(e.min.uv0,t.max.uv0),a=Ae.dot(o,o),l=Ae.sub(e.max.uv0,t.min.uv0),h=Ae.dot(l,l);return s0&&(f.push(f[f.length-1].opp),u.push(f))}if(0==c.length&&r.length>0&&(_||d0;){var o=s.pop(),a=r.pop();if(!o.empty()&&!a.empty()&&o.boundingBox().intersects(a.boundingBox(),i)){var l=o.indivisible(i),h=a.indivisible(i);if(l&&h)n.push(new q(o.yield(),a.yield()));else if(!l||h)if(l||!h){var c=o.split(),u=a.split();s.push(c.item1),r.push(u.item1),s.push(c.item1),r.push(u.item0),s.push(c.item0),r.push(u.item1),s.push(c.item0),r.push(u.item0)}else{var d=o.split();s.push(d.item1),r.push(a),s.push(d.item0),r.push(a)}else{var _=a.split();s.push(o),r.push(_.item1),s.push(o),r.push(_.item0)}}}return n},we.curves=function(e,t,i){var s=we.boundingBoxTrees(new _e(e),new _e(t),0);return V.unique(s.map((function(s){return we.curvesWithEstimate(e,t,V.first(s.item0.knots),V.first(s.item1.knots),i)})).filter((function(e){return Ae.distSquared(e.point0,e.point1)h[_]+z.EPSILON||((null==c||vu.u)&&(u=new ne(v,Ae.onRay(e.origin,e.dir,v),Ae.onRay(n[_],o[_],g/h[_]))))}}return null==u||null==c?null:new Z(c,u)},we.mergeTriangleClipIntervals=function(e,t,i,s,r,n){if(t.min.u>e.max.u+z.EPSILON||e.min.u>t.max.u+z.EPSILON)return null;var o,a;o=e.min.u>t.min.u?new q(e.min,0):new q(t.min,1),a=e.max.uc&&(h=1,c=u),d>c&&(h=2,c=d),0==h?(n=t[1],o=t[2],a=s[1],l=s[2]):1==h?(n=t[0],o=t[2],a=s[0],l=s[2]):(n=t[0],o=t[1],a=s[0],l=s[1]);var _=-Ae.dot(e,t),p=-Ae.dot(i,s),f=n*l-o*a,m=(o*p-_*l)/f,g=(_*a-n*p)/f;return new X(0==h?[0,m,g]:1==h?[m,0,g]:[m,g,0],Ae.normalized(r))},we.threePlanes=function(e,t,i,s,r,n){var o=Ae.cross(i,r),a=Ae.dot(e,o);if(Math.abs(a)1)return null;var f=Ae.add(e,Ae.mul(p,c)),m=Ae.dot(a,l),g=Ae.dot(a,a),v=Ae.dot(l,l),x=Ae.sub(f,r),b=Ae.dot(x,a),T=Ae.dot(x,l),y=m*m-g*v;if(Math.abs(y)1+z.EPSILON||C>1+z.EPSILON||C<-z.EPSILON||S<-z.EPSILON||S+C>1+z.EPSILON?null:new re(f,S,C,p)},we.segmentAndPlane=function(e,t,i,s){var r=Ae.dot(s,Ae.sub(t,e));if(Math.abs(r)1+z.EPSILON||n<-z.EPSILON?null:{p:n}};var Ne=t.eval.Make=function(){};s["verb.eval.Make"]=Ne,Ne.__name__=["verb","eval","Make"],Ne.rationalTranslationalSurface=function(e,t){for(var i=De.rationalCurvePoint(t,V.first(t.knots)),s=V.first(t.knots),r=V.last(t.knots),n=2*t.controlPoints.length,o=(r-s)/(n-1),a=[],l=0;l=0&&(u-=n[o].mult),c=u>0?Fe.surfaceKnotRefine(e,Ae.rep(u,t),i):e;var d=De.knotSpan(r,t,s);return Math.abs(t-V.first(s))e.length-1&&(t=e.length-1);for(var s=e[0].knots,r=[],n=[],o=0,a=e[0].controlPoints.length;oz.EPSILON&&(E=Ae.mul(1/A,E),P=Ae.mul(1/A,P)),m[0][S]=o[S];var R=o[S];g[0][S]=a[S];for(var I=P,M=0,O=1,D=r+1;Ot?e:t},Fe.curveElevateDegree=function(e,t){if(t<=e.degree)return e;var i=e.knots.length-e.degree-2,s=e.degree,r=e.knots,n=e.controlPoints,o=t-e.degree,a=e.controlPoints[0].length,l=Ae.zeros2d(s+o+1,s+1),h=[],c=[],u=[],d=i+s+1,_=t,p=Math.floor(_/2),f=[],m=[];l[0][0]=1,l[_][s]=1;for(var g=1,v=p+1;g0?Math.floor((K+2)/2):1,X=D>0?Math.floor(_-(D+1)/2):_,D>0){for(var $=j-B,q=[],Z=s;Z>Q;)q[Z-Q-1]=$/(r[w+Z]-B),Z--;for(var J=1,ee=D+1;J=se;)h[re]=Ae.add(Ae.mul(q[re-se],h[re]),Ae.mul(1-q[re-se],h[re-1])),re--;u[ie]=h[s]}}for(var ne=H,oe=_+1;ne1)for(var de=O-2,_e=O,pe=j-B,fe=(j-m[O-1])/pe,me=1;mege;){if(ve=H){if(xe-ge<=O-_+K){var ye=(j-m[xe-ge])/pe;c[be]=Ae.lerp(ye,c[be],c[be+1])}}else c[be]=Ae.lerp(fe,c[be],c[be+1]);ve+=1,xe-=1,be-=1}de-=1,_e+=1}if(w!=s)for(var Se=0,Ce=_-K;Se=0;){for(;t[A]<=r[C]&&C>l;)c[E-i-1]=s[C-i-1],u[E]=r[C],E-=1,C-=1;c[E-i-1]=c[E-i];for(var P=1,R=i+1;Ps||!Ee.threePointsAreFlat(n,l,o,s)){var u=t+.5*(i-t),d=Be.rationalCurveAdaptiveSampleRange(e,t,u,s,r),_=Be.rationalCurveAdaptiveSampleRange(e,u,i,s,r);return d.slice(0,-1).concat(_)}return r?[[t].concat(n),[i].concat(o)]:[n,o]},Be.rationalSurfaceNaive=function(e,t,i){t<1&&(t=1),i<1&&(i=1),e.degreeU,e.degreeV,e.controlPoints;for(var s=e.knotsU,r=e.knotsV,n=(V.last(s)-s[0])/t,o=(V.last(r)-r[0])/i,a=[],l=[],h=[],c=0,u=t+1;cr?t.minDivsU=t.minDivsU:t.minDivsU=r,s=t.minDivsV>n?t.minDivsV=t.minDivsV:t.minDivsV=n;for(var o=V.last(e.knotsU),a=e.knotsU[0],l=V.last(e.knotsV),h=e.knotsV[0],c=(o-a)/i,u=(l-h)/s,d=[],_=[],p=0,f=s+1;pn.corners[0].uv[0]+r&&e.uv[0]n.corners[0].uv[1]+r&&e.uv[1]=e.maxDepth)return!1;if(this.hasBadNormals())return this.fixNormals(),!1;if(this.splitVert=Ae.normSquared(Ae.sub(this.corners[0].normal,this.corners[1].normal))>e.normTol||Ae.normSquared(Ae.sub(this.corners[2].normal,this.corners[3].normal))>e.normTol,this.splitHoriz=Ae.normSquared(Ae.sub(this.corners[1].normal,this.corners[2].normal))>e.normTol||Ae.normSquared(Ae.sub(this.corners[3].normal,this.corners[0].normal))>e.normTol,this.splitVert||this.splitHoriz)return!0;var i=this.center();return Ae.normSquared(Ae.sub(i.normal,this.corners[0].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[1].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[2].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[3].normal))>e.normTol},divide:function(e){null==e&&(e=new Le),null==e.normTol&&(e.normTol=.085),null==e.minDepth&&(e.minDepth=0),null==e.maxDepth&&(e.maxDepth=10),this._divide(e,0,!0)},_divide:function(e,t,i){if(this.evalCorners(),this.shouldDivide(e,t)){if(t++,this.splitVert&&!this.splitHoriz?i=!1:!this.splitVert&&this.splitHoriz&&(i=!0),this.horizontal=i,this.horizontal){var s=[this.corners[0],this.corners[1],this.midpoint(1),this.midpoint(3)],r=[this.midpoint(3),this.midpoint(1),this.corners[2],this.corners[3]];this.children=[new ke(this.srf,s),new ke(this.srf,r)],this.children[0].neighbors=[this.neighbors[0],this.neighbors[1],this.children[1],this.neighbors[3]],this.children[1].neighbors=[this.children[0],this.neighbors[1],this.neighbors[2],this.neighbors[3]]}else{var n=[this.corners[0],this.midpoint(0),this.midpoint(2),this.corners[3]],o=[this.midpoint(0),this.corners[1],this.corners[2],this.midpoint(2)];this.children=[new ke(this.srf,n),new ke(this.srf,o)],this.children[0].neighbors=[this.neighbors[0],this.children[1],this.neighbors[2],this.neighbors[3]],this.children[1].neighbors=[this.neighbors[0],this.neighbors[1],this.neighbors[2],this.children[0]]}for(var a=0,l=this.children;a0&&this._pool.length>0;){var i=this._queue.shift(),s=[i.id],r=[this._pool.shift()];this._working.h[s[0]]=r[0],r[0].onmessage=function(i,s){return function(r){t._working.remove(s[0]),t._pool.push(i[0]);try{t._callbacks.h.hasOwnProperty(s[0])&&(t._callbacks.h[s[0]](r.data.result),t._callbacks.remove(s[0]))}catch(t){t instanceof A&&(t=t.val),e.log(t)}t.processQueue()}}(r,s),r[0].postMessage(i)}},__class__:Ue};var Ge=function(e,t,i){this.className=e,this.methodName=t,this.args=i,this.id=Ge.uuid++};s["verb.exe._WorkerPool.Work"]=Ge,Ge.__name__=["verb","exe","_WorkerPool","Work"],Ge.prototype={__class__:Ge};var ze=function(){};s["verb.geom.ICurve"]=ze,ze.__name__=["verb","geom","ICurve"],ze.__interfaces__=[Se],ze.prototype={__class__:ze};var We=t.geom.NurbsCurve=function(e){this._data=Ie.isValidNurbsCurveData(e)};s["verb.geom.NurbsCurve"]=We,We.__name__=["verb","geom","NurbsCurve"],We.__interfaces__=[ze],We.byKnotsControlPointsWeights=function(e,t,i,s){return new We(new Y(e,t.slice(),De.homogenize1d(i,s)))},We.byPoints=function(e,t){return null==t&&(t=3),new We(Ne.rationalInterpCurve(e,t))},We.__super__=W,We.prototype=n(W.prototype,{degree:function(){return this._data.degree},knots:function(){return this._data.knots.slice(0)},controlPoints:function(){return De.dehomogenize1d(this._data.controlPoints)},weights:function(){return De.weight1d(this._data.controlPoints)},asNurbs:function(){return new Y(this.degree(),this.knots(),De.homogenize1d(this.controlPoints(),this.weights()))},clone:function(){return new We(this._data)},domain:function(){return new Z(V.first(this._data.knots),V.last(this._data.knots))},transform:function(e){return new We(Fe.rationalCurveTransform(this._data,e))},transformAsync:function(e){return Ve.dispatchMethod(Fe,"rationalCurveTransform",[this._data,e]).then((function(e){return new We(e)}))},point:function(e){return De.rationalCurvePoint(this._data,e)},pointAsync:function(e){return Ve.dispatchMethod(De,"rationalCurvePoint",[this._data,e])},tangent:function(e){return De.rationalCurveTangent(this._data,e)},tangentAsync:function(e){return Ve.dispatchMethod(De,"rationalCurveTangent",[this._data,e])},derivatives:function(e,t){return null==t&&(t=1),De.rationalCurveDerivatives(this._data,e,t)},derivativesAsync:function(e,t){return null==t&&(t=1),Ve.dispatchMethod(De,"rationalCurveDerivatives",[this._data,e,t])},closestPoint:function(e){return Pe.rationalCurveClosestPoint(this._data,e)},closestPointAsync:function(e){return Ve.dispatchMethod(Pe,"rationalCurveClosestPoint",[this._data,e])},closestParam:function(e){return Pe.rationalCurveClosestParam(this._data,e)},closestParamAsync:function(e){return Ve.dispatchMethod(Pe,"rationalCurveClosestParam",[this._data,e])},length:function(){return Pe.rationalCurveArcLength(this._data)},lengthAsync:function(){return Ve.dispatchMethod(Pe,"rationalCurveArcLength",[this._data])},lengthAtParam:function(e){return Pe.rationalCurveArcLength(this._data,e)},lengthAtParamAsync:function(){return Ve.dispatchMethod(Pe,"rationalCurveArcLength",[this._data])},paramAtLength:function(e,t){return Pe.rationalCurveParamAtArcLength(this._data,e,t)},paramAtLengthAsync:function(e,t){return Ve.dispatchMethod(Pe,"rationalCurveParamAtArcLength",[this._data,e,t])},divideByEqualArcLength:function(e){return Me.rationalCurveByEqualArcLength(this._data,e)},divideByEqualArcLengthAsync:function(e){return Ve.dispatchMethod(Me,"rationalCurveByEqualArcLength",[this._data,e])},divideByArcLength:function(e){return Me.rationalCurveByArcLength(this._data,e)},divideByArcLengthAsync:function(e){return Ve.dispatchMethod(Me,"rationalCurveByArcLength",[this._data,e])},split:function(e){return Me.curveSplit(this._data,e).map((function(e){return new We(e)}))},splitAsync:function(e){return Ve.dispatchMethod(Me,"curveSplit",[this._data,e]).then((function(e){return e.map((function(e){return new We(e)}))}))},reverse:function(){return new We(Fe.curveReverse(this._data))},reverseAsync:function(){return Ve.dispatchMethod(Fe,"curveReverse",[this._data]).then((function(e){return new We(e)}))},tessellate:function(e){return Be.rationalCurveAdaptiveSample(this._data,e,!1)},tessellateAsync:function(e){return Ve.dispatchMethod(Be,"rationalCurveAdaptiveSample",[this._data,e,!1])},__class__:We});var He=t.geom.Arc=function(e,t,i,s,r,n){We.call(this,Ne.arc(e,t,i,s,r,n)),this._center=e,this._xaxis=t,this._yaxis=i,this._radius=s,this._minAngle=r,this._maxAngle=n};s["verb.geom.Arc"]=He,He.__name__=["verb","geom","Arc"],He.__super__=We,He.prototype=n(We.prototype,{center:function(){return this._center},xaxis:function(){return this._xaxis},yaxis:function(){return this._yaxis},radius:function(){return this._radius},minAngle:function(){return this._minAngle},maxAngle:function(){return this._maxAngle},__class__:He});var Xe=t.geom.BezierCurve=function(e,t){We.call(this,Ne.rationalBezierCurve(e,t))};s["verb.geom.BezierCurve"]=Xe,Xe.__name__=["verb","geom","BezierCurve"],Xe.__super__=We,Xe.prototype=n(We.prototype,{__class__:Xe});var Ye=t.geom.Circle=function(e,t,i,s){He.call(this,e,t,i,s,0,2*Math.PI)};s["verb.geom.Circle"]=Ye,Ye.__name__=["verb","geom","Circle"],Ye.__super__=He,Ye.prototype=n(He.prototype,{__class__:Ye});var Qe=function(){};s["verb.geom.ISurface"]=Qe,Qe.__name__=["verb","geom","ISurface"],Qe.__interfaces__=[Se],Qe.prototype={__class__:Qe};var je=t.geom.NurbsSurface=function(e){this._data=Ie.isValidNurbsSurfaceData(e)};s["verb.geom.NurbsSurface"]=je,je.__name__=["verb","geom","NurbsSurface"],je.__interfaces__=[Qe],je.byKnotsControlPointsWeights=function(e,t,i,s,r,n){return new je(new Q(e,t,i,s,De.homogenize2d(r,n)))},je.byCorners=function(e,t,i,s){return new je(Ne.fourPointSurface(e,t,i,s))},je.byLoftingCurves=function(e,t){return new je(Ne.loftedSurface(function(t){for(var i=[],s=0;s{},439:()=>{},699:()=>{}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};return(()=>{"use strict";i.r(s),i.d(s,{cleanJSCADCache:()=>vX,cleanOCCTCache:()=>gX,executeScript:()=>fX,fontsEnum:()=>eX,resetRunnerContext:()=>mX,run:()=>_X});var e={};i.r(e),i.d(e,{AbstractActionManager:()=>z,AbstractAssetTask:()=>OP,AbstractMesh:()=>Sn,AbstractScene:()=>G,AcquireNativeObjectAsync:()=>K_,Action:()=>Pe,ActionEvent:()=>Re,ActionManager:()=>Ye,AddBlock:()=>cb,AddressMode:()=>up,AdvancedTimer:()=>Ig,AlignBlock:()=>IS,AlphaState:()=>Ci,AmmoJSPlugin:()=>bv,AnaglyphArcRotateCamera:()=>kh,AnaglyphFreeCamera:()=>Vh,AnaglyphGamepadCamera:()=>Uh,AnaglyphPostProcess:()=>Bh,AnaglyphUniversalCamera:()=>Gh,Analyser:()=>Ao,AndOrNotEvaluator:()=>xt,Angle:()=>vr,Animatable:()=>fr,AnimatedInputBlockTypes:()=>Aa,Animation:()=>Nt,AnimationAssetTask:()=>FP,AnimationEvent:()=>Br,AnimationGroup:()=>kr,AnimationGroupMask:()=>Ur,AnimationGroupMaskMode:()=>ur,AnimationKeyInterpolation:()=>Ke,AnimationPropertiesOverride:()=>mr,AnimationRange:()=>$e,AnisotropyBlock:()=>qb,ApplyPostProcess:()=>c_,Arc2:()=>xr,ArcFollowCamera:()=>Ph,ArcRotateCamera:()=>Th,ArcRotateCameraGamepadInput:()=>Zl,ArcRotateCameraInputsManager:()=>ih,ArcRotateCameraKeyboardMoveInput:()=>Jl,ArcRotateCameraMouseWheelInput:()=>eh,ArcRotateCameraPointersInput:()=>th,ArcRotateCameraVRDeviceOrientationInput:()=>sh,ArcTan2Block:()=>wb,AssetContainer:()=>Eo,AssetTaskState:()=>MP,AssetsManager:()=>WP,AssetsProgressEvent:()=>DP,AsyncLoop:()=>us,AttachToBoxBehavior:()=>$o,AudioEngine:()=>Po,AudioSceneComponent:()=>Mo,AutoLayoutMode:()=>yp,AutoReleaseWorkerPool:()=>Jm,AutoRotationBehavior:()=>Yo,AxesViewer:()=>gu,Axis:()=>_r,AxisDragGizmo:()=>mu,AxisScaleGizmo:()=>Jf,BRDFTextureTools:()=>Cm,BabylonFileLoaderConfiguration:()=>Rv,BackEase:()=>Er,BackgroundMaterial:()=>vm,BakedVertexAnimationManager:()=>Do,BallAndSocketConstraint:()=>PE,BaseCameraMouseWheelInput:()=>Vl,BaseCameraPointersInput:()=>Ul,BaseError:()=>Xt,BaseParticleSystem:()=>rl,BaseSixDofDragBehavior:()=>na,BaseTexture:()=>No,BasisFileInfo:()=>ux,BasisTools:()=>Sx,BasisToolsOptions:()=>px,BasisTranscodeConfiguration:()=>dx,BezierCurve:()=>gr,BezierCurveEase:()=>Fr,BiPlanarBlock:()=>vT,BinaryFileAssetTask:()=>LP,BindBonesParameters:()=>Wn,BindFogParameters:()=>Nn,BindLight:()=>Xn,BindLightProperties:()=>Hn,BindLights:()=>Yn,BindLogDepth:()=>wn,BindMorphTargetParameters:()=>kn,BindSceneUniformBuffer:()=>Vn,BindTextureMatrix:()=>Gn,BlackAndWhitePostProcess:()=>tA,BlendFactor:()=>Pp,BlendOperation:()=>Rp,BloomEffect:()=>nA,BloomMergePostProcess:()=>rA,BlurPostProcess:()=>pm,Bone:()=>pr,BoneAxesViewer:()=>vu,BoneIKController:()=>Fl,BoneLookController:()=>Bl,BonesBlock:()=>Fx,BooleanGeometryBlock:()=>jS,BooleanGeometryOperations:()=>Py,BounceEase:()=>Ar,BouncingBehavior:()=>Qo,BoundingBlock:()=>QS,BoundingBox:()=>qr,BoundingBoxGizmo:()=>em,BoundingBoxRenderer:()=>QA,BoundingInfo:()=>rn,BoundingSphere:()=>Zr,BoxBlock:()=>Qy,BoxBuilder:()=>Su,BoxParticleEmitter:()=>mC,Buffer:()=>Ts,BufferBindingType:()=>mp,BufferMapState:()=>sp,BufferUsage:()=>rp,CSG:()=>ay,Camera:()=>Kr,CameraGizmo:()=>_m,CameraInputTypes:()=>Ql,CameraInputsManager:()=>jl,CannonJSPlugin:()=>vv,CanvasAlphaMode:()=>kp,CapsuleBlock:()=>sS,CapsuleBuilder:()=>Iu,CascadedShadowGenerator:()=>rv,ChromaticAberrationPostProcess:()=>oA,CircleEase:()=>Cr,CircleOfConfusionPostProcess:()=>aA,ClampBlock:()=>db,ClearCoatBlock:()=>Jb,ClipPlanesBlock:()=>ob,ClipboardEventTypes:()=>qf,ClipboardInfo:()=>Zf,CloudBlock:()=>pT,CloudPoint:()=>JC,Collider:()=>Zc,Color3:()=>Ce,Color3Gradient:()=>MC,Color4:()=>Ee,ColorCorrectionPostProcess:()=>lA,ColorCurves:()=>ms,ColorGradient:()=>IC,ColorGradingTexture:()=>Hv,ColorMergerBlock:()=>gb,ColorSplitterBlock:()=>nl,ColorWrite:()=>Ap,CombineAction:()=>Ge,CompareFunction:()=>pp,CompatibilityOptions:()=>dn,CompilationMessageType:()=>bp,CompleteGreasedLineColorTable:()=>Gy,CompleteGreasedLineWidthTable:()=>Uy,ComputeBindingType:()=>tu,ComputeEffect:()=>eu,ComputeNormalsBlock:()=>xS,ComputePassTimestampLocation:()=>wp,ComputeShader:()=>su,ComputeShaderParticleSystem:()=>RC,Condition:()=>Ie,ConditionBlock:()=>_S,ConditionBlockTests:()=>Sy,ConditionalBlock:()=>_T,ConditionalBlockConditions:()=>aT,ConeParticleEmitter:()=>gC,Constants:()=>Yd,ContainerAssetTask:()=>wP,ConversionMode:()=>pP,ConvolutionPostProcess:()=>hA,Coordinate:()=>hr,CopyTextureToTexture:()=>fP,CopyTools:()=>ko,CreateBox:()=>yu,CreateBoxVertexData:()=>bu,CreateCapsule:()=>Ru,CreateCapsuleVertexData:()=>Pu,CreateCylinder:()=>lu,CreateCylinderVertexData:()=>au,CreateDashedLines:()=>Ju,CreateDashedLinesVertexData:()=>$u,CreateDecal:()=>Pd,CreateDisc:()=>Nu,CreateDiscVertexData:()=>wu,CreateEnvTextureAsync:()=>A_,CreateGeodesic:()=>wd,CreateGoldberg:()=>Bd,CreateGoldbergVertexData:()=>Fd,CreateGreasedLine:()=>Vy,CreateGreasedLineMaterial:()=>ky,CreateGround:()=>Uc,CreateGroundFromHeightMap:()=>zc,CreateGroundFromHeightMapVertexData:()=>Vc,CreateGroundVertexData:()=>Lc,CreateHemisphere:()=>hm,CreateIcoSphere:()=>Sl,CreateIcoSphereVertexData:()=>yl,CreateImageDataArrayBufferViews:()=>R_,CreateLathe:()=>_d,CreateLineSystem:()=>qu,CreateLineSystemVertexData:()=>Ku,CreateLines:()=>Zu,CreatePlane:()=>ta,CreatePlaneVertexData:()=>ea,CreatePolygon:()=>od,CreatePolygonVertexData:()=>nd,CreatePolyhedron:()=>vd,CreatePolyhedronVertexData:()=>gd,CreateResizedCopy:()=>h_,CreateRibbon:()=>Ou,CreateRibbonVertexData:()=>Mu,CreateScreenshot:()=>dR,CreateScreenshotAsync:()=>_R,CreateScreenshotUsingRenderTarget:()=>fR,CreateScreenshotUsingRenderTargetAsync:()=>mR,CreateScreenshotWithResizeAsync:()=>pR,CreateSegmentedBoxVertexData:()=>Tu,CreateSphere:()=>Eu,CreateSphereVertexData:()=>Cu,CreateText:()=>Ud,CreateTextShapePaths:()=>Vd,CreateTiledBox:()=>Uu,CreateTiledBoxVertexData:()=>Vu,CreateTiledGround:()=>Gc,CreateTiledGroundVertexData:()=>kc,CreateTiledPlane:()=>Lu,CreateTiledPlaneVertexData:()=>Bu,CreateTorus:()=>Xc,CreateTorusKnot:()=>Wu,CreateTorusKnotVertexData:()=>zu,CreateTorusVertexData:()=>Hc,CreateTube:()=>fd,CrossBlock:()=>_b,CubeMapToSphericalPolynomialTools:()=>b_,CubeTexture:()=>mm,CubeTextureAssetTask:()=>UP,CubicEase:()=>Pr,CullMode:()=>Ep,CurrentScreenBlock:()=>Ha,Curve3:()=>yr,CurveBlock:()=>yT,CurveBlockTypes:()=>hT,CustomBlock:()=>pb,CustomOptimization:()=>eR,CustomParticleEmitter:()=>CC,CustomProceduralTexture:()=>Rx,CylinderBlock:()=>iS,CylinderBuilder:()=>hu,CylinderDirectedParticleEmitter:()=>xC,CylinderParticleEmitter:()=>vC,DDSTools:()=>jm,DataBuffer:()=>Oi,DataReader:()=>TR,DataStorage:()=>yR,Database:()=>fC,DebugBlock:()=>VS,DebugLayer:()=>xu,DebugLayerTab:()=>pu,DecalBuilder:()=>Rd,DecalMapConfiguration:()=>PT,DecalMapDefines:()=>AT,Decode:()=>$t,DecodeBase64ToBinary:()=>Jt,DecodeBase64ToString:()=>Zt,DecodeBase64UrlToBinary:()=>es,DecodeBase64UrlToString:()=>ts,DeepCopier:()=>Xe,DefaultCollisionCoordinator:()=>Jc,DefaultKTX2DecoderOptions:()=>ng,DefaultLoadingScreen:()=>av,DefaultRenderingPipeline:()=>MA,Deferred:()=>HP,DepthCullingState:()=>yi,DepthOfFieldBlurPostProcess:()=>cA,DepthOfFieldEffect:()=>_A,DepthOfFieldEffectBlurLevel:()=>dA,DepthOfFieldMergePostProcess:()=>uA,DepthPeelingRenderer:()=>$A,DepthPeelingSceneComponent:()=>qA,DepthReducer:()=>Zg,DepthRenderer:()=>$g,DepthRendererSceneComponent:()=>jA,DepthSortedParticle:()=>$C,DerivativeBlock:()=>Hx,DesaturateBlock:()=>Kb,DetailMapConfiguration:()=>xc,DeviceInputEventType:()=>Hs,DeviceLostReason:()=>Vp,DeviceOrientationCamera:()=>yh,DeviceSource:()=>$s,DeviceSourceManager:()=>Zs,DeviceType:()=>Ls,DirectionalLight:()=>lm,DirectionalLightFrustumViewer:()=>Xd,DiscBlock:()=>rS,DiscBuilder:()=>Fu,DiscardBlock:()=>zx,DisplayPassPostProcess:()=>pA,DistanceBlock:()=>Rb,DistanceConstraint:()=>RE,DistanceJoint:()=>_a,DivideBlock:()=>bb,DoNothingAction:()=>Ue,DomManagement:()=>Gt,DotBlock:()=>fb,DracoCompression:()=>ey,DrawWrapper:()=>Fi,DualSenseInput:()=>Gs,DualShockButton:()=>Xl,DualShockDpad:()=>Yl,DualShockInput:()=>Us,DualShockPad:()=>Ih,DumpTools:()=>_l,DynamicFloat32Array:()=>OR,DynamicTexture:()=>Sc,EasingFunction:()=>Sr,EdgesRenderer:()=>JA,Effect:()=>Ti,EffectFallbacks:()=>ja,EffectLayer:()=>Vg,EffectLayerSceneComponent:()=>Ug,EffectRenderer:()=>al,EffectWrapper:()=>ll,ElasticEase:()=>Rr,ElbowBlock:()=>mT,EncodeArrayBufferToBase64:()=>qt,EndsWith:()=>jt,Engine:()=>gn,EngineFactory:()=>$f,EngineFormat:()=>ig,EngineInstrumentation:()=>Lg,EngineStore:()=>se,EngineView:()=>Zd,EnvironmentHelper:()=>xm,EnvironmentTextureTools:()=>N_,Epsilon:()=>K,EquiRectangularCubeTexture:()=>Xv,EquiRectangularCubeTextureAssetTask:()=>zP,ErrorCodes:()=>Yt,ErrorFilter:()=>Up,EventConstants:()=>Xs,EventState:()=>W,ExecuteCodeAction:()=>ze,ExponentialEase:()=>Ir,ExternalTexture:()=>xf,ExtractHighlightsPostProcess:()=>sA,ExtrudePolygon:()=>ad,ExtrudeShape:()=>hd,ExtrudeShapeCustom:()=>cd,FactorGradient:()=>OC,FadeInOutBehavior:()=>qo,FeatureName:()=>ip,FileTools:()=>is,FileToolsOptions:()=>Hi,FilesInput:()=>YP,FilesInputStore:()=>Wt,FilterMode:()=>dp,FilterPostProcess:()=>fA,FlowGraph:()=>aM,FlowGraphAbsBlock:()=>_O,FlowGraphAcosBlock:()=>HO,FlowGraphAcoshBlock:()=>qO,FlowGraphAddBlock:()=>iO,FlowGraphAsinBlock:()=>WO,FlowGraphAsinhBlock:()=>$O,FlowGraphAtan2Block:()=>YO,FlowGraphAtanBlock:()=>XO,FlowGraphAtanhBlock:()=>ZO,FlowGraphBitwiseAndBlock:()=>mD,FlowGraphBitwiseLeftShiftBlock:()=>xD,FlowGraphBitwiseNotBlock:()=>fD,FlowGraphBitwiseOrBlock:()=>gD,FlowGraphBitwiseRightShiftBlock:()=>bD,FlowGraphBitwiseXorBlock:()=>vD,FlowGraphBlock:()=>ZI,FlowGraphBranchBlock:()=>gM,FlowGraphCeilBlock:()=>gO,FlowGraphClampBlock:()=>AO,FlowGraphConditionalDataBlock:()=>wM,FlowGraphConnection:()=>OI,FlowGraphConnectionType:()=>MI,FlowGraphConsoleLogBlock:()=>uM,FlowGraphConstantBlock:()=>BM,FlowGraphContext:()=>sM,FlowGraphContextLogger:()=>hM,FlowGraphCoordinateTransformBlock:()=>FM,FlowGraphCoordinator:()=>lM,FlowGraphCosBlock:()=>GO,FlowGraphCoshBlock:()=>jO,FlowGraphCountLeadingZerosBlock:()=>TD,FlowGraphCountOneBitsBlock:()=>SD,FlowGraphCountTrailingZerosBlock:()=>yD,FlowGraphCounterBlock:()=>EM,FlowGraphCrossBlock:()=>lD,FlowGraphCubeRootBlock:()=>rD,FlowGraphDataConnection:()=>QI,FlowGraphDebounceBlock:()=>PM,FlowGraphDegToRadBlock:()=>kO,FlowGraphDeterminantBlock:()=>dD,FlowGraphDivideBlock:()=>nO,FlowGraphDoNBlock:()=>vM,FlowGraphDotBlock:()=>aO,FlowGraphEBlock:()=>lO,FlowGraphEqBlock:()=>MO,FlowGraphEventBlock:()=>iM,FlowGraphExecutionBlock:()=>eM,FlowGraphExpBlock:()=>JO,FlowGraphFlipFlopBlock:()=>RM,FlowGraphFloorBlock:()=>mO,FlowGraphForLoopBlock:()=>xM,FlowGraphFractBlock:()=>vO,FlowGraphGetPropertyBlock:()=>LM,FlowGraphGetVariableBlock:()=>NM,FlowGraphGreaterThanBlock:()=>NO,FlowGraphGreaterThanOrEqualBlock:()=>FO,FlowGraphInfBlock:()=>cO,FlowGraphInterpolateBlock:()=>IO,FlowGraphInvertMatrixBlock:()=>_D,FlowGraphIsInfBlock:()=>LO,FlowGraphIsNanBlock:()=>BO,FlowGraphLengthBlock:()=>oD,FlowGraphLessThanBlock:()=>DO,FlowGraphLessThanOrEqualBlock:()=>wO,FlowGraphLog10Block:()=>iD,FlowGraphLog2Block:()=>tD,FlowGraphLogBlock:()=>eD,FlowGraphLogicAndBlock:()=>QM,FlowGraphLogicNotBlock:()=>KM,FlowGraphLogicOrBlock:()=>jM,FlowGraphMatMulBlock:()=>pD,FlowGraphMaxBlock:()=>SO,FlowGraphMeshPickEventBlock:()=>nM,FlowGraphMinBlock:()=>yO,FlowGraphMultiGateBlock:()=>yM,FlowGraphMultiplyBlock:()=>rO,FlowGraphNaNBlock:()=>uO,FlowGraphNegBlock:()=>xO,FlowGraphNormalizeBlock:()=>aD,FlowGraphPauseAnimationBlock:()=>DM,FlowGraphPiBlock:()=>hO,FlowGraphPlayAnimationBlock:()=>MM,FlowGraphPowBlock:()=>nD,FlowGraphRadToDegBlock:()=>VO,FlowGraphRandomBlock:()=>oO,FlowGraphReceiveCustomEventBlock:()=>ED,FlowGraphRemainderBlock:()=>TO,FlowGraphRotate2DBlock:()=>hD,FlowGraphRotate3DBlock:()=>cD,FlowGraphSaturateBlock:()=>RO,FlowGraphSceneReadyEventBlock:()=>CD,FlowGraphSceneTickEventBlock:()=>AD,FlowGraphSendCustomEventBlock:()=>mM,FlowGraphSequenceBlock:()=>IM,FlowGraphSetPropertyBlock:()=>fM,FlowGraphSetVariableBlock:()=>dM,FlowGraphSignBlock:()=>pO,FlowGraphSignalConnection:()=>JI,FlowGraphSinBlock:()=>UO,FlowGraphSinhBlock:()=>QO,FlowGraphSqrtBlock:()=>sD,FlowGraphState:()=>oM,FlowGraphStopAnimationBlock:()=>OM,FlowGraphSubtractBlock:()=>sO,FlowGraphSwitchBlock:()=>SM,FlowGraphTanBlock:()=>zO,FlowGraphTanhBlock:()=>KO,FlowGraphThrottleBlock:()=>bM,FlowGraphTimerBlock:()=>TM,FlowGraphTransposeBlock:()=>uD,FlowGraphTruncBlock:()=>fO,FlowGraphWaitAllBlock:()=>CM,FlowGraphWhileLoopBlock:()=>AM,FluidRenderer:()=>bP,FluidRendererSceneComponent:()=>xP,FluidRenderingDebug:()=>uP,FluidRenderingObject:()=>lP,FluidRenderingObjectCustomParticles:()=>_P,FluidRenderingObjectParticleSystem:()=>hP,FluidRenderingTargetRenderer:()=>dP,FlyCamera:()=>Ch,FlyCameraInputsManager:()=>Sh,FlyCameraKeyboardInput:()=>rh,FlyCameraMouseInput:()=>nh,FogBlock:()=>Jx,FollowBehavior:()=>la,FollowCamera:()=>Ah,FollowCameraInputsManager:()=>Eh,FollowCameraKeyboardMoveInput:()=>oh,FollowCameraMouseWheelInput:()=>ah,FollowCameraPointersInput:()=>lh,FragCoordBlock:()=>Xx,FragDepthBlock:()=>$x,FragmentOutputBlock:()=>La,FramingBehavior:()=>jo,FreeCamera:()=>xh,FreeCameraDeviceOrientationInput:()=>ph,FreeCameraGamepadInput:()=>fh,FreeCameraInputsManager:()=>_h,FreeCameraKeyboardMoveInput:()=>hh,FreeCameraMouseInput:()=>ch,FreeCameraMouseWheelInput:()=>uh,FreeCameraTouchInput:()=>dh,FreeCameraVirtualJoystickInput:()=>gh,FresnelBlock:()=>Eb,FresnelParameters:()=>kv,FromHalfFloat:()=>p_,FrontFace:()=>Cp,FrontFacingBlock:()=>Wx,Frustum:()=>sr,FxaaPostProcess:()=>mA,GIRSM:()=>CP,GIRSMManager:()=>EP,GIRSMRenderPluginMaterial:()=>PP,GPUParticleSystem:()=>XC,GUID:()=>os,Gamepad:()=>$l,GamepadCamera:()=>wh,GamepadManager:()=>Mh,GamepadSystemSceneComponent:()=>Oh,GaussianSplattingMaterial:()=>XT,GaussianSplattingMesh:()=>dC,GenerateBase64StringFromPixelData:()=>Fo,GenerateBase64StringFromTexture:()=>Bo,GenerateBase64StringFromTextureAsync:()=>Lo,GenericPad:()=>ql,GeodesicData:()=>Dd,Geometry:()=>_n,GeometryArcTan2Block:()=>KS,GeometryBufferRenderer:()=>TA,GeometryBufferRendererSceneComponent:()=>SA,GeometryClampBlock:()=>iC,GeometryCollectionBlock:()=>gS,GeometryCrossBlock:()=>sC,GeometryCurveBlock:()=>rC,GeometryCurveBlockTypes:()=>Ry,GeometryDesaturateBlock:()=>nC,GeometryDistanceBlock:()=>lC,GeometryDotBlock:()=>hC,GeometryElbowBlock:()=>vS,GeometryInfoBlock:()=>US,GeometryInputBlock:()=>Yy,GeometryLengthBlock:()=>cC,GeometryLerpBlock:()=>$S,GeometryModBlock:()=>eC,GeometryNLerpBlock:()=>qS,GeometryOptimizeBlock:()=>Ky,GeometryOutputBlock:()=>Hy,GeometryPosterizeBlock:()=>oC,GeometryPowBlock:()=>tC,GeometryReplaceColorBlock:()=>aC,GeometryRotate2dBlock:()=>uC,GeometrySmoothStepBlock:()=>JS,GeometryStepBlock:()=>ZS,GeometryTextureBlock:()=>XS,GeometryTextureFetchBlock:()=>YS,GeometryTransformBlock:()=>CS,GeometryTrigonometryBlock:()=>SS,GeometryTrigonometryBlockOperations:()=>Ey,GetClass:()=>te,GetDOMTextContent:()=>Ut,GetEnvInfo:()=>C_,GetEnvironmentBRDFTexture:()=>Sm,GetFogState:()=>$n,GetInternalFormatFromBasisFormat:()=>fx,GetTGAHeader:()=>nx,GetTextureDataAsync:()=>m_,Gizmo:()=>fu,GizmoAnchorPoint:()=>du,GizmoCoordinatesMode:()=>_u,GizmoManager:()=>om,GlowLayer:()=>Gg,GoldbergMesh:()=>Nd,GradientBlock:()=>Gb,GradientBlockColorStep:()=>Ub,GradientHelper:()=>DC,GrainPostProcess:()=>gA,GreasedLineBaseMesh:()=>Fy,GreasedLineMaterialDefaults:()=>FT,GreasedLineMesh:()=>By,GreasedLineMeshColorDistribution:()=>my,GreasedLineMeshColorDistributionType:()=>dT,GreasedLineMeshColorMode:()=>uT,GreasedLineMeshMaterialType:()=>cT,GreasedLineMeshWidthDistribution:()=>gy,GreasedLinePluginMaterial:()=>kT,GreasedLineRibbonAutoDirectionMode:()=>fy,GreasedLineRibbonFacesMode:()=>py,GreasedLineRibbonMesh:()=>Ly,GreasedLineRibbonPointsMode:()=>_y,GreasedLineSimpleMaterial:()=>VT,GreasedLineTools:()=>BT,GridBlock:()=>eS,GroundBuilder:()=>Wc,GroundMesh:()=>Bc,HDRCubeTexture:()=>uv,HDRCubeTextureAssetTask:()=>GP,HDRFiltering:()=>cv,HDRTools:()=>hv,Halton2DSequence:()=>jT,HandConstraintBehavior:()=>Nl,HandConstraintOrientation:()=>Dl,HandConstraintVisibility:()=>wl,HandConstraintZone:()=>Ol,HandPart:()=>El,HandleFallbacksForShadows:()=>Kn,HardwareScalingOptimization:()=>$P,HavokPlugin:()=>zE,HeightToNormalBlock:()=>Kx,HemisphereBuilder:()=>cm,HemisphericLight:()=>cu,HemisphericParticleEmitter:()=>bC,HighlightLayer:()=>Wg,HighlightsPostProcess:()=>vA,Hinge2Joint:()=>ma,HingeConstraint:()=>IE,HingeJoint:()=>fa,HtmlElementTexture:()=>Yv,IWebXRControllerPhysicsOptions:()=>YR,IcoSphereBlock:()=>Zy,IcoSphereBuilder:()=>Cl,ImageAssetTask:()=>kP,ImageProcessingBlock:()=>Vx,ImageProcessingConfiguration:()=>xs,ImageProcessingPostProcess:()=>xA,ImageSourceBlock:()=>tb,IncrementValueAction:()=>Le,IndexFormat:()=>Mp,InputBlock:()=>Wa,InspectableType:()=>xR,InstancedLinesMesh:()=>ju,InstancedMesh:()=>To,InstancesBlock:()=>Bx,InstantiateBlock:()=>FS,InstantiateLinearBlock:()=>BS,InstantiateOnFacesBlock:()=>DS,InstantiateOnVerticesBlock:()=>OS,InstantiateOnVolumeBlock:()=>wS,InstantiateRadialBlock:()=>LS,InstantiatedEntries:()=>Co,IntFloatConverterBlock:()=>kS,InternalTexture:()=>Pi,InternalTextureSource:()=>Ai,InterpolateValueAction:()=>Ft,IntersectionInfo:()=>$r,IsBase64DataUrl:()=>Zi,IsDocumentAvailable:()=>Vt,IsFileURL:()=>qi,IsNavigatorAvailable:()=>kt,IsWindowObjectExist:()=>Lt,JoystickAxis:()=>zl,KeepAssets:()=>So,KeyboardEventTypes:()=>Ns,KeyboardInfo:()=>Fs,KeyboardInfoPre:()=>Bs,KhronosTextureContainer:()=>qm,KhronosTextureContainer2:()=>og,LatheBuilder:()=>pd,Layer:()=>Xg,LayerSceneComponent:()=>Hg,LengthBlock:()=>Ib,LensFlare:()=>Yg,LensFlareSystem:()=>Qg,LensFlareSystemSceneComponent:()=>jg,LensFlaresOptimization:()=>JP,LensRenderingPipeline:()=>OA,LerpBlock:()=>xb,Light:()=>yo,LightBlock:()=>eb,LightGizmo:()=>dm,LightInformationBlock:()=>kx,LineEdgesRenderer:()=>eP,LinesBuilder:()=>ed,LinesMesh:()=>Qu,LoadFile:()=>Ki,LoadFileError:()=>Gi,LoadImage:()=>Qi,LoadOp:()=>Fp,LoadTextureFromTranscodeResult:()=>yx,LockConstraint:()=>OE,Logger:()=>we,MapMode:()=>np,MapRangeBlock:()=>dS,MappingBlock:()=>GS,MappingTypes:()=>Ay,Material:()=>uo,MaterialAnisotropicDefines:()=>Om,MaterialClearCoatDefines:()=>Pm,MaterialDefines:()=>Oa,MaterialDetailMapDefines:()=>vc,MaterialFlags:()=>lc,MaterialGreasedLineDefines:()=>LT,MaterialHelper:()=>Vv,MaterialIridescenceDefines:()=>Im,MaterialPluginBase:()=>gc,MaterialPluginEvent:()=>En,MaterialPluginManager:()=>cc,MaterialSheenDefines:()=>wm,MaterialSubSurfaceDefines:()=>Fm,MathBlock:()=>uS,MathBlockOperations:()=>yy,Matrix:()=>fe,MatrixBuilderBlock:()=>oT,MatrixComposeBlock:()=>zS,MatrixDeterminantBlock:()=>xT,MatrixTransposeBlock:()=>bT,MaxBlock:()=>Ab,MergeGeometryBlock:()=>mS,MergeMeshesOptimization:()=>sR,Mesh:()=>bo,MeshAssetTask:()=>NP,MeshAttributeExistsBlock:()=>TT,MeshAttributeExistsBlockTypes:()=>lT,MeshBlock:()=>qy,MeshBuilder:()=>Gd,MeshDebugMode:()=>GT,MeshDebugPluginMaterial:()=>WT,MeshExploder:()=>XP,MeshLODLevel:()=>po,MeshParticleEmitter:()=>EC,MeshUVSpaceRenderer:()=>ly,MeshoptCompression:()=>ty,MinBlock:()=>Pb,MinMaxReducer:()=>qg,MipmapFilterMode:()=>_p,MirrorTexture:()=>fm,ModBlock:()=>nT,ModelShape:()=>KC,MorphTarget:()=>dv,MorphTargetManager:()=>pv,MorphTargetsBlock:()=>Lx,MotionBlurPostProcess:()=>CA,MotorEnabledJoint:()=>pa,MultiMaterial:()=>_o,MultiObserver:()=>QP,MultiPointerScaleBehavior:()=>ra,MultiRenderTarget:()=>Ex,MultiplyBlock:()=>tl,NLerpBlock:()=>zb,NativeDataStream:()=>i_,NativeEngine:()=>J_,NativePointerInput:()=>Vs,NativeXRFrame:()=>II,NativeXRLayerRenderTargetTextureProvider:()=>Oc,NativeXRLayerWrapper:()=>Mc,NativeXRRenderTarget:()=>Dc,NegateBlock:()=>Mb,Node:()=>Ct,NodeGeometry:()=>jy,NodeGeometryBlock:()=>Wy,NodeGeometryBlockConnectionPointTypes:()=>vy,NodeGeometryBuildState:()=>Xy,NodeGeometryConnectionPoint:()=>zy,NodeGeometryConnectionPointCompatibilityStates:()=>xy,NodeGeometryConnectionPointDirection:()=>by,NodeGeometryContextualSources:()=>Ty,NodeMaterial:()=>Tl,NodeMaterialBlock:()=>wa,NodeMaterialBlockConnectionPointMode:()=>Ca,NodeMaterialBlockConnectionPointTypes:()=>xa,NodeMaterialBlockTargets:()=>ba,NodeMaterialConnectionPoint:()=>Da,NodeMaterialConnectionPointCompatibilityStates:()=>Ta,NodeMaterialConnectionPointCustomObject:()=>Nx,NodeMaterialConnectionPointDirection:()=>ya,NodeMaterialDefines:()=>bl,NodeMaterialModes:()=>il,NodeMaterialOptimizer:()=>ST,NodeMaterialSystemValues:()=>Ea,NodeMaterialTeleportInBlock:()=>lb,NodeMaterialTeleportOutBlock:()=>hb,NoiseBlock:()=>fS,NoiseProceduralTexture:()=>Ix,NormalBlendBlock:()=>Xb,NormalizeBlock:()=>mb,NormalizeVectorBlock:()=>TS,NullBlock:()=>nS,NullEngine:()=>jd,NullEngineOptions:()=>Qd,Observable:()=>X,Observer:()=>H,OcclusionMaterial:()=>Uv,Octree:()=>nu,OctreeBlock:()=>ru,OctreeSceneComponent:()=>ou,OimoJSPlugin:()=>xv,OnAfterEnteringVRObservableEvent:()=>Kc,OneMinusBlock:()=>Sb,Orientation:()=>cr,OutlineRenderer:()=>aP,PBRAnisotropicConfiguration:()=>Dm,PBRBaseMaterial:()=>Vm,PBRBaseSimpleMaterial:()=>Gv,PBRClearCoatConfiguration:()=>Rm,PBRIridescenceConfiguration:()=>Mm,PBRMaterial:()=>Um,PBRMaterialDefines:()=>km,PBRMetallicRoughnessBlock:()=>rT,PBRMetallicRoughnessMaterial:()=>zv,PBRSheenConfiguration:()=>Nm,PBRSpecularGlossinessMaterial:()=>Wv,PBRSubSurfaceConfiguration:()=>Bm,PHI:()=>j,PadNumber:()=>ei,PanoramaToCubeMapTools:()=>lv,Particle:()=>wC,ParticleBlendMultiplyBlock:()=>Qa,ParticleHelper:()=>QC,ParticleRampGradientBlock:()=>Ya,ParticleSystem:()=>HC,ParticleSystemSet:()=>YC,ParticleTextureBlock:()=>Xa,ParticlesOptimization:()=>tR,PassCubePostProcess:()=>Fh,PassPostProcess:()=>Nh,Path2:()=>br,Path3D:()=>Tr,PathCursor:()=>Vr,PerfCollectionStrategy:()=>kR,PerfCounter:()=>tr,PerformanceConfigurator:()=>ie,PerformanceMonitor:()=>pn,PerformanceViewerCollector:()=>BR,PerturbNormalBlock:()=>Gx,PhotoDome:()=>Tm,Physics6DoFConstraint:()=>AE,Physics6DoFLimit:()=>EE,PhysicsActivationControl:()=>hE,PhysicsAggregate:()=>NE,PhysicsBody:()=>fE,PhysicsConstraint:()=>CE,PhysicsConstraintAxis:()=>sE,PhysicsConstraintAxisLimitMode:()=>iE,PhysicsConstraintMotorType:()=>oE,PhysicsConstraintType:()=>rE,PhysicsEngine:()=>gv,PhysicsEngineV2:()=>pE,PhysicsEventType:()=>aE,PhysicsHelper:()=>XE,PhysicsImpostor:()=>ga,PhysicsJoint:()=>da,PhysicsMaterialCombineMode:()=>cE,PhysicsMotionType:()=>lE,PhysicsRadialExplosionEventOptions:()=>$E,PhysicsRadialImpulseFalloff:()=>uE,PhysicsRaycastResult:()=>mv,PhysicsShape:()=>mE,PhysicsShapeBox:()=>bE,PhysicsShapeCapsule:()=>vE,PhysicsShapeContainer:()=>SE,PhysicsShapeConvexHull:()=>TE,PhysicsShapeCylinder:()=>xE,PhysicsShapeMesh:()=>yE,PhysicsShapeSphere:()=>gE,PhysicsShapeType:()=>nE,PhysicsUpdraftEventOptions:()=>qE,PhysicsUpdraftMode:()=>dE,PhysicsViewer:()=>zd,PhysicsVortexEventOptions:()=>ZE,PickingInfo:()=>Ss,PipelineErrorReason:()=>Tp,PivotTools:()=>Jo,Plane:()=>ir,PlaneBlock:()=>$y,PlaneBuilder:()=>ia,PlaneDragGizmo:()=>sm,PlaneRotationGizmo:()=>tm,PlayAnimationAction:()=>ke,PlaySoundAction:()=>Qe,PointColor:()=>tE,PointLight:()=>ov,PointParticleEmitter:()=>TC,PointerDragBehavior:()=>sa,PointerEventTypes:()=>Ms,PointerInfo:()=>ws,PointerInfoBase:()=>Os,PointerInfoPre:()=>Ds,PointerInput:()=>ks,PointsCloudSystem:()=>_E,PointsGroup:()=>eE,Polar:()=>YT,Polygon:()=>sd,PolygonBuilder:()=>ld,PolygonMeshBuilder:()=>rd,PolyhedronBuilder:()=>xd,PolyhedronData:()=>Od,PositionGizmo:()=>rm,PositionNormalTextureVertex:()=>Va,PositionNormalVertex:()=>ka,PostProcess:()=>qa,PostProcessManager:()=>Cs,PostProcessRenderEffect:()=>iA,PostProcessRenderPipeline:()=>PA,PostProcessRenderPipelineManager:()=>RA,PostProcessRenderPipelineManagerSceneComponent:()=>IA,PostProcessesOptimization:()=>ZP,PosterizeBlock:()=>Lb,PowBlock:()=>Ob,PowerEase:()=>Mr,PowerPreference:()=>tp,PrePassOutputBlock:()=>Zx,PrePassRenderer:()=>iP,PrePassRendererSceneComponent:()=>sP,PrePassTextureBlock:()=>ab,PrecisionDate:()=>zt,PredicateCondition:()=>Oe,PrepareAttributesForBakedVertexAnimation:()=>zn,PrepareAttributesForBones:()=>Qn,PrepareAttributesForInstances:()=>jn,PrepareAttributesForMorphTargets:()=>Bn,PrepareAttributesForMorphTargetsInfluencers:()=>Fn,PrepareDefinesForAttributes:()=>ro,PrepareDefinesForBakedVertexAnimation:()=>so,PrepareDefinesForBones:()=>to,PrepareDefinesForCamera:()=>lo,PrepareDefinesForFrameBoundValues:()=>eo,PrepareDefinesForLight:()=>Jn,PrepareDefinesForLights:()=>Zn,PrepareDefinesForMergedUV:()=>Un,PrepareDefinesForMisc:()=>qn,PrepareDefinesForMorphTargets:()=>io,PrepareDefinesForMultiview:()=>no,PrepareDefinesForOIT:()=>oo,PrepareDefinesForPrePass:()=>ao,PrepareUniformsAndSamplersForLight:()=>ho,PrepareUniformsAndSamplersList:()=>co,PressureObserverWrapper:()=>MR,PrimitiveTopology:()=>Sp,PrismaticConstraint:()=>DE,ProceduralTexture:()=>ml,ProceduralTextureSceneComponent:()=>fl,PropertyTypeForEdition:()=>Sa,ProximityCastResult:()=>JE,PushAttributesForInstances:()=>Ln,PushMaterial:()=>Ra,QuadraticEase:()=>Or,QuadraticErrorSimplification:()=>wy,QuarticEase:()=>Dr,Quaternion:()=>pe,QueryType:()=>Lp,QuinticEase:()=>wr,RGBDTextureTools:()=>v_,RSMCreatePluginMaterial:()=>SP,Ragdoll:()=>BE,RagdollBoneProperties:()=>FE,RandomBlock:()=>pS,RandomBlockLocks:()=>Cy,RandomGUID:()=>ns,RandomNumberBlock:()=>Db,RawCubeTexture:()=>Mx,RawTexture:()=>Wo,RawTexture2DArray:()=>_v,RawTexture3D:()=>Ox,Ray:()=>Zo,RayHelper:()=>Wd,ReadFile:()=>ji,ReadFileError:()=>Wi,RecastJSCrowd:()=>pC,RecastJSPlugin:()=>_C,ReciprocalBlock:()=>Fb,ReflectBlock:()=>Qb,ReflectionBlock:()=>Zb,ReflectionProbe:()=>Tv,ReflectionTextureBaseBlock:()=>sb,ReflectionTextureBlock:()=>rb,ReflectiveShadowMap:()=>TP,Reflector:()=>IR,RefractBlock:()=>jb,RefractionBlock:()=>tT,RefractionPostProcess:()=>EA,RefractionTexture:()=>Dx,RegisterClass:()=>ee,RegisterMaterialPlugin:()=>pc,RegisterNativeTypeAsync:()=>$_,RemapBlock:()=>Ja,RenderPassTimestampLocation:()=>Np,RenderTargetTexture:()=>pl,RenderTargetWrapper:()=>Ka,RenderTargetsOptimization:()=>iR,RenderingGroup:()=>Es,RenderingGroupInfo:()=>As,RenderingManager:()=>Ps,ReplaceColorBlock:()=>Bb,RequestFile:()=>$i,RequestFileError:()=>zi,RetryStrategy:()=>Ht,RibbonBuilder:()=>Du,RichType:()=>wI,RichTypeAny:()=>NI,RichTypeBoolean:()=>LI,RichTypeColor3:()=>zI,RichTypeColor4:()=>WI,RichTypeFlowGraphInteger:()=>XI,RichTypeMatrix:()=>GI,RichTypeNumber:()=>BI,RichTypeQuaternion:()=>HI,RichTypeString:()=>FI,RichTypeVector2:()=>kI,RichTypeVector3:()=>VI,RichTypeVector4:()=>UI,RollingAverage:()=>fn,Rotate2dBlock:()=>Yb,RotationGizmo:()=>im,RotationXBlock:()=>ES,RotationYBlock:()=>AS,RotationZBlock:()=>PS,RuntimeAnimation:()=>Bt,RuntimeError:()=>Qt,SSAO2RenderingPipeline:()=>wA,SSAORenderingPipeline:()=>NA,SSRRenderingPipeline:()=>GA,SamplerBindingType:()=>gp,Scalar:()=>xe,ScaleBlock:()=>ub,ScaleGizmo:()=>nm,ScalingBlock:()=>RS,Scene:()=>dr,SceneComponentConstants:()=>Rs,SceneDepthBlock:()=>nb,SceneInstrumentation:()=>kg,SceneLoader:()=>Pa,SceneLoaderAnimationGroupLoadingMode:()=>va,SceneLoaderFlags:()=>un,SceneOptimization:()=>jP,SceneOptimizer:()=>nR,SceneOptimizerOptions:()=>rR,ScenePerformancePriority:()=>ar,SceneRecorder:()=>SR,SceneSerializer:()=>hR,ScreenSizeBlock:()=>Yx,ScreenSpaceBlock:()=>Qx,ScreenSpaceCurvaturePostProcess:()=>YA,ScreenSpaceReflectionPostProcess:()=>BA,ScreenshotTools:()=>vR,SerializationHelper:()=>yt,SetBasisTranscoderWorker:()=>xx,SetColorsBlock:()=>hS,SetCorsBehavior:()=>Yi,SetMaterialIDBlock:()=>yS,SetNormalsBlock:()=>aS,SetParentAction:()=>We,SetPositionsBlock:()=>oS,SetStateAction:()=>Fe,SetTangentsBlock:()=>cS,SetUVsBlock:()=>lS,SetValueAction:()=>Be,ShaderCodeInliner:()=>U_,ShaderLanguage:()=>ui,ShaderMaterial:()=>Yu,ShaderStage:()=>fp,ShaderStore:()=>bi,ShadowDepthWrapper:()=>ET,ShadowGenerator:()=>Kg,ShadowGeneratorSceneComponent:()=>nv,ShadowLight:()=>am,ShadowMapBlock:()=>qx,ShadowsOptimization:()=>qP,ShapeBuilder:()=>dd,ShapeCastResult:()=>eA,SharpenPostProcess:()=>AA,SheenBlock:()=>$b,SimplexPerlin3DBlock:()=>Hb,SimplicationQueueSceneComponent:()=>Ny,SimplificationQueue:()=>uy,SimplificationSettings:()=>cy,SimplificationType:()=>dy,SineEase:()=>Nr,SixDofDragBehavior:()=>oa,Size:()=>Et,Skeleton:()=>Ho,SkeletonViewer:()=>Hd,SliderConstraint:()=>ME,SmartArray:()=>ds,SmartArrayNoDuplicate:()=>_s,SmoothStepBlock:()=>Nb,SolidParticle:()=>jC,SolidParticleSystem:()=>ZC,SolidParticleVertex:()=>qC,Sound:()=>Ro,SoundTrack:()=>Io,SourceTextureFormat:()=>eg,Space:()=>lr,SphereBlock:()=>Jy,SphereBuilder:()=>Au,SphereDirectedParticleEmitter:()=>SC,SphereParticleEmitter:()=>yC,Spherical:()=>QT,SphericalHarmonics:()=>a_,SphericalPolynomial:()=>l_,SpotLight:()=>um,SpringConstraint:()=>wE,Sprite:()=>Sv,SpriteManager:()=>Av,SpriteMap:()=>RP,SpritePackedManager:()=>IP,SpriteSceneComponent:()=>Cv,Stage:()=>Is,StandardMaterial:()=>yc,StandardMaterialDefines:()=>Tc,StandardRenderingPipeline:()=>LA,StartsWith:()=>Kt,StateCondition:()=>De,StencilOperation:()=>Ip,StencilState:()=>Si,StencilStateComposer:()=>Bi,StepBlock:()=>yb,StereoscopicArcRotateCamera:()=>Xh,StereoscopicFreeCamera:()=>Yh,StereoscopicGamepadCamera:()=>Qh,StereoscopicInterlacePostProcess:()=>Wh,StereoscopicInterlacePostProcessI:()=>zh,StereoscopicScreenUniversalCamera:()=>Kh,StereoscopicUniversalCamera:()=>jh,StickValues:()=>Kl,StopAnimationAction:()=>Ve,StopSoundAction:()=>je,StorageBuffer:()=>Ll,StorageTextureAccess:()=>xp,StoreOp:()=>Bp,StringDictionary:()=>ps,StringTools:()=>ti,SubEmitter:()=>BC,SubEmitterType:()=>FC,SubMesh:()=>ln,SubSurfaceBlock:()=>iT,SubSurfaceSceneComponent:()=>oP,SubtractBlock:()=>Tb,SurfaceMagnetismBehavior:()=>aa,SwitchBooleanAction:()=>Ne,SwitchInput:()=>Ws,TAARenderingPipeline:()=>zA,TBNBlock:()=>Ux,TGATools:()=>ax,Tags:()=>bt,TargetCamera:()=>vh,TargetedAnimation:()=>Lr,TeleportInBlock:()=>WS,TeleportOutBlock:()=>HS,TestBase64DataUrl:()=>Ji,TextFileAssetTask:()=>BP,Texture:()=>Vo,TextureAspect:()=>hp,TextureAssetTask:()=>VP,TextureBlock:()=>ib,TextureDimension:()=>op,TextureFormat:()=>cp,TextureOptimization:()=>KP,TexturePacker:()=>Px,TexturePackerFrame:()=>Ax,TextureSampleType:()=>vp,TextureSampler:()=>Ei,TextureTools:()=>g_,TextureUsage:()=>ap,TextureViewDimension:()=>lp,ThinEngine:()=>ki,ThinRenderTargetTexture:()=>wx,ThinTexture:()=>wo,TiledBoxBuilder:()=>Gu,TiledPlaneBuilder:()=>ku,TimerState:()=>Sg,TmpColors:()=>Ae,TmpVectors:()=>ge,ToGammaSpace:()=>Y,ToHalfFloat:()=>__,ToLinearSpace:()=>Q,TonemapPostProcess:()=>HA,TonemappingOperator:()=>WA,Tools:()=>hs,TorusBlock:()=>tS,TorusBuilder:()=>Yc,TorusKnotBuilder:()=>Hu,TouchCamera:()=>bh,TrailMesh:()=>hy,Trajectory:()=>CR,TrajectoryClassifier:()=>RR,TranscodeAsync:()=>bx,TranscodeTarget:()=>tg,TransformBlock:()=>Na,TransformNode:()=>xn,TranslationBlock:()=>MS,TriPlanarBlock:()=>gT,TrigonometryBlock:()=>vl,TrigonometryBlockOperations:()=>gl,TubeBuilder:()=>md,TwirlBlock:()=>jx,UniformBuffer:()=>bs,UniversalCamera:()=>Dh,UnregisterAllMaterialPlugins:()=>mc,UnregisterMaterialPlugin:()=>fc,UploadContent:()=>ox,UploadEnvLevelsAsync:()=>I_,UploadEnvSpherical:()=>D_,UploadLevelsAsync:()=>O_,UtilityLayerRenderer:()=>uu,VRCameraMetrics:()=>qh,VRDeviceOrientationArcRotateCamera:()=>rc,VRDeviceOrientationFreeCamera:()=>nc,VRDeviceOrientationGamepadCamera:()=>oc,VRDistortionCorrectionPostProcess:()=>Zh,VRExperienceHelper:()=>$c,VRMultiviewToSingleviewPostProcess:()=>ic,ValidatedNativeDataStream:()=>ep,ValueCondition:()=>Me,Vector2:()=>ue,Vector2ToFixed:()=>KT,Vector3:()=>de,Vector3ToFixed:()=>$T,Vector4:()=>_e,Vector4ToFixed:()=>qT,VectorConverterBlock:()=>bS,VectorMergerBlock:()=>Za,VectorSplitterBlock:()=>vb,VertexAnimationBaker:()=>Xo,VertexBuffer:()=>ys,VertexData:()=>cn,VertexDataMaterialInfo:()=>hn,VertexFormat:()=>Op,VertexOutputBlock:()=>Fa,VertexStepMode:()=>Dp,VideoDome:()=>Bg,VideoRecorder:()=>cR,VideoTexture:()=>Fg,ViewDirectionBlock:()=>Cb,Viewport:()=>jr,VirtualJoystick:()=>mh,VirtualJoysticksCamera:()=>$h,VolumetricLightScatteringPostProcess:()=>XA,VoronoiNoiseBlock:()=>fT,WaveBlock:()=>Vb,WaveBlockKind:()=>kb,WebGL2ParticleSystem:()=>PC,WebGL2ShaderProcessor:()=>Mi,WebGLDataBuffer:()=>Di,WebGLHardwareTexture:()=>Ni,WebGLPipelineContext:()=>wi,WebGPUCacheBindGroups:()=>Sf,WebGPUCacheRenderPipeline:()=>pf,WebGPUCacheRenderPipelineTree:()=>mf,WebGPUCacheSampler:()=>hf,WebGPUDataBuffer:()=>rf,WebGPUDrawContext:()=>Tf,WebGPUEngine:()=>Wf,WebGPURenderTargetWrapper:()=>Kf,WebGPUTintWASM:()=>Lf,WebRequest:()=>At,WebXRAbstractFeature:()=>ua,WebXRAbstractMotionController:()=>ug,WebXRAnchorSystem:()=>zR,WebXRBackgroundRemover:()=>XR,WebXRCamera:()=>lg,WebXRControllerComponent:()=>cg,WebXRControllerMovement:()=>tI,WebXRControllerPhysics:()=>QR,WebXRControllerPointerSelection:()=>bg,WebXRDefaultExperience:()=>Dg,WebXRDefaultExperienceOptions:()=>Og,WebXRDepthSensing:()=>mI,WebXRDomOverlay:()=>eI,WebXREnterExitUI:()=>Pg,WebXREnterExitUIButton:()=>Eg,WebXREnterExitUIOptions:()=>Ag,WebXRExperienceHelper:()=>hg,WebXREyeTracking:()=>sI,WebXRFeatureName:()=>ha,WebXRFeaturePointSystem:()=>KR,WebXRFeaturesManager:()=>ca,WebXRGenericHandController:()=>TI,WebXRGenericTriggerMotionController:()=>dg,WebXRHTCViveMotionController:()=>PI,WebXRHand:()=>Il,WebXRHandJoint:()=>Al,WebXRHandTracking:()=>Ml,WebXRHitTest:()=>jR,WebXRHitTestLegacy:()=>UR,WebXRImageTracking:()=>JR,WebXRInput:()=>xg,WebXRInputSource:()=>vg,WebXRLayerRenderTargetTextureProvider:()=>Ec,WebXRLayers:()=>fI,WebXRLightEstimation:()=>iI,WebXRManagedOutputCanvas:()=>Ic,WebXRManagedOutputCanvasOptions:()=>Rc,WebXRMeshDetector:()=>qR,WebXRMicrosoftMixedRealityController:()=>SI,WebXRMotionControllerManager:()=>mg,WebXRMotionControllerTeleportation:()=>Mg,WebXRNearControllerMode:()=>yg,WebXRNearInteraction:()=>Cg,WebXROculusTouchMotionController:()=>EI,WebXRPlaneDetector:()=>HR,WebXRProfiledMotionController:()=>pg,WebXRRawCameraAccess:()=>bI,WebXRSessionManager:()=>wc,WebXRSpaceWarp:()=>xI,WebXRSpaceWarpRenderTargetTextureProvider:()=>vI,WebXRState:()=>Nc,WebXRTrackingState:()=>Fc,WebXRWalkingLocomotion:()=>lI,WeightedSound:()=>Oo,WorkerPool:()=>Zm,WorleyNoise3DBlock:()=>Wb,XRSpaceWarpRenderTarget:()=>gI,Xbox360Button:()=>Wl,Xbox360Dpad:()=>Hl,Xbox360Pad:()=>Rh,XboxInput:()=>zs,_BabylonLoaderRegistered:()=>Pv,_BasisTextureLoader:()=>Cx,_CreationDataStorage:()=>fo,_DDSTextureLoader:()=>Km,_ENVTextureLoader:()=>$m,_HDRTextureLoader:()=>hx,_InstancesBatch:()=>go,_KTXTextureLoader:()=>ag,_MeshCollisionData:()=>bn,_OcclusionDataStorage:()=>$d,_PrimaryIsoTriangle:()=>Md,_TGATextureLoader:()=>lx,_TimeToken:()=>Kd,_UpdateRGBDAsync:()=>w_,_forceSceneHelpersToBundle:()=>wg,_forceTransformFeedbackToBundle:()=>qd,_injectLTSFileTools:()=>ss,_staticOffsetValueColor3:()=>Ot,_staticOffsetValueColor4:()=>Dt,_staticOffsetValueQuaternion:()=>Pt,_staticOffsetValueSize:()=>Mt,_staticOffsetValueVector2:()=>It,_staticOffsetValueVector3:()=>Rt,addClipPlaneUniforms:()=>An,allocateAndCopyTypedBuffer:()=>mn,bindClipPlane:()=>In,captureEquirectangularFromScene:()=>VR,className:()=>cs,createDetailMapPlugin:()=>NT,createPBRAnisotropicPlugin:()=>RT,createPBRBRDFPlugin:()=>IT,createPBRClearCoatPlugin:()=>MT,createPBRIridescencePlugin:()=>OT,createPBRSheenPlugin:()=>DT,createPBRSubSurfacePlugin:()=>wT,createYieldingScheduler:()=>zr,editableInPropertyPage:()=>Ba,expandToProperty:()=>it,extractMinAndMax:()=>an,extractMinAndMaxIndexed:()=>on,getRichTypeFromValue:()=>YI,inlineScheduler:()=>Gr,makeAsyncFunction:()=>Qr,makeSyncFunction:()=>Yr,nativeOverride:()=>mt,normalizeEnvInfo:()=>E_,prepareDefinesForClipPlanes:()=>Rn,prepareStringDefinesForClipPlanes:()=>Pn,runCoroutine:()=>Wr,runCoroutineAsync:()=>Xr,runCoroutineSync:()=>Hr,serialize:()=>st,serializeAsCameraReference:()=>ft,serializeAsColor3:()=>nt,serializeAsColor4:()=>ut,serializeAsColorCurves:()=>ct,serializeAsFresnelParameters:()=>ot,serializeAsImageProcessingConfiguration:()=>dt,serializeAsMatrix:()=>pt,serializeAsMeshReference:()=>ht,serializeAsQuaternion:()=>_t,serializeAsTexture:()=>rt,serializeAsVector2:()=>at,serializeAsVector3:()=>lt,setAndStartTimer:()=>Rg,setStereoscopicAnaglyphRigMode:()=>Lh,setStereoscopicRigMode:()=>Hh,setVRRigMode:()=>sc});var t={};i.r(t),i.d(t,{AbstractButton3D:()=>Ow,AdvancedDynamicTexture:()=>Cw,AdvancedDynamicTextureInstrumentation:()=>Ew,BaseGradient:()=>bw,BaseSlider:()=>sw,Button:()=>zD,Button3D:()=>Dw,Checkbox:()=>HD,CheckboxGroup:()=>ow,ColorPicker:()=>jD,Container:()=>LD,Container3D:()=>ww,Control:()=>BD,Control3D:()=>Iw,CornerHandle:()=>Jw,CylinderPanel:()=>Fw,DisplayGrid:()=>gw,Ellipse:()=>KD,FluentBackplateMaterial:()=>Gw,FluentButtonMaterial:()=>Xw,FluentMaterial:()=>Lw,FluentMaterialDefines:()=>Bw,FocusableButton:()=>$D,GUI3DManager:()=>SN,GizmoHandle:()=>qw,Grid:()=>QD,HandMenu:()=>Vw,HandleMaterial:()=>Kw,HandleState:()=>$w,HolographicBackplate:()=>zw,HolographicButton:()=>Ww,HolographicSlate:()=>tN,Image:()=>GD,ImageBasedSlider:()=>vw,ImageScrollBar:()=>dw,InputPassword:()=>ZD,InputText:()=>YD,InputTextArea:()=>qD,KeyPropertySet:()=>fw,Line:()=>JD,LinearGradient:()=>Tw,MRDLBackplateMaterial:()=>uN,MRDLSliderBarMaterial:()=>aN,MRDLSliderThumbMaterial:()=>hN,MathTools:()=>FD,Matrix2D:()=>ND,Measure:()=>DD,MeshButton3D:()=>iN,MultiLine:()=>tw,MultiLinePoint:()=>ew,NearMenu:()=>sN,PlanePanel:()=>rN,RadialGradient:()=>yw,RadioButton:()=>iw,RadioGroup:()=>aw,Rectangle:()=>kD,ScatterPanel:()=>nN,ScrollBar:()=>uw,ScrollViewer:()=>_w,SelectionPanel:()=>hw,SelectorGroup:()=>nw,SideHandle:()=>Zw,SlateGizmo:()=>eN,Slider:()=>rw,Slider3D:()=>dN,SliderGroup:()=>lw,SpherePanel:()=>_N,StackPanel:()=>WD,StackPanel3D:()=>pN,Style:()=>Sw,TextBlock:()=>UD,TextWrapper:()=>XD,TextWrapping:()=>VD,ToggleButton:()=>pw,TouchButton3D:()=>Yw,TouchHolographicButton:()=>Qw,TouchHolographicButtonV3:()=>yN,TouchHolographicMenu:()=>kw,TouchMeshButton3D:()=>fN,ValueAndUnit:()=>PD,Vector2WithInfo:()=>wD,Vector3WithInfo:()=>Rw,VirtualKeyboard:()=>mw,VolumeBasedPanel:()=>Nw,XmlLoader:()=>Pw,name:()=>xw});var r={};i.r(r),i.d(r,{LodDto:()=>YG,lodEnum:()=>kG});var n={};i.r(n),i.d(n,{Part:()=>QG});var o={};i.r(o),i.d(o,{SerenitySwirlData:()=>KG,SerenitySwirlDto:()=>jG});var a={};i.r(a),i.d(a,{ArabicArchwayData:()=>ZG,ArabicArchwayDrawingPart:()=>JG,ArabicArchwayDrawingPartShapes:()=>ez,ArabicArchwayDto:()=>qG,ArabicArchwayDtoBase:()=>$G});var l={};i.r(l),i.d(l,{ArabicArchway:()=>a,SerenitySwirl:()=>o});var h={};i.r(h),i.d(h,{EternalLoveData:()=>sz,EternalLoveDto:()=>iz,EternalLoveDtoBase:()=>tz});var c={};i.r(c),i.d(c,{EternalLove:()=>h});var u={};i.r(u),i.d(u,{CalmCupData:()=>oz,CalmCupDto:()=>nz,CalmCupDtoBase:()=>rz});var d={};i.r(d),i.d(d,{DragonCupData:()=>hz,DragonCupDto:()=>lz,DragonCupDtoBase:()=>az,DragonCupModelDto:()=>cz});var _={};i.r(_),i.d(_,{CalmCup:()=>u,DragonCup:()=>d});var p={};i.r(p),i.d(p,{PhoneNestData:()=>_z,PhoneNestDrawDto:()=>vz,PhoneNestDrawingPart:()=>pz,PhoneNestDrawingPartShapes:()=>fz,PhoneNestDto:()=>dz,PhoneNestDtoBase:()=>uz,PhoneNestMainPart:()=>mz,PhoneNestModelDto:()=>gz});var f={};i.r(f),i.d(f,{PhoneNest:()=>p});var m={};i.r(m),i.d(m,{SpicyBoxData:()=>Tz,SpicyBoxDto:()=>bz,SpicyBoxDtoBase:()=>xz,SpicyBoxModelDto:()=>yz});var g={};i.r(g),i.d(g,{SpicyBox:()=>m});var v={};i.r(v),i.d(v,{Boxes:()=>g,Cups:()=>_,Desktop:()=>f,Medals:()=>c,Vases:()=>l});var x={};i.r(x),i.d(x,{ZenHideoutData:()=>Ez,ZenHideoutDrawingPart:()=>Az,ZenHideoutDrawingPartShapes:()=>Pz,ZenHideoutDto:()=>Cz,ZenHideoutDtoBase:()=>Sz});var b={};i.r(b),i.d(b,{ZenHideout:()=>x});var T={};i.r(T),i.d(T,{BeamPart:()=>kz,CeilingPart:()=>Qz,ColumnPart:()=>Lz,CornerEntranceDto:()=>Kz,CornerEntrancePart:()=>Hz,CornerPart:()=>Bz,CornerStairDto:()=>zz,CornerStairPart:()=>Wz,FloorPart:()=>jz,Houses:()=>b,RoofBeamsPart:()=>Uz,RoofCoverOneSidedDto:()=>Xz,RoofCoverPart:()=>Yz,RoofPanelPart:()=>Gz,RoofPart:()=>Vz,SandwitchPanelDto:()=>Dz,SandwitchPanelFlexDto:()=>wz,SandwitchPart:()=>Nz,SandwitchPartFlex:()=>Fz,WindowCornerDto:()=>Rz,WindowCornerPart:()=>Oz,WindowRectangularDto:()=>Iz,WindowRectangularPart:()=>Mz});var y={};i.r(y),i.d(y,{WingtipVillaData:()=>qz,WingtipVillaDto:()=>$z});var S={};i.r(S),i.d(S,{ChirpyChaletData:()=>Jz,ChirpyChaletDto:()=>Zz});var C={};i.r(C),i.d(C,{ChirpyChalet:()=>S,WingtipVilla:()=>y});var E={};i.r(E),i.d(E,{BirdHouses:()=>C});var A={};i.r(A),i.d(A,{SnakeChairData:()=>iW,SnakeChairDrawDto:()=>aW,SnakeChairDrawingPart:()=>sW,SnakeChairDrawingPartShapes:()=>rW,SnakeChairDto:()=>tW,SnakeChairDtoBase:()=>eW,SnakeChairMainPart:()=>nW,SnakeChairModelDto:()=>oW});var P={};i.r(P),i.d(P,{SnakeChair:()=>A});var R={};i.r(R),i.d(R,{ElegantTableData:()=>cW,ElegantTableDrawDto:()=>gW,ElegantTableDrawingPart:()=>uW,ElegantTableDrawingPartShapes:()=>dW,ElegantTableDto:()=>hW,ElegantTableDtoBase:()=>lW,ElegantTableLegByIndexDto:()=>fW,ElegantTableLegPart:()=>_W,ElegantTableModelDto:()=>mW,ElegantTableTopPart:()=>pW});var I={};i.r(I),i.d(I,{GoodCoffeeTableData:()=>bW,GoodCoffeeTableDrawDto:()=>RW,GoodCoffeeTableDrawingPart:()=>TW,GoodCoffeeTableDrawingPartShapes:()=>yW,GoodCoffeeTableDto:()=>xW,GoodCoffeeTableDtoBase:()=>vW,GoodCoffeeTableLegByIndexDto:()=>AW,GoodCoffeeTableLegPart:()=>SW,GoodCoffeeTableModelDto:()=>PW,GoodCoffeeTableShelfPart:()=>CW,GoodCoffeeTableTopPart:()=>EW});var M={};i.r(M),i.d(M,{SnakeTableData:()=>OW,SnakeTableDrawDto:()=>BW,SnakeTableDrawingPart:()=>DW,SnakeTableDrawingPartShapes:()=>wW,SnakeTableDto:()=>MW,SnakeTableDtoBase:()=>IW,SnakeTableMainPart:()=>NW,SnakeTableModelDto:()=>FW});var O={};i.r(O),i.d(O,{ElegantTable:()=>R,GoodCoffeeTable:()=>I,SnakeTable:()=>M});var D={};i.r(D),i.d(D,{Chairs:()=>P,Tables:()=>O});var w={};i.r(w),i.d(w,{Architecture:()=>T,Enums:()=>r,Furniture:()=>D,KidsCorner:()=>E,Shared:()=>n,ThreeDPrinting:()=>v});var N={};i.r(N),i.d(N,{FontDefinition:()=>zW,Text3DData:()=>UW,Text3DDto:()=>kW,Text3DFaceDefinitionDto:()=>HW,Text3DFaceDto:()=>VW,Text3DLetterByIndexDto:()=>GW,Text3DModelDto:()=>WW,Texts3DFaceDto:()=>XW,faceTextVarEnum:()=>GG,faceTypeEnum:()=>zG,fontVariantsEnum:()=>UG,fontsEnum:()=>VG,fontsModel:()=>LW,recAlignmentEnum:()=>WG});var F={};i.r(F),i.d(F,{PyramidSimpeByIndexDto:()=>KW,PyramidSimpleAffectorsDto:()=>QW,PyramidSimpleCellPart:()=>rH,PyramidSimpleData:()=>jW,PyramidSimpleDto:()=>YW,PyramidSimpleFacePart:()=>nH,PyramidSimpleModelCellDto:()=>JW,PyramidSimpleModelCellsDto:()=>qW,PyramidSimpleModelCellsIndexDto:()=>ZW,PyramidSimpleModelDto:()=>$W,PyramidSimpleModelFaceCellIndexDto:()=>tH,PyramidSimpleModelFaceCellsUIndexDto:()=>iH,PyramidSimpleModelFaceCellsVIndexDto:()=>sH,PyramidSimpleModelFaceIndexDto:()=>eH});var B={};i.r(B),i.d(B,{PyramidSimple:()=>F});var L={};i.r(L),i.d(L,{FacePatterns:()=>B});var k={};i.r(k),i.d(k,{outputShapeEnum:()=>oH});var V={};i.r(V),i.d(V,{Enums:()=>k,Patterns:()=>L,Text3D:()=>N});var U={};i.r(U),i.d(U,{Asset:()=>oV,BabylonCamera:()=>aV,BabylonIO:()=>lV,BabylonMaterial:()=>hV,BabylonMesh:()=>cV,BabylonMeshBuilder:()=>_V,BabylonNode:()=>CV,BabylonPick:()=>uV,BabylonRay:()=>dV,BabylonScene:()=>RV,BabylonTexture:()=>pV,BabylonWebXR:()=>fV,Base:()=>PV,Color:()=>mV,Draw:()=>gV,JSCAD:()=>vV,JSON:()=>xV,Line:()=>bV,Lists:()=>TV,Logic:()=>yV,Math:()=>SV,OCCT:()=>rk,Point:()=>EV,Polyline:()=>AV,Tag:()=>IV,Text:()=>MV,Time:()=>OV,Transforms:()=>DV,Vector:()=>wV,Verb:()=>NV});class G{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}G._BabylonFileParsers={},G._IndividualBabylonFileParsers={};class z{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in z.Triggers)if(Object.prototype.hasOwnProperty.call(z.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in z.Triggers)if(Object.prototype.hasOwnProperty.call(z.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in z.Triggers)if(Object.prototype.hasOwnProperty.call(z.Triggers,t)&&parseInt(t)===e)return!0;return!1}}z.Triggers={};class W{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class H{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class X{static FromPromise(e,t){const i=new X;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new W(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new H(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{this._remove(e)}),0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new X;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const Y=1/2.2,Q=2.2,j=(1+Math.sqrt(5))/2,K=.001;class ${static BuildArray(e,t){const i=[];for(let s=0;sfunction(e,t,i){const s=e[t];if("function"!=typeof s)return null;const r=function(){const s=e.length,n=r.previous.apply(e,arguments);return i(t,s),n};return s.next=r,r.previous=s,e[t]=r,()=>{const i=r.previous;if(!i)return;const s=r.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}const J={};function ee(e,t){J[e]=t}function te(e){return J[e]}class ie{static SetMatrixPrecision(e){if(ie.MatrixTrackPrecisionChange=!1,e&&!ie.MatrixUse64Bits&&ie.MatrixTrackedMatrices)for(let e=0;eparseInt(e.toString().replace(/\W/g,""));class ue{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=ce(this.x);return e=397*e^ce(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return ue.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new this.constructor(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new this.constructor(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.copyFromFloats(this.x-e,this.y-t)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new this.constructor(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=K){return e&&re(this.x,e.x,t)&&re(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new ue(0,0)}static One(){return new ue(1,1)}static Random(e=0,t=1){return new ue(ne(e,t),ne(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ne(e,t),ne(e,t))}static get ZeroReadOnly(){return ue._ZeroReadOnly}static FromArray(e,t=0){return new ue(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new e.constructor(a,l)}static ClampToRef(e,t,i,s){return s.x=ae(e.x,t.x,i.x),s.y=ae(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=ae(e.x,t.x,i.x),r=ae(e.y,t.y,i.y);return new e.constructor(s,r)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.x*a+i.x*l+t.x*h+s.x*c,d=e.y*a+i.y*l+t.y*h+s.y*c;return new e.constructor(u,d)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n.x=6*(o-r)*e.x+(3*o-4*r+1)*t.x+6*(-o+r)*i.x+(3*o-2*r)*s.x,n.y=6*(o-r)*e.y+(3*o-4*r+1)*t.y+6*(-o+r)*i.y+(3*o-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new e.constructor(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){const t=new e.constructor;return ue.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new e.constructor(i,s)}static Transform(e,t){const i=new e.constructor;return ue.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&a>0&&o+a<2*r*n}static Distance(e,t){return Math.sqrt(ue.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){const i=new e.constructor;return ue.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=ue.DistanceSquared(t,i);if(0===s)return ue.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,ue.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return ue.Distance(e,o)}}ue._ZeroReadOnly=ue.Zero(),Object.defineProperties(ue.prototype,{dimension:{value:[2]},rank:{value:1}});class de{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=ce(this._x);return e=397*e^ce(this._y),e=397*e^ce(this._z),e}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return de.FromArrayToRef(e,t,this),this}toQuaternion(){return pe.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,a=e._z,l=e._w,h=2*(o*r-a*s),c=2*(a*i-n*r),u=2*(n*s-o*i);return t._x=i+l*h+o*u-a*c,t._y=s+l*c+a*h-n*u,t._z=r+l*u+n*c-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){const i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=me.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=de.Dot(n,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const e=-(de.Dot(t,s)+r)/o,a=n.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=K){return e&&re(this._x,e._x,t)&&re(this._y,e._y,t)&&re(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new this.constructor(this._x*e,this._y*t,this._z*i)}divide(e){return new this.constructor(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!re(t,i,e))return!0;const s=Math.abs(this._z);return!re(t,s,e)||!re(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new this.constructor(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if("xyz"===(e=e.toLowerCase()))return this;const t=me.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(me.Matrix[0]),de.TransformCoordinatesToRef(this,me.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,me.Vector3[0]),me.Vector3[0].rotateByQuaternionToRef(e,me.Vector3[0]),t.addToRef(me.Vector3[0],i),i}cross(e){const t=new this.constructor;return de.CrossToRef(this,e,t)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=de.Dot(e,i);return(r-s)/(r-de.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(me.Vector3[1]),r=t.normalizeToRef(me.Vector3[2]);let n=de.Dot(s,r);n=ae(n,-1,1);const o=Math.acos(n),a=me.Vector3[3];return de.CrossToRef(s,r,a),de.Dot(a,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){me.Vector3[0].copyFrom(e);const s=me.Vector3[0];me.Vector3[1].copyFrom(t);const r=me.Vector3[1];me.Vector3[2].copyFrom(i);const n=me.Vector3[2],o=me.Vector3[3],a=me.Vector3[4];return s.normalize(),r.normalize(),n.normalize(),de.CrossToRef(n,s,o),de.CrossToRef(o,n,a),le(Math.atan2(de.Dot(r,o),de.Dot(r,a)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=ge.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=de.Zero();return de.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=ae(i,0,1);const r=me.Vector3[0],n=me.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const a=n.length();n.normalizeFromLength(a);const l=de.Dot(r,n);let h,c;if(l<1-K){const e=Math.acos(l),t=1/Math.sin(e);h=Math.sin((1-i)*e)*t,c=Math.sin(i*e)*t}else h=1-i,c=i;return r.scaleInPlace(h),n.scaleInPlace(c),s.copyFrom(r).addInPlace(n),s.scaleInPlace(oe(o,a,i)),s}static SmoothToRef(e,t,i,s,r){return de.SlerpToRef(e,t,0===s?1:i/s,r),r}static FromArray(e,t=0){return new de(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return de.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return de.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new de(0,0,0)}static One(){return new de(1,1,1)}static Up(){return new de(0,1,0)}static get UpReadOnly(){return de._UpReadOnly}static get DownReadOnly(){return de._DownReadOnly}static get RightReadOnly(){return de._RightReadOnly}static get LeftReadOnly(){return de._LeftReadOnly}static get LeftHandedForwardReadOnly(){return de._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return de._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return de._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return de._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return de._ZeroReadOnly}static get OneReadOnly(){return de._OneReadOnly}static Down(){return new de(0,-1,0)}static Forward(e=!1){return new de(0,0,e?-1:1)}static Backward(e=!1){return new de(0,0,e?1:-1)}static Right(){return new de(1,0,0)}static Left(){return new de(-1,0,0)}static Random(e=0,t=1){return new de(ne(e,t),ne(e,t),ne(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ne(e,t),ne(e,t),ne(e,t))}static TransformCoordinates(e,t){const i=de.Zero();return de.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return de.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*h,r._y=a*h,r._z=l*h,r._isDirty=!0,r}static TransformNormal(e,t){const i=de.Zero();return de.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),h=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new e.constructor(a,l,h)}static Clamp(e,t,i){const s=new e.constructor;return de.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:o,o=o0&&E<0?(P.copyFrom(n),R=t,I=i):E>0&&A<0?(P.copyFrom(a),R=i,I=s):(P.copyFrom(o).scaleInPlace(-1),R=s,I=t);const M=me.Vector3[9],O=me.Vector3[4];if(R.subtractToRef(g,T),I.subtractToRef(g,M),de.CrossToRef(T,M,O),!(de.Dot(O,l)<0))return r.copyFrom(g),Math.abs(p*f);const D=me.Vector3[5];de.CrossToRef(P,O,D),D.normalize();const w=me.Vector3[9];w.copyFrom(R).subtractInPlace(g);const N=w.length();if(Nthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}toVector3(){return new de(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new _e(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return _e.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new _e(0,0,0,0)}static One(){return new _e(1,1,1,1)}static Random(e=0,t=1){return new _e(ne(e,t),ne(e,t),ne(e,t),ne(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ne(e,t),ne(e,t),ne(e,t),ne(e,t))}static Clamp(e,t,i){const s=new e.constructor;return _e.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(ae(e.x,t.x,i.x),ae(e.y,t.y,i.y),ae(e.z,t.z,i.z),ae(e.w,t.w,i.w))}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return _e._ZeroReadOnly}static Normalize(e){const t=_e.Zero();return _e.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(_e.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return _e.CenterToRef(e,t,_e.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}static TransformCoordinates(e,t){const i=_e.Zero();return _e.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return _e.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=a,r.z=l,r.w=h,r}static TransformNormal(e,t){const i=new e.constructor;return _e.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new _e(e._x,e._y,e._z,t)}static Dot(e,t){return e.dot(t)}}_e._ZeroReadOnly=_e.Zero(),Object.defineProperties(_e.prototype,{dimension:{value:[4]},rank:{value:1}});class pe{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=ce(this._x);return e=397*e^ce(this._y),e=397*e^ce(this._z),e=397*e^ce(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return pe.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=K){return e&&re(this._x,e._x,t)&&re(this._y,e._y,t)&&re(this._z,e._z,t)&&re(this._w,e._w,t)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new this.constructor)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new this.constructor)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=de.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=r*r,a=t*t,l=i*i,h=s*s;e._z=Math.atan2(2*(i*s+t*r),-a-l+h+o),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),a-l-h+o),e._isDirty=!0}return e}toRotationMatrix(e){return fe.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return pe.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new pe;return pe.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=s+a+u;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(c-l)*_,t._y=(n-h)*_,t._z=(o-r)*_,t._isDirty=!0):s>a&&s>u?(_=2*Math.sqrt(1+s-a-u),t._w=(c-l)/_,t._x=.25*_,t._y=(r+o)/_,t._z=(n+h)/_,t._isDirty=!0):a>u?(_=2*Math.sqrt(1+a-s-u),t._w=(n-h)/_,t._x=(r+o)/_,t._y=.25*_,t._z=(l+c)/_,t._isDirty=!0):(_=2*Math.sqrt(1+u-s-a),t._w=(o-r)/_,t._x=(n+h)/_,t._y=(l+c)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=pe.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=0===s?1:i/s;return n=ae(n,0,1),pe.SlerpToRef(e,t,n,r),r}static Zero(){return new pe(0,0,0,0)}static Inverse(e){return new e.constructor(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new pe(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return pe.RotationAxisToRef(e,t,new pe)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new pe(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new pe;return pe.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return pe.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new pe;return pe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return pe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=K){const r=de.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(de.CrossToRef(e,t,ge.Vector3[0]),i.set(ge.Vector3[0].x,ge.Vector3[0].y,ge.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new pe;return pe.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=.5*i,n=.5*t,o=.5*e,a=Math.sin(r),l=Math.cos(r),h=Math.sin(n),c=Math.cos(n),u=Math.sin(o),d=Math.cos(o);return s._x=d*h*l+u*c*a,s._y=u*c*l-d*h*a,s._z=d*c*a-u*h*l,s._w=d*c*l+u*h*a,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new pe;return pe.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=.5*(i+e),n=.5*(i-e),o=.5*t;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new pe(0,0,0,0);return pe.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=me.Matrix[0];return fe.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),pe.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new pe;return pe.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=me.Matrix[0];return fe.LookDirectionLHToRef(e,t,s),pe.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new pe;return pe.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=me.Matrix[0];return fe.LookDirectionRHToRef(e,t,s),pe.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=pe.Identity();return pe.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)n=1-i,r=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,r=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e._x*a+i._x*l+t._x*h+s._x*c,d=e._y*a+i._y*l+t._y*h+s._y*c,_=e._z*a+i._z*l+t._z*h+s._z*c,p=e._w*a+i._w*l+t._w*h+s._w*c;return new e.constructor(u,d,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=6*(o-r)*e._x+(3*o-4*r+1)*t._x+6*(-o+r)*i._x+(3*o-2*r)*s._x,n._y=6*(o-r)*e._y+(3*o-4*r+1)*t._y+6*(-o+r)*i._y+(3*o-2*r)*s._y,n._z=6*(o-r)*e._z+(3*o-4*r+1)*t._z+6*(-o+r)*i._z+(3*o-2*r)*s._z,n._w=6*(o-r)*e._w+(3*o-4*r+1)*t._w+6*(-o+r)*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=pe.Zero();return pe.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new e.constructor;return pe.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(ae(e.x,t.x,i.x),ae(e.y,t.y,i.y),ae(e.z,t.z,i.z),ae(e.w,t.w,i.w))}static Random(e=0,t=1){return new pe(ne(e,t),ne(e,t),ne(e,t),ne(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ne(e,t),ne(e,t),ne(e,t),ne(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(pe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return pe.CenterToRef(e,t,pe.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(pe.prototype,{dimension:{value:[4]},rank:{value:1}});class fe{static get Use64Bits(){return ie.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=fe._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,ie.MatrixTrackPrecisionChange&&ie.MatrixTrackedMatrices.push(this),this._m=new ie.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],_=e[12],p=e[13],f=e[14],m=e[15],g=u*m-f*d,v=c*m-p*d,x=c*f-p*u,b=h*m-_*d,T=h*f-u*_,y=h*p-_*c;return t*+(o*g-a*v+l*x)+i*-(n*g-a*b+l*T)+s*+(n*v-o*b+l*y)+r*-(n*x-o*T+a*y)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return fe.FromArrayToRef(e,t,this)}copyFromFloats(...e){return fe.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return fe.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new this.constructor;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let e=0;e<16;e++)s[e]=i[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new this.constructor)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return fe.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],_=t[11],p=t[12],f=t[13],m=t[14],g=t[15],v=d*g-m*_,x=u*g-f*_,b=u*m-f*d,T=c*g-p*_,y=c*m-d*p,S=c*f-p*u,C=+(a*v-l*x+h*b),E=-(o*v-l*T+h*y),A=+(o*x-a*T+h*S),P=-(o*b-a*y+l*S),R=i*C+s*E+r*A+n*P;if(0===R)return e.copyFrom(this),e;const I=1/R,M=l*g-m*h,O=a*g-f*h,D=a*m-f*l,w=o*g-p*h,N=o*m-p*l,F=o*f-p*a,B=l*_-d*h,L=a*_-u*h,k=a*d-u*l,V=o*_-c*h,U=o*d-c*l,G=o*u-c*a,z=-(s*v-r*x+n*b),W=+(i*v-r*T+n*y),H=-(i*x-s*T+n*S),X=+(i*b-s*y+r*S),Y=+(s*M-r*O+n*D),Q=-(i*M-r*w+n*N),j=+(i*O-s*w+n*F),K=-(i*D-s*N+r*F),$=-(s*B-r*L+n*k),q=+(i*B-r*V+n*U),Z=-(i*L-s*V+n*G),J=+(i*k-s*U+r*G);return fe.FromValuesToRef(C*I,z*I,Y*I,$*I,E*I,W*I,Q*I,q*I,A*I,H*I,j*I,Z*I,P*I,X*I,K*I,J*I,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new de(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return fe.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]*r[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],o=s[1],a=s[2],l=s[3],h=s[4],c=s[5],u=s[6],d=s[7],_=s[8],p=s[9],f=s[10],m=s[11],g=s[12],v=s[13],x=s[14],b=s[15],T=r[0],y=r[1],S=r[2],C=r[3],E=r[4],A=r[5],P=r[6],R=r[7],I=r[8],M=r[9],O=r[10],D=r[11],w=r[12],N=r[13],F=r[14],B=r[15];return t[i]=n*T+o*E+a*I+l*w,t[i+1]=n*y+o*A+a*M+l*N,t[i+2]=n*S+o*P+a*O+l*F,t[i+3]=n*C+o*R+a*D+l*B,t[i+4]=h*T+c*E+u*I+d*w,t[i+5]=h*y+c*A+u*M+d*N,t[i+6]=h*S+c*P+u*O+d*F,t[i+7]=h*C+c*R+u*D+d*B,t[i+8]=_*T+p*E+f*I+m*w,t[i+9]=_*y+p*A+f*M+m*N,t[i+10]=_*S+p*P+f*O+m*F,t[i+11]=_*C+p*R+f*D+m*B,t[i+12]=g*T+v*E+x*I+b*w,t[i+13]=g*y+v*A+x*M+b*N,t[i+14]=g*S+v*P+x*O+b*F,t[i+15]=g*C+v*R+x*D+b*B,this}divide(e){return this.divideToRef(e,new this.constructor)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new this.constructor)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let e=0;e<16;e++)if(!re(i[e],s[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new this.constructor)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new this.constructor)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=ce(this._m[0]);for(let t=1;t<16;t++)e=397*e^ce(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new pe,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||me.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const t=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,n=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,s=1/e._y,r=1/e._z;fe.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*s,n[5]*s,n[6]*s,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,me.Matrix[0]),pe.FromRotationMatrixToRef(me.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new _e(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new this.constructor;return fe.TransposeToRef(this,e),e}transposeToRef(e){return fe.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new this.constructor;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=me.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return fe.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=me.Vector3[0];if(!this.decompose(t))return fe.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return fe.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new fe;return fe.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return fe._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f){const m=new fe,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated(),m}static Compose(e,t,i){const s=new fe;return fe.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,a=t._z,l=t._w,h=n+n,c=o+o,u=a+a,d=n*h,_=n*c,p=n*u,f=o*c,m=o*u,g=a*u,v=l*h,x=l*c,b=l*u,T=e._x,y=e._y,S=e._z;return r[0]=(1-(f+g))*T,r[1]=(_+b)*T,r[2]=(p-x)*T,r[3]=0,r[4]=(_-b)*y,r[5]=(1-(d+g))*y,r[6]=(m+v)*y,r[7]=0,r[8]=(p+x)*S,r[9]=(m-v)*S,r[10]=(1-(d+f))*S,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=fe.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return fe.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=fe.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new fe;return fe.RotationXToRef(e,t),t}static Invert(e){const t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return fe.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new fe;return fe.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return fe.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new fe;return fe.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return fe.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new fe;return fe.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=de.Dot(t,e),n=i._m;if(r<-1+K)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const i=de.Cross(t,e),s=1/(1+r);n[0]=i._x*i._x*s+r,n[1]=i._y*i._x*s-i._z,n[2]=i._z*i._x*s+i._y,n[3]=0,n[4]=i._x*i._y*s+i._z,n[5]=i._y*i._y*s+r,n[6]=i._z*i._y*s-i._x,n[7]=0,n[8]=i._x*i._z*s-i._y,n[9]=i._y*i._z*s+i._x,n[10]=i._z*i._z*s+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new fe;return fe.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return pe.RotationYawPitchRollToRef(e,t,i,me.Quaternion[0]),me.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new fe;return fe.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return fe.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new fe;return fe.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return fe.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new e.constructor;return fe.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-i)+o[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new e.constructor;return fe.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=me.Vector3[0],n=me.Quaternion[0],o=me.Vector3[1];e.decompose(r,n,o);const a=me.Vector3[2],l=me.Quaternion[1],h=me.Vector3[3];t.decompose(a,l,h);const c=me.Vector3[4];de.LerpToRef(r,a,i,c);const u=me.Quaternion[2];pe.SlerpToRef(n,l,i,u);const d=me.Vector3[5];return de.LerpToRef(o,h,i,d),fe.ComposeToRef(c,u,d,s),s}static LookAtLH(e,t,i){const s=new fe;return fe.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=me.Vector3[0],n=me.Vector3[1],o=me.Vector3[2];t.subtractToRef(e,o),o.normalize(),de.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),de.CrossToRef(o,r,n),n.normalize();const l=-de.Dot(r,e),h=-de.Dot(n,e),c=-de.Dot(o,e);return fe.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookAtRH(e,t,i){const s=new fe;return fe.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=me.Vector3[0],n=me.Vector3[1],o=me.Vector3[2];e.subtractToRef(t,o),o.normalize(),de.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),de.CrossToRef(o,r,n),n.normalize();const l=-de.Dot(r,e),h=-de.Dot(n,e),c=-de.Dot(o,e);return fe.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookDirectionLH(e,t){const i=new fe;return fe.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=me.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=me.Vector3[1];return de.CrossToRef(t,s,r),fe.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new fe;return fe.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=me.Vector3[2];return de.CrossToRef(t,e,s),fe.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new fe;return fe.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=2/e,a=2/t,l=2/(s-i),h=-(s+i)/(s-i);return fe.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,r),n&&r.multiplyToRef(ve,r),r._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const a=new fe;return fe.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a){const l=2/(t-e),h=2/(s-i),c=2/(n-r),u=-(n+r)/(n-r),d=(e+t)/(e-t),_=(s+i)/(i-s);return fe.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,_,u,1,o),a&&o.multiplyToRef(ve,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=-o*Math.cos(a),d=-o*Math.sin(a);return fe.TranslationToRef(0,0,-l,me.Matrix[1]),fe.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,me.Matrix[0]),me.Matrix[1].multiplyToRef(me.Matrix[0],me.Matrix[0]),fe.TranslationToRef(0,0,l,me.Matrix[1]),me.Matrix[0].multiplyToRef(me.Matrix[1],me.Matrix[0]),fe.OrthoOffCenterLHToRef(e,t,i,s,r,n,h,c),me.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,s,r,n,o){const a=new fe;return fe.OrthoOffCenterRHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,a){return fe.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=o*Math.cos(a),d=o*Math.sin(a);return fe.TranslationToRef(0,0,l,me.Matrix[1]),fe.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,me.Matrix[0]),me.Matrix[1].multiplyToRef(me.Matrix[0],me.Matrix[0]),fe.TranslationToRef(0,0,-l,me.Matrix[1]),me.Matrix[0].multiplyToRef(me.Matrix[1],me.Matrix[0]),fe.OrthoOffCenterRHToRef(e,t,i,s,r,n,h,c),me.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,s,r,n=0){const o=new fe,a=2*i/e,l=2*i/t,h=(s+i)/(s-i),c=-2*s*i/(s-i),u=Math.tan(n);return fe.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),r&&o.multiplyToRef(ve,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const a=new fe;return fe.PerspectiveFovLHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=l&&0===h?-1:0!==c?(c+h)/(c-h):1,f=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return fe.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,1,0,0,f,0,r),o&&r.multiplyToRef(ve,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return fe.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(ve,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const a=new fe;return fe.PerspectiveFovRHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,f=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return fe.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,-1,0,0,f,0,r),o&&r.multiplyToRef(ve,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return fe.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(ve,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,a=e.height,l=e.x,h=e.y,c=fe.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,n-r,0,l+o/2,a/2+h,r,1),u=new t.constructor;return t.multiplyToRef(i,u),u.multiplyToRef(s,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return ie.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return ie.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return fe.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[12],a=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],_=i[10],p=i[14],f=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=s,x[1]=r,x[2]=n,x[3]=o,x[4]=a,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=_,x[11]=p,x[12]=f,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new fe;return fe.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,a=-2*r;return fe.FromValuesToRef(n*i+1,o*i,a*i,0,n*s,o*s+1,a*s,0,n*r,o*r,a*r+1,0,n*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return fe.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}fe._UpdateFlagSeed=0,fe._IdentityReadOnly=fe.Identity(),Object.defineProperties(fe.prototype,{dimension:{value:[4,4]},rank:{value:2}});class me{}me.Vector3=$.BuildTuple(11,de.Zero),me.Matrix=$.BuildTuple(2,fe.Identity),me.Quaternion=$.BuildTuple(3,pe.Zero);class ge{}ge.Vector2=$.BuildTuple(3,ue.Zero),ge.Vector3=$.BuildTuple(13,de.Zero),ge.Vector4=$.BuildTuple(3,_e.Zero),ge.Quaternion=$.BuildTuple(2,pe.Zero),ge.Matrix=$.BuildTuple(8,fe.Identity),ee("BABYLON.Vector2",ue),ee("BABYLON.Vector3",de),ee("BABYLON.Vector4",_e),ee("BABYLON.Matrix",fe);const ve=fe.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class xe{static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=xe.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=xe.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=xe.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+xe.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=xe.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*ae(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?ae((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n;return e*(2*o-3*n+1)+i*(-2*o+3*n)+t*(o-2*n+r)+s*(o-n)}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:xe.HCF(t,i)}}function be(e){return Math.pow(e,Q)}function Te(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function ye(e){return Math.pow(e,Y)}function Se(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}xe.TwoPi=2*Math.PI,xe.WithinEpsilon=re,xe.ToHex=he,xe.Clamp=ae,xe.Lerp=oe,xe.RandomRange=ne,xe.NormalizeRadians=le;class Ce{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Ce.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ee(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new this.constructor(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new this.constructor(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=K){return xe.WithinEpsilon(this.r,e.r,t)&&xe.WithinEpsilon(this.g,e.g,t)&&xe.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new this.constructor(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=ae(this.r,e,t),i.g=ae(this.g,e,t),i.b=ae(this.b,e,t),i}add(e){return new this.constructor(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new this.constructor(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new this.constructor(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this.r-e,this.g-t,this.b-i)}clone(){return new this.constructor(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+he(e)+he(t)+he(i)}toHSV(){const e=new this.constructor;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,a=0;const l=r,h=r-n;0!==r&&(a=h/r),r!=n&&(r==t?(o=(i-s)/h,i=0&&n<=1?(a=r,l=o):n>=1&&n<=2?(a=o,l=r):n>=2&&n<=3?(l=r,h=o):n>=3&&n<=4?(l=o,h=r):n>=4&&n<=5?(a=o,h=r):n>=5&&n<=6&&(a=r,h=o);const c=i-r;s.set(a+c,l+c,h+c)}static FromHSV(e,t,i){const s=new Ce(0,0,0);return Ce.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new Ce(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return Ce.FromInts(t,i,s)}static FromArray(e,t=0){return new Ce(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Ce(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Ce(0,0,0);return Ce.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,_=e.b*a+i.b*l+t.b*h+s.b*c;return new Ce(u,d,_)}static Hermite1stDerivative(e,t,i,s,r){const n=Ce.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b}static Red(){return new Ce(1,0,0)}static Green(){return new Ce(0,1,0)}static Blue(){return new Ce(0,0,1)}static Black(){return new Ce(0,0,0)}static get BlackReadOnly(){return Ce._BlackReadOnly}static White(){return new Ce(1,1,1)}static Purple(){return new Ce(.5,0,.5)}static Magenta(){return new Ce(1,0,1)}static Yellow(){return new Ce(1,1,0)}static Gray(){return new Ce(.5,.5,.5)}static Teal(){return new Ce(0,1,1)}static Random(){return new Ce(Math.random(),Math.random(),Math.random())}}Ce._BlackReadOnly=Ce.Black(),Object.defineProperties(Ce.prototype,{dimension:{value:[3]},rank:{value:1}});class Ee{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new this.constructor(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new this.constructor(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new this.constructor(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new this.constructor(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=ae(this.r,e,t),i.g=ae(this.g,e,t),i.b=ae(this.b,e,t),i.a=ae(this.a,e,t),i}multiply(e){return new this.constructor(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new this.constructor(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=K){return xe.WithinEpsilon(this.r,e.r,t)&&xe.WithinEpsilon(this.g,e.g,t)&&xe.WithinEpsilon(this.b,e.b,t)&&xe.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new this.constructor).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+he(t)+he(i)+he(s);const r=Math.round(255*this.a);return"#"+he(t)+he(i)+he(s)+he(r)}toLinearSpace(e=!1){const t=new Ee;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Te(this.r),e.g=Te(this.g),e.b=Te(this.b)):(e.r=be(this.r),e.g=be(this.g),e.b=be(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ee;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=Se(this.r),e.g=Se(this.g),e.b=Se(this.b)):(e.r=ye(this.r),e.g=ye(this.g),e.b=ye(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new Ee(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return Ee.FromInts(t,i,s,r)}static Lerp(e,t,i){const s=new Ee(0,0,0,0);return Ee.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,_=e.b*a+i.b*l+t.b*h+s.b*c,p=e.a*a+i.a*l+t.a*h+s.a*c;return new Ee(u,d,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new Ee;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b,n.a=6*(o-r)*e.a+(3*o-4*r+1)*t.a+6*(-o+r)*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new Ee(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ee(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new Ee(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew Ee(0,0,0,0))),ee("BABYLON.Color3",Ce),ee("BABYLON.Color4",Ee);class Pe{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new X,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}Pe._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof ue?e.x+", "+e.y:e instanceof de?e.x+", "+e.y+", "+e.z:e instanceof Ce?e.r+", "+e.g+", "+e.b:e instanceof Ee?e.r+", "+e.g+", "+e.b+", "+e.a:e,Pe._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),ee("BABYLON.Action",Pe);class Re{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new Re(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Re(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Re(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Re(e,t.x,t.y,null,i,s)}}class Ie{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class Me extends Ie{static get IsEqual(){return Me._IsEqual}static get IsDifferent(){return Me._IsDifferent}static get IsGreater(){return Me._IsGreater}static get IsLesser(){return Me._IsLesser}constructor(e,t,i,s,r=Me.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case Me.IsGreater:return this._effectiveTarget[this._property]>this.value;case Me.IsLesser:return this._effectiveTarget[this._property]e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(void 0!==i&&!we._CheckLimit(s,i))return;const r=we._FormatMessage(s),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const a=`
${r}

`;we._AddLogEntry(a),we._GenerateLimitMessage(s,e)}static get LogCache(){return we._LogCache}static ClearLogCache(){we._LogCache="",we._LogLimitOutputs={},we.errorsCount=0}static set LogLevels(e){we.Log=we._LogDisabled,we.Warn=we._LogDisabled,we.Error=we._LogDisabled,[we.MessageLogLevel,we.WarningLogLevel,we.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];we[e.name]=we._LogEnabled.bind(we,t)}}))}}we.NoneLogLevel=0,we.MessageLogLevel=1,we.WarningLogLevel=2,we.ErrorLogLevel=4,we.AllLogLevel=7,we.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",we._LogCache="",we._LogLimitOutputs={},we._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],we.errorsCount=0,we.Log=we._LogEnabled.bind(we,we.MessageLogLevel),we.Warn=we._LogEnabled.bind(we,we.WarningLogLevel),we.Error=we._LogEnabled.bind(we,we.ErrorLogLevel);class Ne extends Pe{constructor(e,t,i,s){super(e,s),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Pe._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class Fe extends Pe{constructor(e,t,i,s){super(e,s),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Pe._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class Be extends Pe{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Pe._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Pe._SerializeValueAsString(this.value)}]},e)}}class Le extends Pe{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&we.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Pe._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Pe._SerializeValueAsString(this.value)}]},e)}}class ke extends Pe{constructor(e,t,i,s,r,n){super(e,n),this.from=i,this.to=s,this.loop=r,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Pe._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Pe._SerializeValueAsString(this.loop)||!1}]},e)}}class Ve extends Pe{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Pe._GetTargetProperty(this._target)]},e)}}class Ue extends Pe{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class Ge extends Pe{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;ee?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class Xe{static DeepCopy(e,t,i,s,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const o of n){if("_"===o[0]&&(!s||-1===s.indexOf(o)))continue;if(o.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(o))continue;const n=e[o],a=typeof n;if("function"!==a)try{if("object"===a)if(n instanceof Uint8Array)t[o]=Uint8Array.from(n);else if(n instanceof Array){if(t[o]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter((e=>e.actionManager===this));for(const e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=Ye.OnPickTrigger&&t.trigger<=Ye.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=Ye.OnPickTrigger&&t.trigger<=Ye.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===Ye.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(we.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,Ye.Triggers[e.trigger]?Ye.Triggers[e.trigger]++:Ye.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),Ye.Triggers[e.trigger]-=1,0===Ye.Triggers[e.trigger]&&delete Ye.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===s){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const r=s.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;const h=[];let c=null,u=null;const d=e.combine&&e.combine.length>0;if(2===e.type?h.push(s):h.push(t),d){const t=[];for(let i=0;i{const i=te("BABYLON."+e);return i&&new i(...t)})(e.name,h);if(_ instanceof Ie&&null!==o){const e=new Ue(t,o);a?a.then(e):s.registerAction(e),a=e}null===l?_ instanceof Ie?(o=_,_=a):(o=null,a?a.then(_):s.registerAction(_)):l.push(_);for(let i=0;i0){const e=r.properties[0].value,t=null===r.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),s={trigger:Ye[r.name],parameter:t}}else s=Ye[r.name];for(let e=0;e=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}Object.create,Object.create;const Ze={},Je={};function et(e){const t=e.getClassName();if(Ze[t])return Ze[t];Ze[t]={};const i=Ze[t];let s=e,r=t;for(;r;){const e=Je[r];for(const t in e)i[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==r)break;s=t}while(t);if(n)break;r=t.getClassName(),s=t}return i}function tt(e,t){return(i,s)=>{const r=function(e){const t=e.getClassName();return Je[t]||(Je[t]={}),Je[t]}(i);r[s]||(r[s]={type:e,sourceName:t})}}function it(e,t=null){return function(e,t=null){return(i,s)=>{const r=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function st(e){return tt(0,e)}function rt(e){return tt(1,e)}function nt(e){return tt(2,e)}function ot(e){return tt(3,e)}function at(e){return tt(4,e)}function lt(e){return tt(5,e)}function ht(e){return tt(6,e)}function ct(e){return tt(7,e)}function ut(e){return tt(8,e)}function dt(e){return tt(9,e)}function _t(e){return tt(10,e)}function pt(e){return tt(12,e)}function ft(e){return tt(11,e)}function mt(e,t,i,s){const r=i.value;i.value=(...i)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=s?(...t)=>s(...t)?e(...t):r(...t):e}return e[t]=n,n(...i)}}mt.filter=function(e){return(t,i,s)=>mt(t,i,s,e)};const gt={};function vt(e,t=!1){if(!t||!gt[e])return gt[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class xt{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),xt._HandleParenthesisContent(e,t)))):xt._HandleParenthesisContent(e,t))||"false"!==e&&xt.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=xt._SimplifyNegation(s[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class bt{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>bt.HasTags(e),e.addTags=t=>bt.AddTagsTo(e,t),e.removeTags=t=>bt.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>bt.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){bt._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(bt.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!bt.HasTags(e))return;const i=t.split(" ");for(const t in i)bt._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?bt.HasTags(e):xt.Eval(t,(t=>bt.HasTags(e)&&e._tags[t])))}}const Tt=function(e,t,i,s={}){const r=e();bt&&bt.HasTags(t)&&bt.AddTagsTo(r,bt.GetTags(t,!0));const n=et(r),o={};for(const e in n){const a=n[e],l=t[e],h=a.type;if(null!=l&&("uniqueId"!==e||yt.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?r[e]=o[l.uniqueId]:(r[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?l:l.clone()}}return r};class yt{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw vt("ImageProcessingConfiguration")},yt._FresnelParametersParser=e=>{throw vt("FresnelParameters")},yt._ColorCurvesParser=e=>{throw vt("ColorCurves")},yt._TextureParser=(e,t,i)=>{throw vt("Texture")};class St{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new X,this._onClonedObservable=new X}}class Ct{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null){this._isDirty=!1,this._nodeDataStorage=new St,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new X,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=fe.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new X,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||se.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew Ct(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw vt("AnimationRange")},Ct._NodeConstructors={},qe([st()],Ct.prototype,"name",void 0),qe([st()],Ct.prototype,"id",void 0),qe([st()],Ct.prototype,"uniqueId",void 0),qe([st()],Ct.prototype,"state",void 0),qe([st()],Ct.prototype,"metadata",void 0);class Et{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new Et(this.width*e,this.height*t)}clone(){return new Et(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new Et(0,0)}add(e){return new Et(this.width+e.width,this.height+e.height)}subtract(e){return new Et(this.width-e.width,this.height-e.height)}scale(e){return new Et(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new Et(s,r)}}class At{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(At.CustomRequestHeaders).length>0||At.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in At.CustomRequestHeaders){const t=At.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return At.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){At.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of At.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}At.CustomRequestHeaders={},At.CustomRequestModifiers=new Array,At.SkipRequestModificationForBabylonCDN=!0;const Pt=Object.freeze(new pe(0,0,0,0)),Rt=Object.freeze(de.Zero()),It=Object.freeze(ue.Zero()),Mt=Object.freeze(Et.Zero()),Ot=Object.freeze(Ce.Black()),Dt=Object.freeze(new Ee(0,0,0,0)),wt={key:0,repeatCount:0,loopMode:2};class Nt{static _PrepareAnimation(e,t,i,s,r,n,o,a){let l;if(!isNaN(parseFloat(r))&&isFinite(r)?l=Nt.ANIMATIONTYPE_FLOAT:r instanceof pe?l=Nt.ANIMATIONTYPE_QUATERNION:r instanceof de?l=Nt.ANIMATIONTYPE_VECTOR3:r instanceof ue?l=Nt.ANIMATIONTYPE_VECTOR2:r instanceof Ce?l=Nt.ANIMATIONTYPE_COLOR3:r instanceof Ee?l=Nt.ANIMATIONTYPE_COLOR4:r instanceof Et&&(l=Nt.ANIMATIONTYPE_SIZE),null==l)return null;const h=new Nt(e,t,i,l,o),c=[{frame:0,value:r},{frame:s,value:n}];return h.setKeys(c),void 0!==a&&h.setEasingFunction(a),h}static CreateAnimation(e,t,i,s){const r=new Nt(e+"Animation",e,i,t,Nt.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Nt._PrepareAnimation(e,i,s,r,n,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Nt._PrepareAnimation(e,s,r,n,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,n,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,a,l,h){const c=Nt._PrepareAnimation(e,i,s,r,n,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let o=e;if(n.cloneOriginalAnimation&&(o=e.clone(),o.name=n.clonedAnimationName||o.name),!o._keys.length)return o;const a=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let l=0;const h=o._keys[0];let c=o._keys.length-1;const u=o._keys[c],d={referenceValue:h.value,referencePosition:ge.Vector3[0],referenceQuaternion:ge.Quaternion[0],referenceScaling:ge.Vector3[1],keyPosition:ge.Vector3[2],keyQuaternion:ge.Quaternion[1],keyScaling:ge.Vector3[3]};let _=h.frame,p=u.frame;if(n.range){const e=o.getRange(n.range);e&&(_=e.from,p=e.to)}else _=n.fromFrame??_,p=n.toFrame??p;if(_!==h.frame&&(l=o.createKeyForFrame(_)),p!==u.frame&&(c=o.createKeyForFrame(p)),1===o._keys.length){const e=o._getKeyValue(o._keys[0]);d.referenceValue=e.clone?e.clone():e}else if(a<=h.frame){const e=o._getKeyValue(h.value);d.referenceValue=e.clone?e.clone():e}else if(a>=u.frame){const e=o._getKeyValue(u.value);d.referenceValue=e.clone?e.clone():e}else{wt.key=0;const e=o._interpolate(a,wt);d.referenceValue=e.clone?e.clone():e}o.dataType===Nt.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():o.dataType===Nt.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let f=Number.MAX_VALUE;const m=n.clipKeys?[]:null;for(let e=l;e<=c;e++){let t=o._keys[e];if(m&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},f===Number.MAX_VALUE&&(f=t.frame),t.frame-=f,m.push(t)),!e||o.dataType===Nt.ANIMATIONTYPE_FLOAT||t.value!==h.value)switch(o.dataType){case Nt.ANIMATIONTYPE_MATRIX:t.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),fe.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,t.value);break;case Nt.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(t.value,t.value);break;case Nt.ANIMATIONTYPE_VECTOR2:case Nt.ANIMATIONTYPE_VECTOR3:case Nt.ANIMATIONTYPE_COLOR3:case Nt.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(d.referenceValue,t.value);break;case Nt.ANIMATIONTYPE_SIZE:t.value.width-=d.referenceValue.width,t.value.height-=d.referenceValue.height;break;default:t.value-=d.referenceValue}}return m&&o.setKeys(m,!0),o}static TransitionTo(e,t,i,s,r,n,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=s.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===r?Nt.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Nt._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],a=s[n+1];if(i&&(e===o.frame||e===a.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(a.value);if(o.interpolation===Ke.STEP)return a.frame>e?l:h;const c=void 0!==o.outTangent&&void 0!==a.inTangent,u=a.frame-o.frame;let d=(e-o.frame)/u;const _=o.easingFunction||this.getEasingFunction();switch(null!==_&&(d=_.ease(d)),this.dataType){case Nt.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,o.outTangent*u,h,a.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case Nt.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||Pt).scale(t.repeatCount))}return e}case Nt.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Rt).scale(t.repeatCount))}break}case Nt.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||It).scale(t.repeatCount))}break}case Nt.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,d).add((t.offsetValue||Mt).scale(t.repeatCount))}break;case Nt.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ot).scale(t.repeatCount))}break}case Nt.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return e;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Dt).scale(t.repeatCount))}break}case Nt.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Nt.ANIMATIONLOOPMODE_CYCLE:case Nt.ANIMATIONLOOPMODE_CONSTANT:case Nt.ANIMATIONLOOPMODE_YOYO:return Nt.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,d,t.workValue):l;case Nt.ANIMATIONLOOPMODE_RELATIVE:case Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return Nt.AllowMatrixDecomposeForInterpolation?s?(fe.DecomposeLerpToRef(e,t,i,s),s):fe.DecomposeLerp(e,t,i):s?(fe.LerpToRef(e,t,i,s),s):fe.Lerp(e,t,i)}clone(){const e=new Nt(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){wt.key=0;const t=this._interpolate(e,wt,!0);if(!t)return this._keys[wt.key].frame===e?wt.key:wt.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(wt.key+1,0,i),wt.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(o=t.values[1]),t.values.length>=3&&(a=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Nt.ANIMATIONTYPE_QUATERNION:if(r=pe.FromArray(t.values),t.values.length>=8){const e=pe.FromArray(t.values.slice(4,8));e.equals(pe.Zero())||(o=e)}if(t.values.length>=12){const e=pe.FromArray(t.values.slice(8,12));e.equals(pe.Zero())||(a=e)}t.values.length>=13&&(l=t.values[12]);break;case Nt.ANIMATIONTYPE_MATRIX:r=fe.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Nt.ANIMATIONTYPE_COLOR3:r=Ce.FromArray(t.values),t.values[3]&&(o=Ce.FromArray(t.values[3])),t.values[4]&&(a=Ce.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Nt.ANIMATIONTYPE_COLOR4:r=Ee.FromArray(t.values),t.values[4]&&(o=Ee.FromArray(t.values[4])),t.values[5]&&(a=Ee.FromArray(t.values[5])),t.values[6]&&(l=Ee.FromArray(t.values[6]));break;case Nt.ANIMATIONTYPE_VECTOR3:default:r=de.FromArray(t.values),t.values[3]&&(o=de.FromArray(t.values[3])),t.values[4]&&(a=de.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=r,null!=o&&(h.inTangent=o),null!=a&&(h.outTangent=a),null!=l&&(h.interpolation=l),s.push(h)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new At;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new At;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),r=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const s=JSON.parse(i.animation),r=this.Parse(s);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}Nt._UniqueIdGenerator=0,Nt.AllowMatricesInterpolation=!1,Nt.AllowMatrixDecomposeForInterpolation=!0,Nt.SnippetUrl="https://snippet.babylonjs.com",Nt.ANIMATIONTYPE_FLOAT=0,Nt.ANIMATIONTYPE_VECTOR3=1,Nt.ANIMATIONTYPE_QUATERNION=2,Nt.ANIMATIONTYPE_MATRIX=3,Nt.ANIMATIONTYPE_COLOR3=4,Nt.ANIMATIONTYPE_COLOR4=7,Nt.ANIMATIONTYPE_VECTOR2=5,Nt.ANIMATIONTYPE_SIZE=6,Nt.ANIMATIONLOOPMODE_RELATIVE=0,Nt.ANIMATIONLOOPMODE_CYCLE=1,Nt.ANIMATIONLOOPMODE_CONSTANT=2,Nt.ANIMATIONLOOPMODE_YOYO=4,Nt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,Nt.CreateFromSnippetAsync=Nt.ParseFromSnippetAsync,ee("BABYLON.Animation",Nt),Ct._AnimationRangeFactory=(e,t,i)=>new $e(e,t,i);class Ft extends Pe{constructor(e,t,i,s,r=1e3,n,o,a){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new X,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=o,this.onInterpolationDone=a,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if("number"==typeof this.value)i=Nt.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Ce)i=Nt.ANIMATIONTYPE_COLOR3;else if(this.value instanceof de)i=Nt.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof fe)i=Nt.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof pe))return void we.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=Nt.ANIMATIONTYPE_QUATERNION}const s=new Nt("InterpolateValueAction",this._property,1e3/this.duration*100,i,Nt.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget),e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Pe._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Pe._SerializeValueAsString(this.value)},{name:"duration",value:Pe._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Pe._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}ee("BABYLON.InterpolateValueAction",Ft);class Bt{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,s){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Nt.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=fe.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let s=e;for(let e=0;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,u,d=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,_=0;if(s&&this._animationState.loopMode===Nt.ANIMATIONLOOPMODE_YOYO){const e=(d-t)/h;d=Math.abs(Math.sin(e*Math.PI))*h+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!s&&i>=t&&(d>=h&&r>0||d<=0&&r<0))l=!1,_=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&(d<=h&&r<0||d>=0&&r>0))l=!1,_=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Nt.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Nt.ANIMATIONLOOPMODE_CYCLE;const s=o._interpolate(t,this._animationState),r=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case Nt.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-s;break;case Nt.ANIMATIONTYPE_QUATERNION:case Nt.ANIMATIONTYPE_VECTOR3:case Nt.ANIMATIONTYPE_VECTOR2:case Nt.ANIMATIONTYPE_SIZE:case Nt.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(s)}this._highLimitsCache[e]=r}_=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case Nt.ANIMATIONTYPE_FLOAT:c=0;break;case Nt.ANIMATIONTYPE_QUATERNION:c=Pt;break;case Nt.ANIMATIONTYPE_VECTOR3:c=Rt;break;case Nt.ANIMATIONTYPE_VECTOR2:c=It;break;case Nt.ANIMATIONTYPE_SIZE:c=Mt;break;case Nt.ANIMATIONTYPE_COLOR3:c=Ot;break;case Nt.ANIMATIONTYPE_COLOR4:c=Dt}if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;u=t+h*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else u=d>0&&t>i||d<0&&t0&&this.currentFrame>u||r<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=u,this._animationState.repeatCount=0===h?0:d/h|0,this._animationState.highLimitValue=_,this._animationState.offsetValue=c;const f=o._interpolate(u,this._animationState);if(this.setValue(f,n),p.length)for(let e=0;e=0&&u>=p[e].frame&&p[e].frame>=t||h<0&&u<=p[e].frame&&p[e].frame<=t){const t=p[e];t.isDone||(t.onlyOnce&&(p.splice(e,1),e--),t.isDone=!0,t.action(u))}return l||(this._stopped=!0),l}}function Lt(){return"undefined"!=typeof window}function kt(){return"undefined"!=typeof navigator}function Vt(){return"undefined"!=typeof document}function Ut(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}const Gt={IsWindowObjectExist:Lt,IsNavigatorAvailable:kt,IsDocumentAvailable:Vt,GetDOMTextContent:Ut};class zt{static get Now(){return Lt()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class Wt{}Wt.FilesToLoad={};class Ht{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>0!==s.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}class Xt extends Error{}Xt._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const Yt={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Qt extends Xt{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Xt._setPrototypeOf(this,Qt.prototype)}}const jt=(e,t)=>e.endsWith(t),Kt=(e,t)=>!!e&&e.startsWith(t),$t=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,r,n,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|s>>4,a=(15&s)<<2|r>>6,l=63&r,isNaN(s)?a=l=64:isNaN(r)&&(l=64),h+=t.charAt(n)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},Zt=e=>atob(e),Jt=e=>{const t=Zt(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;e{let i=String(e);for(;i.length{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class si{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{h=h.trim(),""!==h&&(i.push(h),h="")},n=e=>{soi._Stack[s],a=()=>-1===s?"!!INVALID EXPRESSION!!":oi._Stack[s--];let l=0,h="";for(;l1){for(r();-1!==s&&oi._OperatorPriority[o()]>=oi._OperatorPriority[c];)i.push(a());n(c),l++}else h+=t;l++}for(r();-1!==s;)"("===o()?a():i.push(a());return oi._InfixToPostfixCache.size>=oi.InfixToPostfixCacheLimitSize&&oi.ClearCache(),oi._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(oi._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r}return i}}var ui;!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(ui||(ui={}));const di=/defined\s*?\((.+?)\)/g,_i=/defined\s*?\[(.+?)\]/g,pi=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,fi=/__decl__/,mi=/light\{X\}.(\w*)/g,gi=/\{X\}/g,vi=[];class xi{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=this._ProcessShaderConversion(e,t,s);i(r,e)}))}static PreProcess(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=this._ApplyPreProcessing(e,t,s);i(r,e)}))}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new ai(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=e.indexOf(s),r>-1)break;if(-1===r)return new ai(e);const n=e.substring(0,r).trim(),o=e.substring(r+s.length).trim();return new ci(n,s,o)}static _BuildSubExpression(e){e=e.replace(di,"defined[$1]");const t=oi.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const r="&&"==e?new hi:new li;"string"==typeof t&&(t=t.replace(_i,"defined($1)")),"string"==typeof s&&(s=s.replace(_i,"defined($1)")),r.leftOperand="string"==typeof s?this._ExtractOperation(s):s,r.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(r)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(_i,"defined($1)")),"string"==typeof s?this._ExtractOperation(s):s}static _BuildExpression(e,t){const i=new ni,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===s?new ai(r):"#ifndef"===s?new ai(r,!0):this._BuildSubExpression(r),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if("#else"===r){const i=new ii;return t.children.push(i),void this._MoveCursor(e,i)}if("#elif"===r){const e=this._BuildExpression(s,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=xi._MoveCursorRegex.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new ri;t.children.push(s);const r=this._BuildExpression(i,6);s.children.push(r),this._MoveCursorWithinIf(e,s,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new ri;t.children.push(s);const r=this._BuildExpression(i,7);s.children.push(r),this._MoveCursorWithinIf(e,s,r);break}case"#if":{const s=new ri,r=this._BuildExpression(i,3);t.children.push(s),s.children.push(r),this._MoveCursorWithinIf(e,s,r);break}}continue}}const s=new ii;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){const s=new ii,r=new si;return r.lineIndex=-1,r.lines=e.split("\n"),this._MoveCursor(r,s),s.process(t,i)}static _PreparePreProcessors(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return e.processor?.shaderLanguage===ui.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let s=this._ProcessPrecision(e,t);if(!t.processor)return s;if(t.processor.shaderLanguage===ui.GLSL&&-1!==s.indexOf("#version 3")&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const r=t.defines,n=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,r,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,n,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ApplyPreProcessing(e,t,i){let s=e;const r=t.defines,n=this._PreparePreProcessors(t,i);return t.processor?.preProcessor&&(s=t.processor.preProcessor(s,r,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,n,t),t.processor?.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ProcessIncludes(e,t,i){let s;for(vi.length=0;null!==(s=pi.exec(e));)vi.push(s);let r=String(e),n=[e],o=!1;for(const e of vi){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(fi,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void xi._FileToolsLoadFile(e,(e=>{t.includesShadersStore[s]=e,this._ProcessIncludes(n.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=o.replace(gi,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(mi,((e,t)=>t+"{X}"))),i=i.replace(gi,s)}const r=[];for(const t of n){const s=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}vi.length=0,r=n.join(""),o?this._ProcessIncludes(r.toString(),t,i):i(r)}static _FileToolsLoadFile(e,t,i,s,r,n){throw vt("FileTools")}}xi._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;class bi{static GetShadersRepository(e=ui.GLSL){return e===ui.GLSL?bi.ShadersRepository:bi.ShadersRepositoryWGSL}static GetShadersStore(e=ui.GLSL){return e===ui.GLSL?bi.ShadersStore:bi.ShadersStoreWGSL}static GetIncludesShadersStore(e=ui.GLSL){return e===ui.GLSL?bi.IncludesShadersStore:bi.IncludesShadersStoreWGSL}}bi.ShadersRepository="src/Shaders/",bi.ShadersStore={},bi.IncludesShadersStore={},bi.ShadersRepositoryWGSL="src/ShadersWGSL/",bi.ShadersStoreWGSL={},bi.IncludesShadersStoreWGSL={};class Ti{static get ShadersRepository(){return bi.ShadersRepository}static set ShadersRepository(e){bi.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new X),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,o=null,a=null,l=null,h,c="",u=ui.GLSL){if(this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new X,this.onErrorObservable=new X,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c,t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??ui.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(a[0]&&a[1]){o.isFragment=!0;const[e,i]=a;xi.Process(i,o,((i,s)=>{this._fragmentSourceCodeBeforeMigration=s,this._processFinalCode&&(i=this._processFinalCode("fragment",i));const n=xi.Finalize(e,i,o);o=null,this._useFinalCode(n.vertexCode,n.fragmentCode,r,t)}),this._engine)}};this._loadShader(i,"Vertex","",(e=>{xi.Initialize(o),xi.Process(e,o,((t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,this._processFinalCode&&(t=this._processFinalCode("vertex",t)),a[0]=t,l()}),this._engine)})),this._loadShader(s,"Fragment","Pixel",(e=>{this._rawFragmentSourceCode=e,a[1]=e,l()}))}_useFinalCode(e,t,i,s=!1){if(i){const s=i.vertexElement||i.vertex||i.spectorName||i,r=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===ui.WGSL?"//":"")+"#define SHADER_NAME vertex:"+s+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===ui.WGSL?"//":"")+"#define SHADER_NAME fragment:"+r+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(s)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Ut(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));const r=bi.GetShadersStore(this._shaderLanguage);if(r[e+t+"Shader"])return void s(r[e+t+"Shader"]);if(i&&r[e+i+"Shader"])return void s(r[e+i+"Shader"]);let n;n="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:bi.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",s)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,s);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?r._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,n,null,this._transformFeedbackVaryings,this._key):r._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,n,i,this._transformFeedbackVaryings,this._key),r._executeWhenRenderingStateIsCompiled(this._pipelineContext,(()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,t,this._attributes),t)for(let e=0;e=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(we.Error("Unable to compile effect:"),we.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),we.Error("Attributes: "+i.map((function(e){return" "+e}))),we.Error("Defines:\n"+this.defines),Ti.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(we.Error("Vertex code:"),we.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(we.Error("Fragment code:"),we.Error(i))),e&&we.Error(e),t&&we.Error(t)}we.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,we.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case Ai.Temp:break;case Ai.Url:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case Ai.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case Ai.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case Ai.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case Ai.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case Ai.Cube:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case Ai.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case Ai.CubeRawRGBD:return;case Ai.CubePrefiltered:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial);case Ai.DepthStencil:case Ai.Depth:}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}Pi._Counter=0;class Ri{constructor(){this.shaderLanguage=ui.GLSL}postProcessor(e,t,i,s,r){if(!r.getCaps().drawBuffersExtension){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const Ii=/(flat\s)?\s*varying\s*.*/;class Mi{constructor(){this.shaderLanguage=ui.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Ii.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Oi{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=Oi._Counter++}}Oi._Counter=0;class Di extends Oi{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class wi{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}class Ni{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Fi{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}class Bi{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class Li{}class ki{static get NpmPackage(){return"babylonjs@7.2.1"}static get Version(){return"7.2.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return Ti.ShadersRepository}static set ShadersRepository(e){Ti.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?518:515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return ki._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,s){this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new X,this._frameId=0,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new X,this.onContextRestoredObservable=new X,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new yi,this._stencilStateComposer=new Bi,this._stencilState=new Si,this._alphaState=new Ci,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=new Array,this._renderTargetWrapperCache=new Array,this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._currentRenderTarget=null,this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._boundRenderFunction=()=>this._renderLoop(),this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._frameHandler=0,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=new Array,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new X,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=zt.Now;let r=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=s??!1,this._stencilStateComposer.stencilGlobal=this._stencilState,ie.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=t??i.antialias,i.deterministicLockstep=i.deterministicLockstep??!1,i.lockstepMaxSteps=i.lockstepMaxSteps??4,i.timeStep=i.timeStep??1/60,i.audioEngine=i.audioEngine??!0,i.stencil=i.stencil??!0,this._audioContext=i.audioEngineOptions?.audioContext??null,this._audioDestination=i.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=i.premultipliedAlpha??!0,this.useExactSrgbConversions=i.useExactSrgbConversions??!1,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,s=s||i.adaptToDeviceRatio||!1;const n=Lt()&&window.devicePixelRatio||1,o=i.limitDeviceRatio||n;if(this._hardwareScalingLevel=s?1/Math.min(o,n):1,this._lastDevicePixelRatio=n,!e)return;if(e.getContext){if(r=e,this._renderingCanvas=r,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of ki.ExceptionList){const s=t.key,r=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=s)continue}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,we.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new Mi:new Ri,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const a=`Babylon.js v${ki.Version}`;we.Log(a+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",a)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&Vt()&&"ontouchend"in document},this._checkForMobile(),Lt()&&window.addEventListener("resize",this._checkForMobile))}_clearEmptyResources(){this._dummyFramebuffer=null,this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){we.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,this._flagContextRestored()}),0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}Ti.ResetCache()}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}_rebuildTextures(){}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,Lt()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==s&&(a.type=s,l=!0),a.normalized!==r&&(a.normalized=r,l=!0),a.stride!==n&&(a.stride=n,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=s,a.normalized=r,a.stride=n,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const t=s[r];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let o=0;o=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,s,n)),n+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",a=this._compileShader(t,"vertex",s,o),l=this._compileShader(i,"fragment",s,o);return this._createShaderProgram(e,a,l,r,n)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new wi;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");return s.attachShader(n,t),s.attachShader(n,i),s.linkProgram(n),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,s=e.fragmentShader,r=e.program;if(!t.getProgramParameter(r,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){const t=this._gl.getShaderInfoLog(i);if(t)throw e.vertexCompilationError=t,new Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(s,this._gl.COMPILE_STATUS)){const t=this._gl.getShaderInfoLog(s);if(t)throw e.fragmentCompilationError=t,new Error("FRAGMENT SHADER "+t)}const n=t.getProgramInfoLog(r);if(n)throw e.programLinkError=n,new Error(n)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS))){const i=t.getProgramInfoLog(r);if(i)throw e.programValidationError=i,new Error(i)}t.deleteShader(i),t.deleteShader(s),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,s,r,n,o,a,l,h){const c=e;c.program=s?this.createRawShaderProgram(c,t,i,void 0,l):this.createShaderProgram(c,t,i,a,void 0,l),c.program.__SPECTOR_rebuildProgram=o}_isRenderingStateCompiled(e){const t=e;return!(this._isDisposed||t._isDisposed||!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)||(this._finalizePipelineContext(t),0))}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!i.isParallelCompiled)return void t();const s=i.onCompiled;i.onCompiled=s?()=>{s(),t()}:t}getUniforms(e,t){const i=new Array,s=e;for(let e=0;e1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,we.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,d=new Pi(this,s),_=e.width||e,p=e.height||e,f=e.depth||0,m=e.layers||0,g=this._getSamplingParameters(a,n),v=0!==m?u.TEXTURE_2D_ARRAY:0!==f?u.TEXTURE_3D:u.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(o,l,h),b=this._getInternalFormat(l),T=this._getWebGLTextureType(o);return this._bindTextureDirectly(v,d),0!==m?(d.is2DArray=!0,u.texImage3D(v,0,x,_,p,m,0,b,T,null)):0!==f?(d.is3D=!0,u.texImage3D(v,0,x,_,p,f,0,b,T,null)):u.texImage2D(v,0,x,_,p,0,b,T,null),u.texParameteri(v,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(v,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(v,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(v,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),d._useSRGBBuffer=h,d.baseWidth=_,d.baseHeight=p,d.width=_,d.height=p,d.depth=m,d.isReady=!0,d.samples=c,d.generateMipMaps=n,d.samplingMode=a,d.type=o,d.format=l,d.label=r,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,n=null,o=null,a,l,h=null,c=null,u=null,d=null,_,p,f){const m="data:"===(e=e||"").substr(0,5),g="blob:"===e.substr(0,5),v=m&&-1!==e.indexOf(";base64,"),x=c||new Pi(this,Ai.Url);x!==c&&(x.label=e.substring(0,60));const b=e;!this._transformTextureUrl||v||c||h||(e=this._transformTextureUrl(e)),b!==e&&(x._originalUrl=b);const T=e.lastIndexOf(".");let y=d||(T>-1?e.substring(T).toLowerCase():""),S=null;y.indexOf("?")>-1&&(y=y.split("?")[0]);for(const e of ki._TextureLoaders)if(e.canLoad(y,_)){S=e;break}s&&s.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=r,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!f,t),this._doNotHandleContextLost||(x._buffer=h);let C=null;n&&!c&&(C=x.onLoadedObservable.add(n)),c||this._internalTexturesCache.push(x);const E=(i,c)=>{s&&s.removePendingData(x),e===b?(C&&x.onLoadedObservable.remove(C),se.UseFallbackTexture&&e!==se.FallbackTexture&&this._createTextureBase(se.FallbackTexture,t,x.invertY,s,r,null,o,a,l,h,x),i=(i||"Unknown error")+(se.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:i,exception:c}),o&&o(i,c)):(we.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,x.invertY,s,r,n,o,a,l,h,x,u,d,_,p,f))};if(S){const t=e=>{S.loadData(e,x,((e,t,i,n,o,l)=>{l?E("TextureLoader failed to load data"):a(x,y,s,{width:e,height:t},x.invertY,!i,n,(()=>(o(),!1)),r)}),p)};h?h instanceof ArrayBuffer?t(new Uint8Array(h)):ArrayBuffer.isView(h)?t(h):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,s?s.offlineProvider:void 0,!0,((e,t)=>{E("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{g&&!this._doNotHandleContextLost&&(x._buffer=e),a(x,y,s,e,x.invertY,t,!1,l,r)};!m||v?h&&("string"==typeof h.decoding||h.close)?i(h):ki._FileToolsLoadImage(e,i,E,s?s.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?ki._FileToolsLoadImage(h,i,E,s?s.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return x}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,s,r,n,o,this._prepareWebGLTexture.bind(this),((e,t,i,r,n,o)=>{const a=this._gl,l=i.width===e&&i.height===t;n._creationFlags=_??0;const c=this._getTexImageParametersForCreateTexture(h,r,n._useSRGBBuffer);if(l)return a.texImage2D(a.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),!1;const u=this._caps.maxTextureSize;if(i.width>u||i.height>u||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,c.internalFormat,c.format,c.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new Pi(this,Ai.Temp);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),this._rescaleTexture(e,n,s,c.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,n,!0),o()}))}return!0}),a,l,h,c,u,d,p)}_getTexImageParametersForCreateTexture(e,t,i){let s,r;return null==e&&(e=".jpg"!==t||i?5:4),1===this.webGLVersion?(s=this._getInternalFormat(e,i),r=s):(s=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,i)),{internalFormat:r,format:s,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,i,s,r,n){throw vt("FileTools")}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){throw vt("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,o,a=null){throw vt("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,o,a,l=null,h=0){throw vt("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,o,a,l=null,h=0){throw vt("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(u-s,0)),p=n?e.height:Math.pow(2,Math.max(d-s,0));o.texImage2D(c,s,h,_,p,0,l,a,t)}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,_=h.TEXTURE_2D;e.isCube&&(_=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(_,a,i,s,r,n,u,c,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),i||s||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,o,a,l=3){const h=this.getCaps().maxTextureSize,c=Math.min(h,this.needPOTTextures?ki.GetExponentOfTwo(s.width,h):s.width),u=Math.min(h,this.needPOTTextures?ki.GetExponentOfTwo(s.height,h):s.height),d=this._gl;d&&(e._hardwareTexture?(this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=c,e.height=u,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:".jpg"!==t||e._useSRGBBuffer?5:4,a(c,u,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,o,l)}))||this._prepareWebGLTextureContinuation(e,i,n,o,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture?.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw we.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const a=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(a,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(a,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),this.releaseComputeEffects?.(),this.unbindAllAttributes(),this._boundUniforms={},Lt()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,Ti.ResetCache();for(const e of this._activeRequests)e.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext()}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_loadFile(e,t,i,s,r,n){const o=ki._FileToolsLoadFile(e,t,i,s,r,n);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}static _FileToolsLoadFile(e,t,i,s,r,n){throw vt("FileTools")}readPixels(e,t,i,s,r=!0,n=!0){const o=r?4:3,a=r?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=this._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=this._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){const t=ki.CeilingPOT(e),i=ki.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=ki.FloorPOT(e);break;case 2:s=ki.NearestPOT(e);break;default:s=ki.CeilingPOT(e)}return Math.min(s,t)}static QueueNewFrame(e,t){if(Lt()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:Vt()?document:null}}ki._TempClearColorUint32=new Uint32Array(4),ki._TempClearColorInt32=new Int32Array(4),ki.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],ki._TextureLoaders=[],ki.CollisionsEpsilon=.001,ki._IsSupported=null,ki._HasMajorPerformanceCaveat=null;class Vi{static SetImmediate(e){Lt()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const Ui=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class Gi extends Qt{constructor(e,t){super(e,Yt.LoadFileError),this.name="LoadFileError",Xt._setPrototypeOf(this,Gi.prototype),t instanceof At?this.request=t:this.file=t}}class zi extends Qt{constructor(e,t){super(e,Yt.RequestFileError),this.request=t,this.name="RequestFileError",Xt._setPrototypeOf(this,zi.prototype)}}class Wi extends Qt{constructor(e,t){super(e,Yt.ReadFileError),this.file=t,this.name="ReadFileError",Xt._setPrototypeOf(this,Wi.prototype)}}const Hi={DefaultRetryStrategy:Ht.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e},Xi=e=>e.replace(/#/gm,"%23"),Yi=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&Hi.CorsBehavior)if("string"==typeof Hi.CorsBehavior||Hi.CorsBehavior instanceof String)t.crossOrigin=Hi.CorsBehavior;else{const i=Hi.CorsBehavior(e);i&&(t.crossOrigin=i)}},Qi=(e,t,i,s,r="",n)=>{const o=se.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!o?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let a,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(a=URL.createObjectURL(new Blob([e],{type:r})),l=!0):a=`data:${r};base64,`+qt(e):e instanceof Blob?(a=URL.createObjectURL(e),l=!0):(a=Xi(e),a=Hi.PreprocessUrl(e));const h=t=>{if(i){const s=a||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(o?._features.forceBitmapOverHTMLImageElement)return Ki(a,(s=>{o.createImageBitmap(new Blob([s],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),l&&URL.revokeObjectURL(a)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{h(t)})),null;const c=new Image;Yi(a,c);const u=[],d=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),h(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);se.UseFallbackTexture=!1,h(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const _="blob:"===a.substring(0,5),p="data:"===a.substring(0,5),f=()=>{_||p||!At.IsCustomRequestAvailable?c.src=a:Ki(a,((e,t,i)=>{const s=new Blob([e],{type:!r&&i?i:r}),n=URL.createObjectURL(s);l=!0,c.src=n}),void 0,s||void 0,!0,((e,t)=>{h(t)}))};if(!_&&!p&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(a,c)}),f);else{if(-1!==a.indexOf("file:")){const e=decodeURIComponent(a.substring(5).toLowerCase());if(Wt.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(Wt.FilesToLoad[e])}catch(i){t=URL.createObjectURL(Wt.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}f()}return c},ji=(e,t,i,s,r)=>{const n=new FileReader,o={onCompleteObservable:new X,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),r&&(n.onerror=()=>{r(new Wi(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),s?n.readAsArrayBuffer(e):n.readAsText(e),o},Ki=(e,t,i,s,r,n,o)=>{if(e.name)return ji(e,t,i,r,n?e=>{n(void 0,e)}:void 0);const a=e;if(-1!==a.indexOf("file:")){let e=decodeURIComponent(a.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=Wt.FilesToLoad[e];if(s)return ji(s,t,i,r,n?e=>n(void 0,new Gi(e.message,e.file)):void 0)}const{match:l,type:h}=Ji(a);if(l){const e={onCompleteObservable:new X,abort:()=>()=>{}};try{const e=r?es(a):ts(a);t(e,void 0,h)}catch(e){n?n(void 0,e):we.Error(e.message||"Failed to parse the Data URL")}return Vi.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return $i(a,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,r,n?e=>{n(e.request,new Gi(e.message,e.request))}:void 0,o)},$i=(e,t,i,s,r,n,o)=>{e=Xi(e),e=Hi.PreprocessUrl(e);const a=Hi.BaseUrl+e;let l=!1;const h={onCompleteObservable:new X,abort:()=>l=!0},c=()=>{let e,s=new At,c=null;const u=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",d))};let d=()=>{u(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,d=null,n=void 0,o=void 0,t=void 0};h.abort=()=>{l=!0,d&&d(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const _=e=>{const t=e.message||"Unknown error";n&&s?n(new zi(t,s)):we.Error(t)},p=h=>{if(s){if(s.open("GET",a),o)try{o(s)}catch(e){return void _(e)}r&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),d&&s.addEventListener("loadend",d),e=()=>{if(!l&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!Lt()||qi())){try{t&&t(r?s.response:s.responseText,s)}catch(e){_(e)}return}const i=Hi.DefaultRetryStrategy;if(i){const e=i(a,s,h);if(-1!==e)return u(),s=new At,void(c=setTimeout((()=>p(h+1)),e))}const o=new zi("Error status: "+s.status+" "+s.statusText+" - Unable to load "+a,s);n&&n(o)}},s.addEventListener("readystatechange",e),s.send()}};p(0)};if(s&&s.enableSceneOffline){const o=e=>{e&&e.status>400?n&&n(e):c()},a=()=>{s&&s.loadFile(Hi.BaseUrl+e,(e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)}),i?e=>{!l&&i&&i(e)}:void 0,o,r)};s.open(a,o)}else c();return h},qi=()=>"undefined"!=typeof location&&"file:"===location.protocol,Zi=e=>Ui.test(e),Ji=e=>{const t=Ui.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function es(e){return Jt(e.split(",")[1])}const ts=e=>Zt(e.split(",")[1]);let is;ki._FileToolsLoadImage=Qi,ki._FileToolsLoadFile=Ki,xi._FileToolsLoadFile=Ki;const ss=(e,t,i,s,r,n,o,a,l,h)=>{is={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:r,LoadFile:n,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(is,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(is,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(is,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(is,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})};ss(es,ts,Hi,Zi,qi,Ki,Qi,ji,$i,Yi);class rs{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=te(e);if(t)return t;we.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}rs.RegisteredExternalClasses={};const os={RandomId:ns};function as(e){let t=1;do{t*=2}while(te.indexOf("/"))&&(e.indexOf("://"){Ki(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(hs.ScriptBaseUrl&&e.startsWith(hs._DefaultCdnUrl)){const t="/"===hs.ScriptBaseUrl[hs.ScriptBaseUrl.length-1]?hs.ScriptBaseUrl.substring(0,hs.ScriptBaseUrl.length-1):hs.ScriptBaseUrl;e=e.replace(hs._DefaultCdnUrl,t)}return e=hs.ScriptPreprocessUrl(e),t&&(e=hs.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=hs.GetBabylonScriptURL(e),hs.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=hs.GetBabylonScriptURL(e),hs.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!Lt())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new X,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return ji(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){Xe.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const s=atob(this.toDataURL(t,i).split(",")[1]),r=s.length,n=new Uint8Array(r);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}hs.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if("string"!=typeof s&&t){if(t){if(hs._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,r);t(s)}}else this.ToBlob(e,(function(e){e&&hs.DownloadBlob(e,s),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",(()=>{s.parentElement&&s.parentElement.removeChild(s)})),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,o){throw vt("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw vt("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u){throw vt("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){throw vt("ScreenshotTools")}static RandomId(){return ns()}static IsBase64(e){return Zi(e)}static DecodeBase64(e){return es(e)}static get errorsCount(){return we.errorsCount}static Log(e){we.Log(e)}static Warn(e){we.Warn(e)}static Error(e){we.Error(e)}static get LogCache(){return we.LogCache}static ClearLogCache(){we.ClearLogCache()}static set LogLevels(e){we.LogLevels=e}static set PerformanceLogLevel(e){return(e&hs.PerformanceUserMarkLogLevel)===hs.PerformanceUserMarkLogLevel?(hs.StartPerformanceCounter=hs._StartUserMark,void(hs.EndPerformanceCounter=hs._EndUserMark)):(e&hs.PerformanceConsoleLogLevel)===hs.PerformanceConsoleLogLevel?(hs.StartPerformanceCounter=hs._StartPerformanceConsole,void(hs.EndPerformanceCounter=hs._EndPerformanceConsole)):(hs.StartPerformanceCounter=hs._StartPerformanceCounterDisabled,void(hs.EndPerformanceCounter=hs._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!hs._Performance){if(!Lt())return;hs._Performance=window.performance}t&&hs._Performance.mark&&hs._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&hs._Performance.mark&&(hs._Performance.mark(e+"-End"),hs._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(hs._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(hs._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return zt.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!kt()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}function cs(e,t){return i=>{i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}hs.UseCustomRequestHeaders=!1,hs.CustomRequestHeaders=At.CustomRequestHeaders,hs.GetDOMTextContent=Ut,hs._DefaultCdnUrl="https://cdn.babylonjs.com",hs.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},hs.NoneLogLevel=we.NoneLogLevel,hs.MessageLogLevel=we.MessageLogLevel,hs.WarningLogLevel=we.WarningLogLevel,hs.ErrorLogLevel=we.ErrorLogLevel,hs.AllLogLevel=we.AllLogLevel,hs.IsWindowObjectExist=Lt,hs.PerformanceNoneLogLevel=0,hs.PerformanceUserMarkLogLevel=1,hs.PerformanceConsoleLogLevel=2,hs.StartPerformanceCounter=hs._StartPerformanceCounterDisabled,hs.EndPerformanceCounter=hs._EndPerformanceCounterDisabled;class us{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?s.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(o),r&&r()){s.breakLoop();break}}s.executeNext()}),n)}),s)}}hs.Mix=ls,hs.IsExponentOfTwo=as,se.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class ds{constructor(e){this.length=0,this.data=new Array(e),this._id=ds._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}ds._GlobalId=0;class _s extends ds{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return!(e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;tthis.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}function fs(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class ms{constructor(){this._dirty=!0,this._tempColor=new Ee(0,0,0,0),this._globalCurve=new Ee(0,0,0,0),this._highlightsCurve=new Ee(0,0,0,0),this._midtonesCurve=new Ee(0,0,0,0),this._shadowsCurve=new Ee(0,0,0,0),this._positiveCurve=new Ee(0,0,0,0),this._negativeCurve=new Ee(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){null!=e&&(e=ms._Clamp(e,0,360),t=ms._Clamp(t,-100,100),i=ms._Clamp(i,-100,100),s=ms._Clamp(s,-100,100),t=ms._ApplyColorGradingSliderNonlinear(t),t*=.5,s=ms._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),ms._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let r=ms._Clamp(e,0,360);const n=ms._Clamp(t/100,0,1),o=ms._Clamp(i/100,0,1);if(0===n)s.r=o,s.g=o,s.b=o;else{r/=60;const e=Math.floor(r),t=r-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:s.r=o,s.g=l,s.b=i;break;case 1:s.r=a,s.g=o,s.b=i;break;case 2:s.r=i,s.g=o,s.b=l;break;case 3:s.r=i,s.g=a,s.b=o;break;case 4:s.r=l,s.g=i,s.b=o;break;default:s.r=o,s.g=i,s.b=a}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return yt.Clone((()=>new ms),this)}serialize(){return yt.Serialize(this)}static Parse(e){return yt.Parse((()=>new ms),e,null,null)}}function gs(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&fs(e),t.DITHER&&e.push("ditherIntensity")}function vs(e,t){t.COLORGRADING&&e.push("txColorTransform")}ms.PrepareUniforms=fs,qe([st()],ms.prototype,"_globalHue",void 0),qe([st()],ms.prototype,"_globalDensity",void 0),qe([st()],ms.prototype,"_globalSaturation",void 0),qe([st()],ms.prototype,"_globalExposure",void 0),qe([st()],ms.prototype,"_highlightsHue",void 0),qe([st()],ms.prototype,"_highlightsDensity",void 0),qe([st()],ms.prototype,"_highlightsSaturation",void 0),qe([st()],ms.prototype,"_highlightsExposure",void 0),qe([st()],ms.prototype,"_midtonesHue",void 0),qe([st()],ms.prototype,"_midtonesDensity",void 0),qe([st()],ms.prototype,"_midtonesSaturation",void 0),qe([st()],ms.prototype,"_midtonesExposure",void 0),yt._ColorCurvesParser=ms.Parse;class xs{constructor(){this.colorCurves=new ms,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=xs.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ee(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=xs.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new X}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===xs._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===xs.TONEMAPPING_ACES?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&ms.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:s/i;let n=Math.tan(.5*this.vignetteCameraFov),o=n*r;const a=Math.sqrt(o*n);o=ls(o,a,this.vignetteStretch),n=ls(n,a,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return yt.Clone((()=>new xs),this)}serialize(){return yt.Serialize(this)}static Parse(e){const t=yt.Parse((()=>new xs),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}xs.TONEMAPPING_STANDARD=0,xs.TONEMAPPING_ACES=1,xs.PrepareUniforms=gs,xs.PrepareSamplers=vs,xs._VIGNETTEMODE_MULTIPLY=0,xs._VIGNETTEMODE_OPAQUE=1,qe([ct()],xs.prototype,"colorCurves",void 0),qe([st()],xs.prototype,"_colorCurvesEnabled",void 0),qe([rt("colorGradingTexture")],xs.prototype,"_colorGradingTexture",void 0),qe([st()],xs.prototype,"_colorGradingEnabled",void 0),qe([st()],xs.prototype,"_colorGradingWithGreenDepth",void 0),qe([st()],xs.prototype,"_colorGradingBGR",void 0),qe([st()],xs.prototype,"_exposure",void 0),qe([st()],xs.prototype,"_toneMappingEnabled",void 0),qe([st()],xs.prototype,"_toneMappingType",void 0),qe([st()],xs.prototype,"_contrast",void 0),qe([st()],xs.prototype,"vignetteStretch",void 0),qe([st()],xs.prototype,"vignetteCenterX",void 0),qe([st()],xs.prototype,"vignetteCenterY",void 0),qe([st()],xs.prototype,"vignetteWeight",void 0),qe([ut()],xs.prototype,"vignetteColor",void 0),qe([st()],xs.prototype,"vignetteCameraFov",void 0),qe([st()],xs.prototype,"_vignetteBlendMode",void 0),qe([st()],xs.prototype,"_vignetteEnabled",void 0),qe([st()],xs.prototype,"_ditheringEnabled",void 0),qe([st()],xs.prototype,"_ditheringIntensity",void 0),qe([st()],xs.prototype,"_skipFinalColorClamp",void 0),qe([st()],xs.prototype,"_applyByPostProcess",void 0),qe([st()],xs.prototype,"_isEnabled",void 0),yt._ImageProcessingConfigurationParser=xs.Parse,ki.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new Di(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},ki.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new Di(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},ki.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},ki.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},ki.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},ki.prototype.bindUniformBlock=function(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);4294967295!==r&&this._gl.uniformBlockBinding(s,r,i)};class bs{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,s=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(bs._UpdatedUbosInFrame[this._name]||(bs._UpdatedUbosInFrame[this._name]=0),bs._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer)return void we.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));we.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class ys{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,r,n,o,a,l,h,c=!1,u=!1,d=1,_=!1){this._isDisposed=!1;let p=!1;if(this.engine=e,"object"==typeof s&&null!==s?(p=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,o=s.instanced,a=s.offset,l=s.size,h=s.type,c=s.normalized??!1,u=s.useBytes??!1,d=s.divisor??1,_=s.takeBufferOwnership??!1,this._label=s.label):p=!!s,t instanceof Ts?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new Ts(e,t,p,n,r,o,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=ys._Counter++,this._kind=i,void 0===h){const e=this.getData();this.type=e?ys.GetDataType(e):ys.FLOAT}else this.type=h;const f=ys.GetTypeByteLength(this.type);u?(this._size=l||(n?n/f:ys.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*f,this.byteOffset=a||0):(this._size=l||n||ys.DeduceStride(i),this.byteStride=n?n*f:this._buffer.byteStride||this._size*f,this.byteOffset=(a||0)*f),this.normalized=c,this._instanced=void 0!==o&&o,this._instanceDivisor=o?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?ys.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/ys.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/ys.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*ys.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){ys.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case ys.UVKind:case ys.UV2Kind:case ys.UV3Kind:case ys.UV4Kind:case ys.UV5Kind:case ys.UV6Kind:return 2;case ys.NormalKind:case ys.PositionKind:return 3;case ys.ColorKind:case ys.ColorInstanceKind:case ys.MatricesIndicesKind:case ys.MatricesIndicesExtraKind:case ys.MatricesWeightsKind:case ys.MatricesWeightsExtraKind:case ys.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?ys.BYTE:e instanceof Uint8Array?ys.UNSIGNED_BYTE:e instanceof Int16Array?ys.SHORT:e instanceof Uint16Array?ys.UNSIGNED_SHORT:e instanceof Int32Array?ys.INT:e instanceof Uint32Array?ys.UNSIGNED_INT:ys.FLOAT}static GetTypeByteLength(e){switch(e){case ys.BYTE:case ys.UNSIGNED_BYTE:return 1;case ys.SHORT:case ys.UNSIGNED_SHORT:return 2;case ys.INT:case ys.UNSIGNED_INT:case ys.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,a){if(e instanceof Array){let r=t/4;const o=i/4;for(let t=0;to[t]=e)),o}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==h){if(e instanceof Array){const t=s/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,h);{let t=e.byteOffset+s;if(a){const i=new Float32Array(h),s=new Float32Array(e.buffer,t,h);return i.set(s),i}const i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return a?e.slice():e}}ys._Counter=0,ys.BYTE=5120,ys.UNSIGNED_BYTE=5121,ys.SHORT=5122,ys.UNSIGNED_SHORT=5123,ys.INT=5124,ys.UNSIGNED_INT=5125,ys.FLOAT=5126,ys.PositionKind="position",ys.NormalKind="normal",ys.TangentKind="tangent",ys.UVKind="uv",ys.UV2Kind="uv2",ys.UV3Kind="uv3",ys.UV4Kind="uv4",ys.UV5Kind="uv5",ys.UV6Kind="uv6",ys.ColorKind="color",ys.ColorInstanceKind="instanceColor",ys.MatricesIndicesKind="matricesIndices",ys.MatricesWeightsKind="matricesWeights",ys.MatricesIndicesExtraKind="matricesIndicesExtra",ys.MatricesWeightsExtraKind="matricesWeightsExtra";class Ss{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(ys.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(ys.NormalKind);let t=s?de.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?de.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?de.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),a=a.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new de(t.x+a.x+l.x,t.y+a.y+l.y,t.z+a.z+l.z)}else{const e=this.pickedMesh.getVerticesData(ys.PositionKind),t=s?de.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?de.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?de.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),h=t.subtract(a),c=l.subtract(a);i=de.Cross(h,c)}const a=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(ge.Matrix[0].copyFrom(i),i=ge.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(ge.Matrix[1]),i=ge.Matrix[1]),de.TransformNormalToRef(t,i,t)};if(e&&a(this.pickedMesh,i),this.ray){const t=ge.Vector3[0].copyFrom(i);e||a(this.pickedMesh,t),de.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=ys.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=ue.FromArray(i,2*t[3*this.faceId]),r=ue.FromArray(i,2*t[3*this.faceId+1]),n=ue.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new ue(s.x+r.x+n.x,s.y+r.y+n.y)}}class Cs{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[ys.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[ys.PositionKind]=new ys(this._scene.getEngine(),e,ys.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,s=0,r=0,n=!1){const o=this._scene.getEngine();for(let a=0;anull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let a=0,l=s.length;at._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=ks.LeftClick&&i<=ks.RightClick&&(a.type=1===s?"pointerdown":"pointerup",a.button=i-2),a}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=Xs.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case ks.MouseWheelX:o.deltaX=s;break;case ks.MouseWheelY:o.deltaY=s;break;case ks.MouseWheelZ:o.deltaZ=s}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),a=r.pollInput(e,t,ks.Horizontal),l=r.pollInput(e,t,ks.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,Vs.DeltaHorizontal),o.movementY=r.pollInput(e,t,Vs.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=a,o.clientY=l,o.x=a,o.y=l,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=Ls.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(Ls.Keyboard),s=i&&1===t.pollInput(Ls.Keyboard,0,18),r=i&&1===t.pollInput(Ls.Keyboard,0,17),n=i&&(1===t.pollInput(Ls.Keyboard,0,91)||1===t.pollInput(Ls.Keyboard,0,92)||1===t.pollInput(Ls.Keyboard,0,93)),o=i&&1===t.pollInput(Ls.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Qs{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,r)=>{const n=Ys.CreateDeviceEvent(e,t,s,r,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Ls.Mouse||e===Ls.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const js=Object.keys(ks).length/2;class Ks{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=hs.IsSafari(),this._usingMacOS=kt()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=kt()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=kt()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=hs.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${Ls[e]}`;e>=Ls.DualShock&&e<=Ls.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${Ls[e]} in slot ${t}`;return i===ks.Move&&hs.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ls.Keyboard,0,255));const t=this._inputs[Ls.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(Ls.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ls.Keyboard,0,255));const t=this._inputs[Ls.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=Ys.CreateDeviceEvent(Ls.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(Ls.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Ls.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[Ls.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===Ls.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Ls.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void hs.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=ks.Move,s[ks.Horizontal]=e.clientX,s[ks.Vertical]=e.clientY,t===Ls.Touch&&0===s[ks.LeftClick]&&(s[ks.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===Ls.Mouse?0:e.pointerId;if(t===Ls.Touch){const t=this._activeTouchIds.indexOf(-1);if(!(t>=0))return void hs.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===Ls.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[ks.Horizontal],n=s[ks.Vertical];if(t===Ls.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[ks.Horizontal]=e.clientX,s[ks.Vertical]=e.clientY,s[e.button+2]=1;const o=e;o.inputIndex=e.button+2,this._onInputChanged(t,i,o),r===e.clientX&&n===e.clientY||(o.inputIndex=ks.Move,this._onInputChanged(t,i,o))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===Ls.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Ls.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const r=s[ks.Horizontal],n=s[ks.Vertical];s[ks.Horizontal]=e.clientX,s[ks.Vertical]=e.clientY,s[e.button+2]=0;const o=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(o.inputIndex=ks.Move,this._onInputChanged(t,i,o)),o.inputIndex=e.button+2,t===Ls.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,o),t===Ls.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[Ls.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=ks.LeftClick;t<=ks.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Ys.CreateDeviceEvent(Ls.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ls.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[Ls.Touch][t][ks.LeftClick]=0;const i=Ys.CreateDeviceEvent(Ls.Touch,t,ks.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(Ls.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Ls.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(Ls.Mouse)){const e=this._inputs[Ls.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=ks.LeftClick;t<=ks.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Ys.CreateDeviceEvent(Ls.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ls.Mouse,0,i)}}if(this.isDeviceAvailable(Ls.Touch)){const e=this._inputs[Ls.Touch];for(let t=0;t{const t=Ls.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,js));const i=this._inputs[t][0];if(i){i[ks.MouseWheelX]=e.deltaX||0,i[ks.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[ks.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[ks.MouseWheelX]&&(s.inputIndex=ks.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[ks.MouseWheelY]&&(s.inputIndex=ks.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[ks.MouseWheelZ]&&(s.inputIndex=ks.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(Ls.Mouse)){const e=this._inputs[Ls.Mouse][0];e[ks.MouseWheelX]=0,e[ks.MouseWheelY]=0,e[ks.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Ls.DualSense:Ls.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?Ls.Xbox:-1!==e.indexOf("057e")?Ls.Switch:Ls.Generic}_getPointerType(e){let t=Ls.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Ls.Touch),t}}class $s{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new X,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class qs{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(Ls).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new $s(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new Qs(i,s,r):this._deviceInputSystem=new Ks(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Zs{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(Ls).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new qs(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new X((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new X,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Ls.Keyboard:case Ls.Mouse:this._firstDevice[e]=0;break;case Ls.Touch:case Ls.DualSense:case Ls.DualShock:case Ls.Xbox:case Ls.Switch:case Ls.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=ks.MouseWheelX&&t.inputIndex<=ks.MouseWheelZ?Ms.POINTERWHEEL:Ms.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(o=new ws(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new ws(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,fe.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new Ds(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=ks.Move,this._checkPrePointerObservable(e,i,Ms.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,Ms.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(5,Re.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(2,Re.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(4,Re.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(3,Re.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>er.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(8,Re.CreateNew(e.pickedMesh,t)))}),er.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=Ms.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new ws(r,t,e),this._setRayOnPointerInfo(e,t)):s=new ws(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=ks.Move;const r=new Js;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,Ms.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=Ms.POINTERPICK,r=new ws(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,Re.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,Re.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&s&&s.processTrigger(6,Re.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,Re.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new ws(Ms.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,Ms.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Ms.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=Ms.POINTERTAP:i.doubleClick&&(r=Ms.POINTERDOUBLETAP),r){const i=new ws(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Zs(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>er.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=Ms.POINTERTAP,s=new ws(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const r=new Js;this._currentPickResult=null;let n=null,o=e.hasSpecificMask(Ms.POINTERPICK)||t.hasSpecificMask(Ms.POINTERPICK)||e.hasSpecificMask(Ms.POINTERTAP)||t.hasSpecificMask(Ms.POINTERTAP)||e.hasSpecificMask(Ms.POINTERDOUBLETAP)||t.hasSpecificMask(Ms.POINTERDOUBLETAP);!o&&z&&(n=this._initActionManager(n,r),n&&(o=n.hasPickTriggers));let a=!1;if(o){const o=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let l=!er.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(Ms.POINTERDOUBLETAP)&&!t.hasSpecificMask(Ms.POINTERDOUBLETAP),l&&!z.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(l=!n.hasSpecificTrigger(6)))),l)(Date.now()-this._previousStartingPointerTime>er.DoubleClickDelay||o!==this._previousButtonPressed)&&(r.singleClick=!0,s(r,this._currentPickResult),a=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,o,r,s),er.DoubleClickDelay)};this._delayedClicks[o]=e}let h=e.hasSpecificMask(Ms.POINTERDOUBLETAP)||t.hasSpecificMask(Ms.POINTERDOUBLETAP);!h&&z.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(h=n.hasSpecificTrigger(6))),h&&(o===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>er.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>er.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=ks.MouseWheelX&&e.inputIndex<=ks.MouseWheelZ?Ms.POINTERWHEEL:Ms.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new Ss,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,er.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new Ss:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,Ms.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(Ms.POINTERTAP)&&this._checkPrePointerObservable(null,e,Ms.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(Ms.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,Ms.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(z&&z.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=Ns.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new Bs(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Fs(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,Re.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=Ns.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new Bs(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Fs(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,Re.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===Ls.Mouse?s.onInputChangedObservable.add((r=>{r.inputIndex===ks.LeftClick||r.inputIndex===ks.MiddleClick||r.inputIndex===ks.RightClick||r.inputIndex===ks.BrowserBack||r.inputIndex===ks.BrowserForward?t&&1===s.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===s.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===ks.Move?this._onPointerMove(r):r.inputIndex!==ks.MouseWheelX&&r.inputIndex!==ks.MouseWheelY&&r.inputIndex!==ks.MouseWheelZ||this._onPointerMove(r))})):s.deviceType===Ls.Touch?s.onInputChangedObservable.add((r=>{r.inputIndex===ks.LeftClick&&(t&&1===s.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===ks.Move&&this._onPointerMove(r)})):s.deviceType===Ls.Keyboard&&s.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,Re.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,Re.CreateNew(e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}er.DragMovementThreshold=10,er.LongPressDelay=500,er.DoubleClickDelay=300,er.ExclusiveDoubleClickMode=!1;class tr{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){tr.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){tr.Enabled&&(this._startMonitoringTime=zt.Now)}endMonitoring(e=!0){if(!tr.Enabled)return;e&&this.fetchNewFrame();const t=zt.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=zt.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}tr.Enabled=!0;class ir{constructor(e,t,i,s){this.normal=new de(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new ir(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=ir._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,a=s*i[0]+r*i[1]+n*i[2]+o*i[3],l=s*i[4]+r*i[5]+n*i[6]+o*i[7],h=s*i[8]+r*i[9]+n*i[10]+o*i[11],c=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new ir(a,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=r*l-n*a,c=n*o-s*l,u=s*a-r*o,d=Math.sqrt(h*h+c*c+u*u);let _;return _=0!==d?1/d:0,this.normal.x=h*_,this.normal.y=c*_,this.normal.z=u*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return de.Dot(this.normal,e)<=t}signedDistanceTo(e){return de.Dot(e,this.normal)+this.d}static FromArray(e){return new ir(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new ir(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new ir(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return de.Dot(i,t)+s}}ir._TmpMatrix=fe.Identity();class sr{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new ir(0,0,0,0));return sr.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){sr.GetNearPlaneToRef(e,t[0]),sr.GetFarPlaneToRef(e,t[1]),sr.GetLeftPlaneToRef(e,t[2]),sr.GetRightPlaneToRef(e,t[3]),sr.GetTopPlaneToRef(e,t[4]),sr.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class rr{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}rr._UniqueIdCounter=1;class nr{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}nr.FALLOFF_DEFAULT=0,nr.FALLOFF_PHYSICAL=1,nr.FALLOFF_GLTF=2,nr.FALLOFF_STANDARD=3,nr.LIGHTMAP_DEFAULT=0,nr.LIGHTMAP_SPECULAR=1,nr.LIGHTMAP_SHADOWSONLY=2,nr.INTENSITYMODE_AUTOMATIC=0,nr.INTENSITYMODE_LUMINOUSPOWER=1,nr.INTENSITYMODE_LUMINOUSINTENSITY=2,nr.INTENSITYMODE_ILLUMINANCE=3,nr.INTENSITYMODE_LUMINANCE=4,nr.LIGHTTYPEID_POINTLIGHT=0,nr.LIGHTTYPEID_DIRECTIONALLIGHT=1,nr.LIGHTTYPEID_SPOTLIGHT=2,nr.LIGHTTYPEID_HEMISPHERICLIGHT=3;class or{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var ar,lr,hr,cr,ur;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(ar||(ar={}));class dr extends G{static DefaultMaterialFactory(e){throw vt("StandardMaterial")}static CollisionCoordinatorFactory(){throw vt("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case ar.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case ar.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case ar.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return er.DragMovementThreshold}static set DragMovementThreshold(e){er.DragMovementThreshold=e}static get LongPressDelay(){return er.LongPressDelay}static set LongPressDelay(e){er.LongPressDelay=e}static get DoubleClickDelay(){return er.DoubleClickDelay}static set DoubleClickDelay(e){er.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return er.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){er.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return ge.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,ge.Vector4[0].x,ge.Vector4[0].y,ge.Vector4[0].z):e.setVector4(t,ge.Vector4[0])),ge.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=Z(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=dr.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=dr.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new er(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Ee(.2,.2,.3,1),this.ambientColor=new Ce(0,0,0),this.environmentIntensity=1,this._performancePriority=ar.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new X,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new X,this._onDisposeObserver=null,this.onBeforeRenderObservable=new X,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new X,this.onAfterRenderCameraObservable=new X,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new X,this.onAfterAnimationsObservable=new X,this.onBeforeDrawPhaseObservable=new X,this.onAfterDrawPhaseObservable=new X,this.onReadyObservable=new X,this.onBeforeCameraRenderObservable=new X,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new X,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new X,this.onAfterActiveMeshesEvaluationObservable=new X,this.onBeforeParticlesRenderingObservable=new X,this.onAfterParticlesRenderingObservable=new X,this.onDataLoadedObservable=new X,this.onNewCameraAddedObservable=new X,this.onCameraRemovedObservable=new X,this.onNewLightAddedObservable=new X,this.onLightRemovedObservable=new X,this.onNewGeometryAddedObservable=new X,this.onGeometryRemovedObservable=new X,this.onNewTransformNodeAddedObservable=new X,this.onTransformNodeRemovedObservable=new X,this.onNewMeshAddedObservable=new X,this.onMeshRemovedObservable=new X,this.onNewSkeletonAddedObservable=new X,this.onSkeletonRemovedObservable=new X,this.onNewMaterialAddedObservable=new X,this.onNewMultiMaterialAddedObservable=new X,this.onMaterialRemovedObservable=new X,this.onMultiMaterialRemovedObservable=new X,this.onNewTextureAddedObservable=new X,this.onTextureRemovedObservable=new X,this.onBeforeRenderTargetsRenderObservable=new X,this.onAfterRenderTargetsRenderObservable=new X,this.onBeforeStepObservable=new X,this.onAfterStepObservable=new X,this.onActiveCameraChanged=new X,this.onActiveCamerasChanged=new X,this.onBeforeRenderingGroupObservable=new X,this.onAfterRenderingGroupObservable=new X,this.onMeshImportedObservable=new X,this.onAnimationFileImportedObservable=new X,this._registeredForLateAnimationBindings=new _s(256),this._pointerPickingConfiguration=new or,this.onPrePointerObservable=new X,this.onPointerObservable=new X,this.onPreKeyboardObservable=new X,this.onKeyboardObservable=new X,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=dr.FOGMODE_NONE,this.fogColor=new Ce(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new de(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new _s(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new tr,this._activeIndices=new tr,this._activeParticles=new tr,this._activeBones=new tr,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new ds(256),this._processedMaterials=new ds(256),this._renderTargets=new _s(256),this._materialsRenderTargets=new _s(256),this._activeParticleSystems=new ds(256),this._activeSkeletons=new _s(32),this._softwareSkinnedMeshes=new _s(32),this._activeAnimatables=new Array,this._transformMatrix=fe.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Is.Create(),this._beforeClearStage=Is.Create(),this._beforeRenderTargetClearStage=Is.Create(),this._gatherRenderTargetsStage=Is.Create(),this._gatherActiveCameraRenderTargetsStage=Is.Create(),this._isReadyForMeshStage=Is.Create(),this._beforeEvaluateActiveMeshStage=Is.Create(),this._evaluateSubMeshStage=Is.Create(),this._preActiveMeshStage=Is.Create(),this._cameraDrawRenderTargetStage=Is.Create(),this._beforeCameraDrawStage=Is.Create(),this._beforeRenderTargetDrawStage=Is.Create(),this._beforeRenderingGroupDrawStage=Is.Create(),this._beforeRenderingMeshStage=Is.Create(),this._afterRenderingMeshStage=Is.Create(),this._afterRenderingGroupDrawStage=Is.Create(),this._afterCameraDrawStage=Is.Create(),this._afterCameraPostProcessStage=Is.Create(),this._afterRenderTargetDrawStage=Is.Create(),this._afterRenderTargetPostProcessStage=Is.Create(),this._afterRenderStage=Is.Create(),this._pointerMoveStage=Is.Create(),this._pointerDownStage=Is.Create(),this._pointerUpStage=Is.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||se.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(se._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Ps(this),Cs&&(this.postProcessManager=new Cs(this)),Lt()&&this.attachControl(),this._createUbo(),xs&&(this._imageProcessingConfiguration=new xs),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(s,n)||(r=!1);if(!e)continue;const o=s.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout((()=>{this._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=zt.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?sr.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=sr.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new bs(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return rr.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;return this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||1===r;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){hs.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(Re.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(dr.MinDeltaTime,Math.min(this._engine.getDeltaTime(),dr.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??0,this.activeCamera=s,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null})),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){we.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),se._LastCreatedScene===this&&(this._engine.scenes.length>0?se._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:se._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),r=s.boundingBox.minimumWorld,n=s.boundingBox.maximumWorld;de.CheckExtends(r,t,i),de.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw vt("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw vt("Ray")}createPickingRayInCameraSpace(e,t,i){throw vt("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw vt("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const o=vt("Ray",!0);return o&&we.Warn(o),new Ss}pickWithBoundingInfo(e,t,i,s,r){const n=vt("Ray",!0);return n&&we.Warn(n),new Ss}pickWithRay(e,t,i,s){throw vt("Ray")}multiPick(e,t,i,s,r){throw vt("Ray")}multiPickWithRay(e,t,i){throw vt("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;const s=[];for(const r in e){const n=e[r];bt&&bt.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,r,n,o){const a=Ki(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._loadFile(e,(e=>{n(e)}),t,i,s,((e,t)=>{o(t)}),r)}))}_requestFile(e,t,i,s,r,n,o){const a=$i(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._requestFile(e,(e=>{n(e)}),t,i,s,(e=>{o(e)}),r)}))}_readFile(e,t,i,s,r){const n=ji(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((s,r)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw vt("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}dr.FOGMODE_NONE=0,dr.FOGMODE_EXP=1,dr.FOGMODE_EXP2=2,dr.FOGMODE_LINEAR=3,dr.MinDeltaTime=1,dr.MaxDeltaTime=1e3,function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(lr||(lr={}));class _r{}_r.X=new de(1,0,0),_r.Y=new de(0,1,0),_r.Z=new de(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(hr||(hr={}));class pr extends Ct{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,o=null){super(e,t.getScene()),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??fe.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new fe,this._absoluteBindMatrix=new fe,this._absoluteInverseBindMatrix=new fe,this._finalMatrix=new fe,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=ge.Vector3[0],t=ge.Quaternion[0],i=ge.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??pe.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=de.Zero(),this._localRotation=pe.Zero(),this._localPosition=de.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,fe.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let i=r.length-1;i>=0;i--){const s=r[i];e&&s.animation.name!=e||t&&!t(s.target)||(s.dispose(),r.splice(i,1))}0==r.length&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let s;for(s=0;s0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const s=this._animationTime;for(let e=0;ee.playOrder-t.playOrder))},dr.prototype.beginWeightedAnimation=function(e,t,i,s=1,r,n=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,r,n,o,a,!1,l,h,c);return u.weight=s,u},dr.prototype.beginAnimation=function(e,t,i,s,r=1,n,o,a=!0,l,h,c=!1){t>i&&r>0&&(r*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new fr(this,e,t,i,s,r,n,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;es&&n>0)n*=-1;else if(s>i&&n<0){const e=s;s=i,i=e}return new fr(this,e,i,s,r,n,o,t,a,l)},dr.prototype.beginDirectHierarchyAnimation=function(e,t,i,s,r,n,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));return u},dr.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,r),a.scaleAndAddToRef(l,i)}r.normalize()}for(let t=0;t0)r.copyFrom(s);else if(1===e.animations.length){if(pe.SlerpToRef(s,i.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let i,n,o=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],n=[],i.push(s),n.push(t)}else{if(2===e.animations.length&&(pe.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],o=e.totalWeight}for(let t=0;t=o&&m.frame<=a&&(s?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(_))):p&&r?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(r))):v=m.value):v=m.value,f.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0};class mr{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=Nt.ANIMATIONLOOPMODE_CYCLE}}!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(cr||(cr={}));class gr{static Interpolate(e,t,i,s,r){const n=1-3*s+3*t,o=3*s-6*t,a=3*t;let l=e;for(let t=0;t<5;t++){const t=l*l;l-=1/(3*n*t+2*o*l+a)*(n*(t*l)+o*t+a*l-e),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*r+Math.pow(l,3)}}class vr{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new vr(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new vr(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=xe.Clamp(s,-1,1);const r=Math.acos(s);return new vr(r)}static FromRadians(e){return new vr(e)}static FromDegrees(e){return new vr(e*Math.PI/180)}}class xr{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new ue((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=vr.BetweenTwoPoints(this.centerPoint,this.startPoint);const a=this.startAngle.degrees();let l=vr.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=vr.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-a>180&&(l-=360),l-a<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-a<0?cr.CW:cr.CCW,this.angle=vr.FromDegrees(this.orientation===cr.CW?a-h:h-a)}}class br{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new ue(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new ue(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new ue(e,t),a=new ue(i,s),l=new xr(n,o,a);let h=l.angle.radians()/r;l.orientation===cr.CW&&(h*=-1);let c=l.startAngle.radians()+h;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s,o=this._points[this._points.length-1];for(let a=0;a<=r;a++){const l=a/r,h=n(l,o.x,e,i),c=n(l,o.y,t,s);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const a=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,u=a(c,l.x,e,i,r),d=a(c,l.y,t,s,n);this.addLineTo(u,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;rNumber.EPSILON){if(a<0&&(i=this._points[r],o=-o,n=this._points[s],a=-a),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const s=a*(e.x-i.x)-o*(e.y-i.y);if(0===s)return!0;if(s<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return ue.Zero();const t=e*this.length();let i=0;for(let e=0;e=i&&t<=o){const e=n.normalize(),s=t-i;return new ue(r.x+e.x*s,r.y+e.y*s)}i=o}return ue.Zero()}static StartingAt(e,t){return new br(e,t)}}class Tr{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:de.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:fe.Identity()};for(let t=0;tt){const i=e;e=t,t=i}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(r++,a.push(s)),a.push(...i.slice(r,o)),1===t&&1!==e||a.push(n),new Tr(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(0===s&&(s=1),null==t){let t;t=xe.WithinEpsilon(Math.abs(e.y)/s,1,K)?xe.WithinEpsilon(Math.abs(e.x)/s,1,K)?xe.WithinEpsilon(Math.abs(e.z)/s,1,K)?de.Zero():new de(0,0,1):new de(1,0,0):new de(0,-1,0),i=de.Cross(e,t)}else i=de.Cross(e,t),de.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s,r=i[0],n=0;const o=e*this.length();for(let a=1;ao){const i=(n-o)/l,h=r.subtract(s),c=s.add(h.scaleInPlace(i));return this._setPointAtData(e,1-i,c,a-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=fe.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),a=this._binormals[t].clone(),l=pe.RotationQuaternionFromAxis(s,r,i),h=pe.RotationQuaternionFromAxis(o,a,n);pe.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class yr{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(e,t,i,s)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s;for(let o=0;o<=s;o++)r.push(new de(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new yr(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],o=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r;for(let a=0;a<=r;a++)n.push(new de(o(a/r,e.x,t.x,i.x,s.x),o(a/r,e.y,t.y,i.y,s.y),o(a/r,e.z,t.z,i.z,s.z)));return new yr(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],o=1/r;for(let a=0;a<=r;a++)n.push(de.Hermite(e,t,i,s,a*o));return new yr(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const i=e.length;for(let o=0;o=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}Sr.EASINGMODE_EASEIN=0,Sr.EASINGMODE_EASEOUT=1,Sr.EASINGMODE_EASEINOUT=2;class Cr extends Sr{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Er extends Sr{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class Ar extends Sr{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const s=Math.pow(i,t),r=1-i,n=(1-s)/r+.5*s,o=e*n,a=Math.log(-o*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(r*n),u=.5*(c+(1-Math.pow(i,h))/(r*n)),d=e-u,_=u-c;return-Math.pow(1/i,t-l)/(_*_)*(d-_)*(d+_)}}class Pr extends Sr{easeInCore(e){return e*e*e}}class Rr extends Sr{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),s=Math.max(0,this.springiness);return t=0==s?e:(Math.exp(s*e)-1)/(Math.exp(s)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class Ir extends Sr{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class Mr extends Sr{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class Or extends Sr{easeInCore(e){return e*e}}class Dr extends Sr{easeInCore(e){return e*e*e*e}}class wr extends Sr{easeInCore(e){return e*e*e*e*e}}class Nr extends Sr{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Fr extends Sr{constructor(e=0,t=0,i=1,s=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=s}easeInCore(e){return gr.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class Br{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new Br(this.frame,this.action,this.onlyOnce)}}class Lr{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class kr{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(this.mask||e){this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);const o=new kr(e[0].name+"_merged",e[0]._scene,s);for(const s of e){i&&s.normalize(r,n);for(const e of s.targetedAnimations)o.addTargetedAnimation(e.animation,e.target);t&&s.dispose()}return o}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new X,this.onAnimationLoopObservable=new X,this.onAnimationGroupLoopObservable=new X,this.onAnimationGroupEndObservable=new X,this.onAnimationGroupPauseObservable=new X,this.onAnimationGroupPlayObservable=new X,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||se.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new Lr;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};s.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,n),this._animatables.push(a)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new kr(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const e of this._targetedAnimations)s.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tr[0].frame&&(e=r[0].frame),t=t&&e<=i||r&&s.frame>=t&&s.frame<=i){const e={frame:s.frame,value:s.value.clone?s.value.clone():s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation,lockedTangent:s.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),o1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach((e=>e(this))),this}onchange(e){return this._onchange.push(e),this}}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(ur||(ur={}));class Ur{constructor(e,t=ur.Include){this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}addTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.add(t);else this._targetNames.add(e)}removeTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.delete(t);else this._targetNames.delete(e)}hasTarget(e){return this._targetNames.has(e)}retainsTarget(e){return this._targetNames.has(e)===(this.mode===ur.Include)}}function Gr(e,t,i){try{const s=e.next();s.done?t(s):s.value?s.value.then((()=>{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function zr(e=25){let t;return(i,s,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{Gr(i,s,r)}),0)):Gr(i,s,r)}}function Wr(e,t,i,s,r){const n=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:n()};do{o=void 0,r&&r.aborted?s(new Error("Aborted")):t(e,a,s),void 0===o&&(o=!1)}while(o)};n()}function Hr(e,t){let i;return Wr(e,Gr,(e=>i=e),(e=>{throw e}),t),i}function Xr(e,t,i){return new Promise(((s,r)=>{Wr(e,t,s,r,i)}))}function Yr(e,t){return(...i)=>Hr(e(...i),t)}function Qr(e,t,i){return(...s)=>Xr(e(...s),t,i)}class jr{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new jr(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new jr(this.x,this.y,this.width,this.height)}}class Kr extends Ct{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===Kr.PERSPECTIVE_CAMERA)this.fovMode===Kr.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i),this._position=de.Zero(),this._upVector=de.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=Kr.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new jr(0,0,1,1),this.layerMask=268435455,this.fovMode=Kr.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Kr.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new X,this.onProjectionMatrixChangedObservable=new X,this.onAfterCheckInputsObservable=new X,this.onRestoreStateObservable=new X,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new fe,this._postProcesses=new Array,this._activeMeshes=new ds(256),this._globalPosition=de.Zero(),this._computedViewMatrix=fe.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=fe.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=pe.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(we.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return fe.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===Kr.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=i.useRightHandedSystem?fe.PerspectiveFovRHToRef:fe.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Kr.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?fe.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):fe.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?fe.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):fe.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?de.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?sr.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=sr.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw vt("Ray")}getForwardRayToRef(e,t=100,i,s){throw vt("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==Kr.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=hs.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Kr.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return fe.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=hs.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eKr._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=Kr.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=yt.Parse(s,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=de.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(de.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(de.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw vt("UniversalCamera")},Kr.PERSPECTIVE_CAMERA=0,Kr.ORTHOGRAPHIC_CAMERA=1,Kr.FOVMODE_VERTICAL_FIXED=0,Kr.FOVMODE_HORIZONTAL_FIXED=1,Kr.RIG_MODE_NONE=0,Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Kr.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Kr.RIG_MODE_VR=20,Kr.RIG_MODE_CUSTOM=22,Kr.ForceAttachControlToAlwaysPreventDefault=!1,qe([lt("position")],Kr.prototype,"_position",void 0),qe([lt("upVector")],Kr.prototype,"_upVector",void 0),qe([st()],Kr.prototype,"orthoLeft",null),qe([st()],Kr.prototype,"orthoRight",null),qe([st()],Kr.prototype,"orthoBottom",null),qe([st()],Kr.prototype,"orthoTop",null),qe([st()],Kr.prototype,"fov",void 0),qe([st()],Kr.prototype,"projectionPlaneTilt",void 0),qe([st()],Kr.prototype,"minZ",void 0),qe([st()],Kr.prototype,"maxZ",void 0),qe([st()],Kr.prototype,"inertia",void 0),qe([st()],Kr.prototype,"mode",null),qe([st()],Kr.prototype,"layerMask",void 0),qe([st()],Kr.prototype,"fovMode",void 0),qe([st()],Kr.prototype,"cameraRigMode",void 0),qe([st()],Kr.prototype,"interaxialDistance",void 0),qe([st()],Kr.prototype,"isStereoscopicSideBySide",void 0);class $r{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class qr{constructor(e,t,i){this.vectors=$.BuildArray(8,de.Zero),this.center=de.Zero(),this.centerWorld=de.Zero(),this.extendSize=de.Zero(),this.extendSizeWorld=de.Zero(),this.directions=$.BuildArray(3,de.Zero),this.vectorsWorld=$.BuildArray(8,de.Zero),this.minimumWorld=de.Zero(),this.maximumWorld=de.Zero(),this.minimum=de.Zero(),this.maximum=de.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,o=t.x,a=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,a,l),h[0].copyFromFloats(s,r,n),h[1].copyFromFloats(o,a,l),h[2].copyFromFloats(o,r,n),h[3].copyFromFloats(s,a,n),h[4].copyFromFloats(s,r,l),h[5].copyFromFloats(o,a,n),h[6].copyFromFloats(s,a,l),h[7].copyFromFloats(o,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||fe.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=qr._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(.5*r),o=this.center.subtractToRef(n,t[1]),a=this.center.addToRef(n,t[2]);return this.reConstruct(o,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const o=r[s];de.TransformCoordinatesToRef(n[s],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}de.FromArrayToRef(e.m,0,s[0]),de.FromArrayToRef(e.m,4,s[1]),de.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return qr.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return qr.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,a=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-K;return!(o-hh-s||a-cc-r||l-uu-n)}intersectsSphere(e){return qr.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,o=i.z,a=s.x,l=s.y,h=s.z,c=e.x,u=e.y,d=e.z,_=t.x,p=t.y,f=t.z;return!(a_||lp||hf)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=qr._TmpVector3[0];return de.ClampToRef(i,e,t,r),de.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}qr._TmpVector3=$.BuildArray(3,de.Zero);class Zr{constructor(e,t,i){this.center=de.Zero(),this.centerWorld=de.Zero(),this.minimum=de.Zero(),this.maximum=de.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=de.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||fe.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Zr._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{de.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Zr._TmpVector3[0];de.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=de.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const s=de.Dot(t.centerWorld,e),r=Math.abs(de.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(de.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(de.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-r,i.max=s+r},sn=(e,t,i)=>(tn(e,t,Jr),tn(e,i,en),!(Jr.min>en.max||en.min>Jr.max));class rn{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new qr(e,t,i),this.boundingSphere=new Zr(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=rn._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=rn._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=de.Minimize(this.minimum,e),i=de.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=ge.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=ge.Vector3[0];return de.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),de.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,rn._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e)}intersects(e,t){if(!Zr.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!qr.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!(sn(i.directions[0],i,s)&&sn(i.directions[1],i,s)&&sn(i.directions[2],i,s)&&sn(s.directions[0],i,s)&&sn(s.directions[1],i,s)&&sn(s.directions[2],i,s)&&sn(de.Cross(i.directions[0],s.directions[0]),i,s)&&sn(de.Cross(i.directions[0],s.directions[1]),i,s)&&sn(de.Cross(i.directions[0],s.directions[2]),i,s)&&sn(de.Cross(i.directions[1],s.directions[0]),i,s)&&sn(de.Cross(i.directions[1],s.directions[1]),i,s)&&sn(de.Cross(i.directions[1],s.directions[2]),i,s)&&sn(de.Cross(i.directions[2],s.directions[0]),i,s)&&sn(de.Cross(i.directions[2],s.directions[1]),i,s)&&sn(de.Cross(i.directions[2],s.directions[2]),i,s))}}rn._TmpVector3=$.BuildArray(2,de.Zero);class nn{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o!Array.isArray(e)&&!Array.isArray(t)))],nn,"extractMinAndMaxIndexed",null),qe([mt.filter(((...[e])=>!Array.isArray(e)))],nn,"extractMinAndMax",null);class ln{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Fi(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,o,a=!0){return new ln(e,t,i,s,r,n,o,a)}constructor(e,t,i,s,r,n,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=o||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,a&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(ys.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=on(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new rn(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;ta&&(a=t)}return new ln(e,o,a-o+1,t,i,s,r,n)}}class hn{}class cn{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Yr(this._applyToCoroutine.bind(this)),this.uniqueId=cn._UniqueIDGenerator,cn._UniqueIDGenerator++}set(e,t){switch(e.length||we.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case ys.PositionKind:this.positions=e;break;case ys.NormalKind:this.normals=e;break;case ys.TangentKind:this.tangents=e;break;case ys.UVKind:this.uvs=e;break;case ys.UV2Kind:this.uvs2=e;break;case ys.UV3Kind:this.uvs3=e;break;case ys.UV4Kind:this.uvs4=e;break;case ys.UV5Kind:this.uvs5=e;break;case ys.UV6Kind:this.uvs6=e;break;case ys.ColorKind:this.colors=e;break;case ys.MatricesIndicesKind:this.matricesIndices=e;break;case ys.MatricesWeightsKind:this.matricesWeights=e;break;case ys.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case ys.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(ys.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(ys.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(ys.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(ys.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(ys.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(ys.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(ys.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(ys.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(ys.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(ys.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(ys.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(ys.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(ys.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(ys.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new ln(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(ys.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(ys.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(ys.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(ys.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(ys.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(ys.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(ys.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(ys.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(ys.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(ys.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(ys.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(ys.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(ys.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(ys.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=ge.Vector3[0],n=ge.Vector3[1];for(let o=i;o({vertexData:e}))):[{vertexData:e}];return Hr(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){this._validate();let a=t.map((e=>e.vertexData)),l=this;if(o)for(const e of a)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of a)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,s=0,r=0;const n=[];let o=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,o&&o.materialIndex===i)o.indexCount+=t.indices.length,o.verticesCount+=t.positions.length/3;else{const e=new hn;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),o=e}s+=t.indices.length,r+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,a=h.map((e=>e.vertexData)),t=h,this.materialInfos=n}const h=a.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=r||a.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let r=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&cn._FlipFaces(c,0,r)}let n=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),s&&(yield),l.normals&&(this.normals=cn._MergeElement(ys.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),l.tangents&&(this.tangents=cn._MergeElement(ys.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),l.uvs&&(this.uvs=cn._MergeElement(ys.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),l.uvs2&&(this.uvs2=cn._MergeElement(ys.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),l.uvs3&&(this.uvs3=cn._MergeElement(ys.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),l.uvs4&&(this.uvs4=cn._MergeElement(ys.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),l.uvs5&&(this.uvs5=cn._MergeElement(ys.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),l.uvs6&&(this.uvs6=cn._MergeElement(ys.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),l.colors&&(this.colors=cn._MergeElement(ys.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),l.matricesIndices&&(this.matricesIndices=cn._MergeElement(ys.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),l.matricesWeights&&(this.matricesWeights=cn._MergeElement(ys.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=cn._MergeElement(ys.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=cn._MergeElement(ys.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const r=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),o=e===ys.PositionKind?cn._TransformVector3Coordinates:e===ys.NormalKind?cn._TransformVector3Normals:e===ys.TangentKind?cn._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&o(e,i,0,t.length);let s=t.length;for(const[t,i]of r)e.set(t,s),i&&o(e,i,s,t.length),s+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=ys.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(ys.PositionKind,this.positions),i=(i,s)=>{const r=e(i,s);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(ys.NormalKind,this.normals),this.tangents&&i(ys.TangentKind,this.tangents),this.uvs&&i(ys.UVKind,this.uvs),this.uvs2&&i(ys.UV2Kind,this.uvs2),this.uvs3&&i(ys.UV3Kind,this.uvs3),this.uvs4&&i(ys.UV4Kind,this.uvs4),this.uvs5&&i(ys.UV5Kind,this.uvs5),this.uvs6&&i(ys.UV6Kind,this.uvs6),this.colors&&i(ys.ColorKind,this.colors),this.matricesIndices&&i(ys.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(ys.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(ys.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(ys.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return cn.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return cn._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return cn._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new cn;return e.isVerticesDataPresent(ys.PositionKind)&&(s.positions=e.getVerticesData(ys.PositionKind,t,i)),e.isVerticesDataPresent(ys.NormalKind)&&(s.normals=e.getVerticesData(ys.NormalKind,t,i)),e.isVerticesDataPresent(ys.TangentKind)&&(s.tangents=e.getVerticesData(ys.TangentKind,t,i)),e.isVerticesDataPresent(ys.UVKind)&&(s.uvs=e.getVerticesData(ys.UVKind,t,i)),e.isVerticesDataPresent(ys.UV2Kind)&&(s.uvs2=e.getVerticesData(ys.UV2Kind,t,i)),e.isVerticesDataPresent(ys.UV3Kind)&&(s.uvs3=e.getVerticesData(ys.UV3Kind,t,i)),e.isVerticesDataPresent(ys.UV4Kind)&&(s.uvs4=e.getVerticesData(ys.UV4Kind,t,i)),e.isVerticesDataPresent(ys.UV5Kind)&&(s.uvs5=e.getVerticesData(ys.UV5Kind,t,i)),e.isVerticesDataPresent(ys.UV6Kind)&&(s.uvs6=e.getVerticesData(ys.UV6Kind,t,i)),e.isVerticesDataPresent(ys.ColorKind)&&(s.colors=e.getVerticesData(ys.ColorKind,t,i)),e.isVerticesDataPresent(ys.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(ys.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(ys.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(ys.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(ys.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(ys.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(ys.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(ys.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw vt("ribbonBuilder")}static CreateBox(e){throw vt("boxBuilder")}static CreateTiledBox(e){throw vt("tiledBoxBuilder")}static CreateTiledPlane(e){throw vt("tiledPlaneBuilder")}static CreateSphere(e){throw vt("sphereBuilder")}static CreateCylinder(e){throw vt("cylinderBuilder")}static CreateTorus(e){throw vt("torusBuilder")}static CreateLineSystem(e){throw vt("linesBuilder")}static CreateDashedLines(e){throw vt("linesBuilder")}static CreateGround(e){throw vt("groundBuilder")}static CreateTiledGround(e){throw vt("groundBuilder")}static CreateGroundFromHeightMap(e){throw vt("groundBuilder")}static CreatePlane(e){throw vt("planeBuilder")}static CreateDisc(e){throw vt("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw vt("polygonBuilder")}static CreateIcoSphere(e){throw vt("icoSphereBuilder")}static CreatePolyhedron(e){throw vt("polyhedronBuilder")}static CreateCapsule(e={orientation:de.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw vt("capsuleBuilder")}static CreateTorusKnot(e){throw vt("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=0,v=0,x=0,b=0,T=0,y=0,S=0,C=!1,E=!1,A=!1,P=!1,R=1,I=0,M=null;s&&(C=!!s.facetNormals,E=!!s.facetPositions,A=!!s.facetPartitioning,R=!0===s.useRightHandedSystem?-1:1,I=s.ratio||0,P=!!s.depthSort,M=s.distanceTo,P&&void 0===M&&(M=de.Zero()));let O=0,D=0,w=0,N=0;for(A&&s&&s.bbSize&&(O=s.subDiv.X*I/s.bbSize.x,D=s.subDiv.Y*I/s.bbSize.y,w=s.subDiv.Z*I/s.bbSize.z,N=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],cn,"_TransformVector3Coordinates",null),qe([mt.filter(((...[e])=>!Array.isArray(e)))],cn,"_TransformVector3Normals",null),qe([mt.filter(((...[e])=>!Array.isArray(e)))],cn,"_TransformVector4Normals",null),qe([mt.filter(((...[e])=>!Array.isArray(e)))],cn,"_FlipFaces",null);class un{static get ForceFullSceneLoadingForIncremental(){return un._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){un._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return un._ShowLoadingScreen}static set ShowLoadingScreen(e){un._ShowLoadingScreen=e}static get loggingLevel(){return un._LoggingLevel}static set loggingLevel(e){un._LoggingLevel=e}static get CleanBoneMatrixWeights(){return un._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){un._CleanBoneMatrixWeights=e}}un._ForceFullSceneLoadingForIncremental=!1,un._ShowLoadingScreen=!0,un._CleanBoneMatrixWeights=!1,un._LoggingLevel=0;class dn{}dn.UseOpenGLOrientationForUV=!1;class _n{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new _n(_n.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||se.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new ys(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const r=this._meshes,n=r.length;if(s===ys.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new de(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(ys.PositionKind)))return;this._extend=an(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===ys.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new cn;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(ys.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(ys.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(ys.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(dn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(ys.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(ys.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(ys.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(ys.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(ys.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(ys.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(ys.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(_n._CleanMatricesWeights(e,t),t.setVerticesData(ys.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(ys.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const r=t.getVerticesData(ys.MatricesIndicesKind),n=t.getVerticesData(ys.MatricesIndicesExtraKind),o=e.matricesWeights,a=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let e=0;el-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)o[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else h>=4?(a[e+h-4]=1-t,n[e+h-4]=s):(o[e+h]=1-t,r[e+h]=s)}t.setVerticesData(ys.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(ys.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new _n(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,bt&&bt.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new rn(de.FromArray(e.boundingBoxMinimum),de.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(ys.UVKind),e.hasUVs2&&s._delayInfo.push(ys.UV2Kind),e.hasUVs3&&s._delayInfo.push(ys.UV3Kind),e.hasUVs4&&s._delayInfo.push(ys.UV4Kind),e.hasUVs5&&s._delayInfo.push(ys.UV5Kind),e.hasUVs6&&s._delayInfo.push(ys.UV6Kind),e.hasColors&&s._delayInfo.push(ys.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(ys.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(ys.MatricesWeightsKind),s._delayLoadingFunction=cn.ImportVertexData):cn.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class pn{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new fn(e)}sampleFrame(e=zt.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class fn{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}function mn(e,t,i=!1,s){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return s&&e.set(new Int8Array(s)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return s&&e.set(new Uint8Array(s)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return s&&e.set(new Int16Array(s)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return s&&e.set(new Uint16Array(s)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return s&&e.set(new Int32Array(s)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return s&&e.set(new Uint32Array(s)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return s&&e.set(new Float32Array(s)),e}}const r=(ArrayBuffer,new Uint8Array(t));return s&&r.set(new Uint8Array(s)),r}ki.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},ki.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},ki.prototype.getAlphaMode=function(){return this._alphaMode},ki.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},ki.prototype.getAlphaEquation=function(){return this._alphaEquation},ki.prototype._readTexturePixelsSync=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return a?n||(n=mn(e.type,4*t*i)):u===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),u=c.FLOAT),o&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},ki.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,r,n,o,a,l,h))},ki.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},ki.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===s||s>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()};class gn extends ki{static get NpmPackage(){return ki.NpmPackage}static get Version(){return ki.Version}static get Instances(){return se.Instances}static get LastCreatedEngine(){return se.LastCreatedEngine}static get LastCreatedScene(){return se.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise(((i,s)=>{const r=new Image;r.onload=()=>{r.decode().then((()=>{this.createImageBitmap(r,t).then((e=>{i(e)}))}))},r.onerror=()=>{s(`Error loading image ${r.src}`)},r.src=e}))}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const s=this.createCanvas(t,i).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(e,0,0),s.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};const t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!gn.audioEngine&&this._creationOptions.audioEngine&&gn.AudioEngineFactory&&(gn.audioEngine=gn.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),Vt()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&gn._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==gn.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){this._onPointerLockChange?.()}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()}restoreStencilState(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}setDirectViewport(e,t,i,s){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise(((s,r)=>{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{r(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))}setTextureFromPostProcess(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)}setTextureFromPostProcessOutput(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures();super._rebuildTextures()}_renderFrame(){for(let e=0;e1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++gn._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()})))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new Ni(e,this._gl),o=new Pi(this,Ai.Unknown,!0);return o._hardwareTexture=n,o.baseWidth=s,o.baseHeight=r,o.width=s,o.height=r,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=r.TEXTURE_2D;e.isCube&&(h=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(h,s,a,o,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void we.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new Di(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((r,n)=>{const o=()=>{const a=s.clientWaitSync(e,t,0);a!=s.WAIT_FAILED?a!=s.TIMEOUT_EXPIRED?r():setTimeout(o,i):n()};o()}))}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,s,r,n,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===se.Instances.length&&gn.audioEngine&&(gn.audioEngine.dispose(),gn.audioEngine=null);const e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),Vt()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();const t=se.Instances.indexOf(this);t>=0&&se.Instances.splice(t,1),gn.Instances.length||se.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!Lt())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!Lt())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=gn.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){const t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}}gn.ALPHA_DISABLE=0,gn.ALPHA_ADD=1,gn.ALPHA_COMBINE=2,gn.ALPHA_SUBTRACT=3,gn.ALPHA_MULTIPLY=4,gn.ALPHA_MAXIMIZED=5,gn.ALPHA_ONEONE=6,gn.ALPHA_PREMULTIPLIED=7,gn.ALPHA_PREMULTIPLIED_PORTERDUFF=8,gn.ALPHA_INTERPOLATE=9,gn.ALPHA_SCREENMODE=10,gn.DELAYLOADSTATE_NONE=0,gn.DELAYLOADSTATE_LOADED=1,gn.DELAYLOADSTATE_LOADING=2,gn.DELAYLOADSTATE_NOTLOADED=4,gn.NEVER=512,gn.ALWAYS=519,gn.LESS=513,gn.EQUAL=514,gn.LEQUAL=515,gn.GREATER=516,gn.GEQUAL=518,gn.NOTEQUAL=517,gn.KEEP=7680,gn.REPLACE=7681,gn.INCR=7682,gn.DECR=7683,gn.INVERT=5386,gn.INCR_WRAP=34055,gn.DECR_WRAP=34056,gn.TEXTURE_CLAMP_ADDRESSMODE=0,gn.TEXTURE_WRAP_ADDRESSMODE=1,gn.TEXTURE_MIRROR_ADDRESSMODE=2,gn.TEXTUREFORMAT_ALPHA=0,gn.TEXTUREFORMAT_LUMINANCE=1,gn.TEXTUREFORMAT_LUMINANCE_ALPHA=2,gn.TEXTUREFORMAT_RGB=4,gn.TEXTUREFORMAT_RGBA=5,gn.TEXTUREFORMAT_RED=6,gn.TEXTUREFORMAT_R=6,gn.TEXTUREFORMAT_RG=7,gn.TEXTUREFORMAT_RED_INTEGER=8,gn.TEXTUREFORMAT_R_INTEGER=8,gn.TEXTUREFORMAT_RG_INTEGER=9,gn.TEXTUREFORMAT_RGB_INTEGER=10,gn.TEXTUREFORMAT_RGBA_INTEGER=11,gn.TEXTURETYPE_UNSIGNED_BYTE=0,gn.TEXTURETYPE_UNSIGNED_INT=0,gn.TEXTURETYPE_FLOAT=1,gn.TEXTURETYPE_HALF_FLOAT=2,gn.TEXTURETYPE_BYTE=3,gn.TEXTURETYPE_SHORT=4,gn.TEXTURETYPE_UNSIGNED_SHORT=5,gn.TEXTURETYPE_INT=6,gn.TEXTURETYPE_UNSIGNED_INTEGER=7,gn.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,gn.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,gn.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,gn.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,gn.TEXTURETYPE_UNSIGNED_INT_24_8=12,gn.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,gn.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,gn.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,gn.TEXTURE_NEAREST_SAMPLINGMODE=1,gn.TEXTURE_BILINEAR_SAMPLINGMODE=2,gn.TEXTURE_TRILINEAR_SAMPLINGMODE=3,gn.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,gn.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,gn.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,gn.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,gn.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,gn.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,gn.TEXTURE_NEAREST_LINEAR=7,gn.TEXTURE_NEAREST_NEAREST=1,gn.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,gn.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,gn.TEXTURE_LINEAR_LINEAR=2,gn.TEXTURE_LINEAR_NEAREST=12,gn.TEXTURE_EXPLICIT_MODE=0,gn.TEXTURE_SPHERICAL_MODE=1,gn.TEXTURE_PLANAR_MODE=2,gn.TEXTURE_CUBIC_MODE=3,gn.TEXTURE_PROJECTION_MODE=4,gn.TEXTURE_SKYBOX_MODE=5,gn.TEXTURE_INVCUBIC_MODE=6,gn.TEXTURE_EQUIRECTANGULAR_MODE=7,gn.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,gn.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,gn.SCALEMODE_FLOOR=1,gn.SCALEMODE_NEAREST=2,gn.SCALEMODE_CEILING=3,gn._RescalePostProcessFactory=null,gn._RenderPassIdCounter=0;const vn=fe.Compose(de.One(),pe.FromEulerAngles(0,Math.PI,0),de.Zero());class xn extends Ct{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&xn.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==xn.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new de(0,0,1),this._up=new de(0,1,0),this._right=new de(1,0,0),this._position=de.Zero(),this._rotation=de.Zero(),this._rotationQuaternion=null,this._scaling=de.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=xn.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=fe.Zero(),this._usePivotMatrix=!1,this._absolutePosition=de.Zero(),this._absoluteScaling=de.Zero(),this._absoluteRotationQuaternion=pe.Identity(),this._pivotMatrix=fe.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new X,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return de.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return de.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return de.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=fe.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==xn.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=fe.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||pe.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const e=ge.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),de.TransformCoordinatesFromFloatsToRef(t,i,s,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=de.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=ge.Matrix[0];return this._localMatrix.invertToRef(e),de.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=de.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=lr.LOCAL){const n=xn._LookAtVectorCache,o=r===lr.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===lr.WORLD&&this.parent)if(this.rotationQuaternion){const e=ge.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=ge.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=ge.Quaternion[0];pe.FromEulerVectorToRef(this.rotation,e);const t=ge.Matrix[0];e.toRotationMatrix(t);const i=ge.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=de.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return de.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?pe.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=lr.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==lr.WORLD){const t=ge.Matrix[0];i.invertToRef(t),e=de.TransformCoordinates(e,t)}return this.setPivotMatrix(fe.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=de.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=de.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),de.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=ge.Quaternion[0],r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Matrix[1];fe.IdentityToRef(o);const a=ge.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=xn._TmpRotation,pe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),fe.ComposeToRef(this.scaling,l,this.position,a),this.parent&&a.multiplyToRef(this.parent.computeWorldMatrix(!0),a),e&&(e.computeWorldMatrix(!0).invertToRef(o),a.multiplyToRef(o,a)),a.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(fe.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==lr.LOCAL){if(this.parent){const i=this.parent.getWorldMatrix(),s=ge.Matrix[0];i.invertToRef(s),e=de.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=pe.RotationAxisToRef(e,t,xn._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=pe.RotationAxisToRef(e,t,xn._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=pe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=ge.Vector3[0],r=ge.Vector3[1],n=ge.Vector3[2],o=ge.Quaternion[0],a=ge.Matrix[0],l=ge.Matrix[1],h=ge.Matrix[2],c=ge.Matrix[3];return e.subtractToRef(this.position,s),fe.TranslationToRef(s.x,s.y,s.z,a),fe.TranslationToRef(-s.x,-s.y,-s.z,l),fe.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(a,c),c.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&i!==lr.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=ge.Quaternion[1],pe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=ge.Quaternion[0];return pe.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==xn.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=xn._TmpScaling;let o,a=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new de(e.m[12],e.m[13],e.m[14]);a=xn._TmpTranslation,a.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(pe.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=xn._TmpRotation,pe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const e=ge.Matrix[1];fe.ScalingToRef(n.x,n.y,n.z,e);const t=ge.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,ge.Matrix[4]),ge.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else fe.ComposeToRef(n,o,a,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),ge.Matrix[7])}else ge.Matrix[7].copyFrom(r.getWorldMatrix());const e=ge.Vector3[5],t=ge.Vector3[6],i=ge.Quaternion[0];ge.Matrix[7].decompose(t,i,e),fe.ScalingToRef(t.x,t.y,t.z,ge.Matrix[7]),ge.Matrix[7].setTranslation(e),xn.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(ge.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),ge.Matrix[6]),ge.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=ge.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),ge.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&ge.Matrix[1].multiplyToRef(vn,ge.Matrix[1]),ge.Matrix[1].setTranslationFromFloats(0,0,0),ge.Matrix[1].invertToRef(ge.Matrix[0]),(this.billboardMode&xn.BILLBOARDMODE_ALL)!==xn.BILLBOARDMODE_ALL){ge.Matrix[0].decompose(void 0,ge.Quaternion[0],void 0);const e=ge.Vector3[1];ge.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&xn.BILLBOARDMODE_X)!==xn.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&xn.BILLBOARDMODE_Y)!==xn.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&xn.BILLBOARDMODE_Z)!==xn.BILLBOARDMODE_Z&&(e.z=0),fe.RotationYawPitchRollToRef(e.y,e.x,e.z,ge.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ge.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ge.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=ge.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(ge.Matrix[1]);const s=ge.Vector3[1];de.TransformCoordinatesToRef(i,ge.Matrix[1],s),s.normalize();const r=-Math.atan2(s.z,s.x)+Math.PI/2,n=Math.sqrt(s.x*s.x+s.z*s.z),o=-Math.atan2(s.y,n);if(pe.RotationYawPitchRollToRef(r,o,0,ge.Quaternion[0]),(this.billboardMode&xn.BILLBOARDMODE_ALL)!==xn.BILLBOARDMODE_ALL){const e=ge.Vector3[1];ge.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&xn.BILLBOARDMODE_X)!==xn.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&xn.BILLBOARDMODE_Y)!==xn.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&xn.BILLBOARDMODE_Z)!==xn.BILLBOARDMODE_Z&&(e.z=0),fe.RotationYawPitchRollToRef(e.y,e.x,e.z,ge.Matrix[0])}else fe.FromQuaternionToRef(ge.Quaternion[0],ge.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ge.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ge.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=fe.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew xn(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew xn(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(fe.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(fe.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof xn)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}xn.BILLBOARDMODE_NONE=0,xn.BILLBOARDMODE_X=1,xn.BILLBOARDMODE_Y=2,xn.BILLBOARDMODE_Z=4,xn.BILLBOARDMODE_ALL=7,xn.BILLBOARDMODE_USE_POSITION=128,xn.BillboardUseParentOrientation=!1,xn._TmpRotation=pe.Zero(),xn._TmpScaling=de.Zero(),xn._TmpTranslation=de.Zero(),xn._LookAtVectorCache=new de(0,0,0),xn._RotationAxisCache=new pe,qe([lt("position")],xn.prototype,"_position",void 0),qe([lt("rotation")],xn.prototype,"_rotation",void 0),qe([_t("rotationQuaternion")],xn.prototype,"_rotationQuaternion",void 0),qe([lt("scaling")],xn.prototype,"_scaling",void 0),qe([st("billboardMode")],xn.prototype,"_billboardMode",void 0),qe([st()],xn.prototype,"scalingDeterminant",void 0),qe([st("infiniteDistance")],xn.prototype,"_infiniteDistance",void 0),qe([st()],xn.prototype,"ignoreNonUniformScaling",void 0),qe([st()],xn.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class bn{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new de(0,0,0),this._diffPositionForCollisions=new de(0,0,0),this._collisionResponse=!0}}class Tn{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=de.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class yn{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Tn,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new bn,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Sn extends xn{static get BILLBOARDMODE_NONE(){return xn.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return xn.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return xn.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return xn.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return xn.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return xn.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return!!super._updateNonUniformScalingState(e)&&(this._markSubMeshesAsMiscDirty(),!0)}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new yn,this._waitingMaterialId=null,this.cullingStrategy=Sn.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new X,this.onCollisionPositionChangeObservable=new X,this.onMaterialChangedObservable=new X,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Ce.Red(),this.outlineWidth=.02,this.overlayColor=Ce.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new de(.5,1,.5),this.ellipsoidOffset=new de(0,0,0),this.edgesWidth=1,this.edgesColor=new Ee(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new X,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>gn.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new bs(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case ar.Aggressive:this.doNotSyncBoundingInfo=!0;case ar.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==xn.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new rn(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(ys.MatricesIndicesKind)&&this.isVerticesDataPresent(ys.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===xn.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new fe;(this.rotationQuaternion?this.rotationQuaternion:pe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=de.Zero(),n=this.definedFacingForward?-1:1;return de.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,s,r),r}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new de(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=an(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new rn(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=r?this.getVerticesData(ys.MatricesIndicesExtraKind):null,o=r?this.getVerticesData(ys.MatricesWeightsExtraKind):null,a=this.skeleton.getTransformMatrices(this),l=ge.Vector3[0],h=ge.Matrix[0],c=ge.Matrix[1];let u=0;for(let d=0;d0&&(fe.FromFloat32ArrayToRefScaled(a,Math.floor(16*e[u+_]),p,c),h.addToSelf(c));if(r)for(_=0;_<4;_++)p=o[u+_],p>0&&(fe.FromFloat32ArrayToRefScaled(a,Math.floor(16*n[u+_]),p,c),h.addToSelf(c));s===ys.NormalKind?de.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):de.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),s===ys.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,ys.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,ys.PositionKind)}_getPositionData(e,t){let i=this.getVerticesData(ys.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let r=i;r1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=ge.Matrix[0],i=ge.Matrix[1];return fe.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const o=new Ss,a=this.getClassName(),l="InstancedLinesMesh"===a||"LinesMesh"===a||"GreasedLineMesh"===a?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return o;if(!(n||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:de.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let _=!1;for(let e=0;e1&&!n&&!r.canIntersects(e))continue;const o=r.intersects(e,this._positions,this.getIndices(),t,i);if(o&&(t||!c||o.distancee!==this&&e.actionManager===this.actionManager))||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:de.Zero()}e.depthSortedFacets=[];for(let t=0;tK?r.maximum.x-r.minimum.x:K,e.bbSize.y=r.maximum.y-r.minimum.y>K?r.maximum.y-r.minimum.y:K,e.bbSize.z=r.maximum.z-r.minimum.z>K?r.maximum.z-r.minimum.z:K;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),de.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&cn.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;sr.subDiv.max||o<0||o>r.subDiv.max||a<0||a>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),a=ge.Matrix[5];o.invertToRef(a);const l=ge.Vector3[8];de.TransformCoordinatesFromFloatsToRef(e,t,i,a,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,s,r,n);return s&&de.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),h}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0;const f=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,x,b,T=Number.MAX_VALUE,y=T;for(let S=0;S=0||r&&!n&&c<=0)&&(c=x.x*b.x+x.y*b.y+x.z*b.z,u=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*u,_=t+x.y*u,p=i+x.z*u,a=d-e,l=_-t,h=p-i,y=a*a+l*l+h*h,ye.emitter===this))}}Sn.OCCLUSION_TYPE_NONE=0,Sn.OCCLUSION_TYPE_OPTIMISTIC=1,Sn.OCCLUSION_TYPE_STRICT=2,Sn.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Sn.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Sn.CULLINGSTRATEGY_STANDARD=0,Sn.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Sn.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Sn.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,ee("BABYLON.AbstractMesh",Sn);class Cn{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){yt.Clone((()=>e),this)}serialize(){return yt.Serialize(this)}parse(e,t,i){yt.Parse((()=>this),e,t,i)}}var En;function An(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function Pn(e,t,i){const s=!!(e.clipPlane??t.clipPlane),r=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),a=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);s&&i.push("#define CLIPPLANE"),r&&i.push("#define CLIPPLANE2"),n&&i.push("#define CLIPPLANE3"),o&&i.push("#define CLIPPLANE4"),a&&i.push("#define CLIPPLANE5"),l&&i.push("#define CLIPPLANE6")}function Rn(e,t,i){let s=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),o=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,s=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,s=!0),i.CLIPPLANE3!==o&&(i.CLIPPLANE3=o,s=!0),i.CLIPPLANE4!==a&&(i.CLIPPLANE4=a,s=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,s=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,s=!0),s}function In(e,t,i){let s=t.clipPlane??i.clipPlane;Mn(e,"vClipPlane",s),s=t.clipPlane2??i.clipPlane2,Mn(e,"vClipPlane2",s),s=t.clipPlane3??i.clipPlane3,Mn(e,"vClipPlane3",s),s=t.clipPlane4??i.clipPlane4,Mn(e,"vClipPlane4",s),s=t.clipPlane5??i.clipPlane5,Mn(e,"vClipPlane5",s),s=t.clipPlane6??i.clipPlane6,Mn(e,"vClipPlane6",s)}function Mn(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}qe([st()],Cn.prototype,"func",null),qe([st()],Cn.prototype,"funcRef",null),qe([st()],Cn.prototype,"funcMask",null),qe([st()],Cn.prototype,"opStencilFail",null),qe([st()],Cn.prototype,"opDepthFail",null),qe([st()],Cn.prototype,"opStencilDepthPass",null),qe([st()],Cn.prototype,"mask",null),qe([st()],Cn.prototype,"enabled",null),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(En||(En={}));const On=Ce.Black(),Dn={NUM_MORPH_INFLUENCERS:0};function wn(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;1===e.mode&&we.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function Nn(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(On,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",On)):i.setColor3("vFogColor",e.fogColor))}function Fn(e,t,i){Dn.NUM_MORPH_INFLUENCERS=i,Bn(e,t,Dn)}function Bn(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&se.LastCreatedEngine){const r=se.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const o=n&&n.supportsNormals&&i.NORMAL,a=n&&n.supportsTangents&&i.TANGENT,l=n&&n.supportsUVs&&i.UV1;for(let i=0;ir&&we.Error("Cannot add more vertex attributes for mesh "+t.name)}}function Ln(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function kn(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function Vn(e,t){t.bindToEffect(e,"Scene")}function Un(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function Gn(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function zn(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function Wn(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=n,i.previousBones[e.uniqueId].set(s)))}}}function Hn(e,t,i){e.transferToEffect(t,i+"")}function Xn(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}function Yn(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let r=0;r0&&(s.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}function jn(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&Ln(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}function Kn(e,t,i=4,s=0){let r=0;for(let n=0;n0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}function $n(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}function qn(e,t,i,s,r,n,o,a=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=s,o.FOG=r&&$n(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=a)}function Zn(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(Jn(e,t,n,o,i,s,a),o++,o===r)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e0&&(o.shadowEnabled=!0,t.prepareDefines(r,s))}}i.lightmapMode!=nr.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==nr.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}function eo(e,t,i,s,r,n=null,o=!1){let a=lo(e,s);!1!==n&&(a=Rn(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,a=!0),s.INSTANCES!==r&&(s.INSTANCES=r,a=!0),s.THIN_INSTANCES!==o&&(s.THIN_INSTANCES=o,a=!0),a&&s.markAsUnprocessed()}function to(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function io(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function so(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function ro(e,t,i,s,r=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&to(e,t),r&&io(e,t),o&&so(e,t),!0}function no(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function oo(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,s===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function ao(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||se.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||hs.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Fi(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=uo.ClockWiseSideOrientation:this.sideOrientation=uo.CounterClockWiseSideOrientation,this._uniformBuffer=new bs(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),uo.OnEventObservable.notifyObservers(this,En.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===uo.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===uo.MATERIAL_OPAQUE||this._transparencyMode===uo.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(uo.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===uo.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(En.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,Vn(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(En.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(En.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(En.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),uo._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new ir(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new ln(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,n&&s&&s(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);r.clipPlane&&(n.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(uo._DirtyCallbackArray.length=0,e&uo.TextureDirtyFlag&&uo._DirtyCallbackArray.push(uo._TextureDirtyCallBack),e&uo.LightDirtyFlag&&uo._DirtyCallbackArray.push(uo._LightsDirtyCallBack),e&uo.FresnelDirtyFlag&&uo._DirtyCallbackArray.push(uo._FresnelDirtyCallBack),e&uo.AttributesDirtyFlag&&uo._DirtyCallbackArray.push(uo._AttributeDirtyCallBack),e&uo.MiscDirtyFlag&&uo._DirtyCallbackArray.push(uo._MiscDirtyCallBack),e&uo.PrePassDirtyFlag&&uo._DirtyCallbackArray.push(uo._PrePassDirtyCallBack),uo._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(uo._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(uo._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(uo._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(uo._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(uo._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(uo._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(uo._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(uo._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(uo._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(uo._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(uo._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==ar.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(En.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=yt.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return we.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=hs.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let o=t.pluginManager?.getPlugin(n.name);if(!o){const e=hs.Instantiate("BABYLON."+r);e&&(o=new e(t))}o?.parse(n,i,s)}}}uo.TriangleFillMode=0,uo.WireFrameFillMode=1,uo.PointFillMode=2,uo.PointListDrawMode=3,uo.LineListDrawMode=4,uo.LineLoopDrawMode=5,uo.LineStripDrawMode=6,uo.TriangleStripDrawMode=7,uo.TriangleFanDrawMode=8,uo.ClockWiseSideOrientation=0,uo.CounterClockWiseSideOrientation=1,uo.TextureDirtyFlag=1,uo.LightDirtyFlag=2,uo.FresnelDirtyFlag=4,uo.AttributesDirtyFlag=8,uo.MiscDirtyFlag=16,uo.PrePassDirtyFlag=32,uo.AllDirtyFlag=63,uo.MATERIAL_OPAQUE=0,uo.MATERIAL_ALPHATEST=1,uo.MATERIAL_ALPHABLEND=2,uo.MATERIAL_ALPHATESTANDBLEND=3,uo.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,uo.MATERIAL_NORMALBLENDMETHOD_RNM=1,uo.OnEventObservable=new X,uo._AllDirtyCallBack=e=>e.markAllAsDirty(),uo._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),uo._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),uo._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),uo._MiscDirtyCallBack=e=>e.markAsMiscDirty(),uo._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),uo._LightsDirtyCallBack=e=>e.markAsLightDirty(),uo._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),uo._FresnelAndMiscDirtyCallBack=e=>{uo._FresnelDirtyCallBack(e),uo._MiscDirtyCallBack(e)},uo._TextureAndMiscDirtyCallBack=e=>{uo._TextureDirtyCallBack(e),uo._MiscDirtyCallBack(e)},uo._DirtyCallbackArray=[],uo._RunDirtyCallBacks=e=>{for(const t of uo._DirtyCallbackArray)t(e)},qe([st()],uo.prototype,"id",void 0),qe([st()],uo.prototype,"uniqueId",void 0),qe([st()],uo.prototype,"name",void 0),qe([st()],uo.prototype,"metadata",void 0),qe([st()],uo.prototype,"checkReadyOnEveryCall",void 0),qe([st()],uo.prototype,"checkReadyOnlyOnce",void 0),qe([st()],uo.prototype,"state",void 0),qe([st("alpha")],uo.prototype,"_alpha",void 0),qe([st("backFaceCulling")],uo.prototype,"_backFaceCulling",void 0),qe([st("cullBackFaces")],uo.prototype,"_cullBackFaces",void 0),qe([st()],uo.prototype,"sideOrientation",void 0),qe([st("alphaMode")],uo.prototype,"_alphaMode",void 0),qe([st()],uo.prototype,"_needDepthPrePass",void 0),qe([st()],uo.prototype,"disableDepthWrite",void 0),qe([st()],uo.prototype,"disableColorWrite",void 0),qe([st()],uo.prototype,"forceDepthWrite",void 0),qe([st()],uo.prototype,"depthFunction",void 0),qe([st()],uo.prototype,"separateCullingPass",void 0),qe([st("fogEnabled")],uo.prototype,"_fogEnabled",void 0),qe([st()],uo.prototype,"pointSize",void 0),qe([st()],uo.prototype,"zOffset",void 0),qe([st()],uo.prototype,"zOffsetUnits",void 0),qe([st()],uo.prototype,"pointsCloud",null),qe([st()],uo.prototype,"fillMode",null),qe([st()],uo.prototype,"useLogarithmicDepth",null),qe([st()],uo.prototype,"transparencyMode",null);class _o extends uo{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new _o(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,bt&&bt.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}ee("BABYLON.MultiMaterial",_o);class po{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class fo{}class mo{constructor(){this.visibleInstances={},this.batchCache=new go,this.batchCacheReplacementModeInFrozenMode=new go,this.instancesBufferSize=2048}}class go{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class vo{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class xo{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class bo extends Sn{static _GetDefaultSideOrientation(e){return e||bo.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(ys.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(ys.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new X),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new X),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new X),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new X),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new X),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new xo,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new mo,this._thinInstanceDataStorage=new vo,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=bo.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),Xe.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,bt&&bt.HasTags(s)&&bt.AddTagsTo(this,bt.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const t=s.getDescendants(!0);for(let i=0;i{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new X(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return we.Warn("You cannot use a mesh as LOD level twice"),this;const i=new po(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;io*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const o=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new ln(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)ln.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new cn;s.set(t,e);const r=this.getScene();new _n(_n.RandomId(),r,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=_n.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(ys.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(ys.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(ys.NormalKind);if(!t)return this;cn.ComputeNormals(i,e,t),this.updateVerticesData(ys.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(_n.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new _n(_n.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new cn;t.indices=e;const s=this.getScene();new _n(_n.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case uo.PointFillMode:n=null;break;case uo.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case uo.TriangleFillMode:n=this._geometry.getIndexBuffer()}return s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==uo.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==uo.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),o=s?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&o&&(n.visibleInstances[e]=t[o])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],o=n?n.length:0,a=this._instanceDataStorage,l=a.instancesBufferSize;let h=a.instancesBuffer,c=a.instancesPreviousBuffer;const u=16*(o+1)*4;for(;a.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const o=s.getEngine();let a=0,l=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(a=s.activeCamera.maxZ,l=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let _;t&&o.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),_=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const p=_?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,n,p);if(!_||!p)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;const f=i||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=f._getWorldMatrixDeterminant();m=this.overrideMaterialSideOrientation,null==m&&(m=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(m=m===uo.ClockWiseSideOrientation?uo.CounterClockWiseSideOrientation:uo.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(_,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&o.setDepthWrite(!0);const v=this._internalMeshDataInfo._effectiveMaterial,x=v.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,p,x,!1);const b=f.getWorldMatrix();v._storeEffectOnSubMeshes?v.bindForSubMesh(b,this,e):v.bind(b,this),!v.backFaceCulling&&v.separateCullingPass&&(o.setState(!0,v.zOffset,!1,!g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),o.setState(!0,v.zOffset,!1,g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,n,p);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=a,s.updateTransformMatrix(!0)),s.performancePriority!==ar.Aggressive||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(ys.MatricesWeightsKind)&&(this.isVerticesDataPresent(ys.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(ys.MatricesWeightsKind),t=e.length;for(let i=0;ii&&s++,0!==n&&u++,c+=n,i=n}if(l[u]++,u>n&&(n=u),0===c)r++;else{const i=1/c;let s=0;for(let r=0;r.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(ys.MatricesIndicesKind),u=this.getVerticesData(ys.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===r&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return hs.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(ys.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(ys.PositionKind);const s=de.Zero();let r;for(r=0;r{const a=e.width,l=e.height,h=this.getEngine().createCanvas(a,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,a,l).data;this.applyDisplacementMapFromBuffer(c,a,l,t,i,r,n,o),s&&s(this)}),a||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,a=!1){if(!this.isVerticesDataPresent(ys.PositionKind)||!this.isVerticesDataPresent(ys.NormalKind)||!this.isVerticesDataPresent(ys.UVKind))return we.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(ys.PositionKind,!0,!0),h=this.getVerticesData(ys.NormalKind),c=this.getVerticesData(ys.UVKind);let u=de.Zero();const d=de.Zero(),_=ue.Zero();n=n||ue.Zero(),o=o||new ue(1,1);for(let a=0;a{const s=new Float32Array(i.length*t);let r=0;for(let n=0;n{const t=s.length-1-e,i=s[t];for(let e=0;e{for(let e=0;e-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=a?this.getVerticesData(ys.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(ys.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=de.Zero(),d=new fe,_=new fe;let p,f=0;for(let e=0;e0&&(fe.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[f+p]),m,_),d.addToSelf(_));if(a)for(p=0;p<4;p++)m=h[f+p],m>0&&(fe.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[f+p]),m,_),d.addToSelf(_));de.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(s,e),t&&(de.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(ys.PositionKind,s),t&&this.updateVerticesData(ys.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:de.Zero(),max:de.Zero()}}static Center(e){const t=e instanceof Array?bo.MinMax(e):e;return de.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return Hr(bo._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return Xr(bo._MergeMeshesCoroutine(e,t,i,s,r,n,!0),zr())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a=65536)return we.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const l=new Array,h=new Array,c=new Array,u=e[0].overrideMaterialSideOrientation;for(a=0;a{const t=e.computeWorldMatrix(!0);return{vertexData:cn.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:p,transform:f}=_(d);o&&(yield);const m=new Array(e.length-1);for(let t=1;t{throw vt("GroundMesh")},bo._GoldbergMeshParser=(e,t)=>{throw vt("GoldbergMesh")},bo._LinesMeshParser=(e,t)=>{throw vt("LinesMesh")},bo._GreasedLineMeshParser=(e,t)=>{throw vt("GreasedLineMesh")},bo._GreasedLineRibbonMeshParser=(e,t)=>{throw vt("GreasedLineRibbonMesh")},bo._TrailMeshParser=(e,t)=>{throw vt("TrailMesh")},ee("BABYLON.Mesh",bo),bo._instancedMeshFactory=(e,t)=>{const i=new To(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class To extends Sn{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&hs.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&hs.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&hs.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&hs.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&we.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||we.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==xn.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new fe);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,ge.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(ge.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=yo.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=yt.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=yt.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((t=>{e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((t=>{e.includedOnlyMeshesIds.push(t.id)}))),yt.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return Ct.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=yo.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=yt.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._resyncMeshes(),r},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===yo.INTENSITYMODE_AUTOMATIC&&(i=t===yo.LIGHTTYPEID_DIRECTIONALLIGHT?yo.INTENSITYMODE_ILLUMINANCE:yo.INTENSITYMODE_LUMINOUSINTENSITY),t){case yo.LIGHTTYPEID_POINTLIGHT:case yo.LIGHTTYPEID_SPOTLIGHT:switch(i){case yo.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case yo.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case yo.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case yo.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case yo.INTENSITYMODE_ILLUMINANCE:e=1;break;case yo.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case yo.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}yo.FALLOFF_DEFAULT=nr.FALLOFF_DEFAULT,yo.FALLOFF_PHYSICAL=nr.FALLOFF_PHYSICAL,yo.FALLOFF_GLTF=nr.FALLOFF_GLTF,yo.FALLOFF_STANDARD=nr.FALLOFF_STANDARD,yo.LIGHTMAP_DEFAULT=nr.LIGHTMAP_DEFAULT,yo.LIGHTMAP_SPECULAR=nr.LIGHTMAP_SPECULAR,yo.LIGHTMAP_SHADOWSONLY=nr.LIGHTMAP_SHADOWSONLY,yo.INTENSITYMODE_AUTOMATIC=nr.INTENSITYMODE_AUTOMATIC,yo.INTENSITYMODE_LUMINOUSPOWER=nr.INTENSITYMODE_LUMINOUSPOWER,yo.INTENSITYMODE_LUMINOUSINTENSITY=nr.INTENSITYMODE_LUMINOUSINTENSITY,yo.INTENSITYMODE_ILLUMINANCE=nr.INTENSITYMODE_ILLUMINANCE,yo.INTENSITYMODE_LUMINANCE=nr.INTENSITYMODE_LUMINANCE,yo.LIGHTTYPEID_POINTLIGHT=nr.LIGHTTYPEID_POINTLIGHT,yo.LIGHTTYPEID_DIRECTIONALLIGHT=nr.LIGHTTYPEID_DIRECTIONALLIGHT,yo.LIGHTTYPEID_SPOTLIGHT=nr.LIGHTTYPEID_SPOTLIGHT,yo.LIGHTTYPEID_HEMISPHERICLIGHT=nr.LIGHTTYPEID_HEMISPHERICLIGHT,qe([nt()],yo.prototype,"diffuse",void 0),qe([nt()],yo.prototype,"specular",void 0),qe([st()],yo.prototype,"falloffType",void 0),qe([st()],yo.prototype,"intensity",void 0),qe([st()],yo.prototype,"range",null),qe([st()],yo.prototype,"intensityMode",null),qe([st()],yo.prototype,"radius",null),qe([st()],yo.prototype,"_renderPriority",void 0),qe([it("_reorderLightsInScene")],yo.prototype,"renderPriority",void 0),qe([st("shadowEnabled")],yo.prototype,"_shadowEnabled",void 0),qe([st("excludeWithLayerMask")],yo.prototype,"_excludeWithLayerMask",void 0),qe([st("includeOnlyWithLayerMask")],yo.prototype,"_includeOnlyWithLayerMask",void 0),qe([st("lightmapMode")],yo.prototype,"_lightmapMode",void 0);class So extends G{}class Co{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach((e=>{e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0}}class Eo extends G{constructor(e){super(),this._wasAddedToScene=!1,(e=e||se.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,r=i.dependsOn.get(e);if(s instanceof To){const n=s.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const r of s.getDescendants()){const s=r.uniqueId;t.has(s)&&(n.add(s),i.dependsOn.get(s).add(e))}}const s=[],r=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(r.push(s),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();s.push(e);const r=i.dependedBy.get(e.uniqueId);for(const s of Array.from(r.values())){const r=i.dependsOn.get(s);r.delete(e.uniqueId),0===r.size&&t.get(s)&&(n.push(t.get(s)),t.delete(s))}}return t.size>0&&(we.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>we.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof Sn&&-1!==this.meshes.indexOf(e)||e instanceof xn&&-1!==this.transformNodes.indexOf(e)||e instanceof yo&&-1!==this.lights.indexOf(e)||e instanceof Kr&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return we.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return we.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return we.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return we.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||hs.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new Co,o=[],a=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,o)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof bo){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&r[s[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[s[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===o.parent&&n.rootNodes.push(o)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=s[i.uniqueId],o=("number"==typeof n?r[n]:i).createInstance(t.name);d(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[s[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[s[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||hs.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach((i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))})),this.lights.forEach((i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))})),this.meshes.forEach((i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||hs.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const s of e){let e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new So);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new bo("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=se.LastCreatedScene,t,i=null){if(!e)return we.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof bo?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof xn?this.transformNodes.push(e):e instanceof yo?this.lights.push(e):e instanceof Kr&&this.cameras.push(e),e instanceof Sn){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class Ao{constructor(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},(e=e||se.LastCreatedScene)&&(this._scene=e,gn.audioEngine?(this._audioEngine=gn.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))):hs.Warn("No audio engine initialized, failed to create an audio analyser"))}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;tnew Po(e,t,i);class Po{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new X,this.onAudioLockedObservable=new X,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!Lt())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContext(){return this._audioContext?.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,we.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)})).catch((()=>{this._tryToRun=!1,this.unlocked=!1})))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const e=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this.unlock()}),!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class Ro{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if(gn.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:gn.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,s=null,r){if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new X,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=de.Zero(),this._localDirection=new de(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,i=i||se.LastCreatedScene)if(this._scene=i,Ro._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(e,t,i,s,r)=>t0&&(s=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&we.Error("XHR "+e.status+" error on: "+t+"."),we.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?s||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):we.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){we.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),gn.audioEngine&&!gn.audioEngine.WarnedWebAudioUnsupported&&(we.Error("Web Audio is not supported by your browser."),gn.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){gn.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){gn.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){gn.audioEngine?.audioContext&&gn.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{we.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){gn.audioEngine?.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){gn.audioEngine?.canUseWebAudio&&gn.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??gn.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){gn.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){gn.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(gn.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{gn.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=gn.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=gn.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const r=()=>{if(gn.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=gn.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},s=e?gn.audioEngine?.audioContext.currentTime+e:gn.audioEngine.audioContext.currentTime;const r=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(s,r,this.loop?void 0:i)}}};"suspended"===gn.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===gn.audioEngine?.audioContext.state?(gn.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=gn.audioEngine.onAudioUnlockedObservable.addOnce((()=>{r()})))):r()}),500):r()}this._startTime=s,this.isPlaying=!0,this.isPaused=!1}catch(e){we.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(gn.audioEngine?.audioContext&&this._soundSource){const t=e?gn.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):gn.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=gn.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){gn.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&gn.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(gn.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,gn.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,gn.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);gn.audioEngine?.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Ro(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,s){const r=e.name;let n;n=e.url?i+e.url:i+r;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let a;if(s){const e=()=>{s._isReadyToPlay?(a._audioBuffer=s.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(e,300)};a=new Ro(r,new ArrayBuffer(0),t,null,o),e()}else a=new Ro(r,n,t,(()=>{t.removePendingData(a)}),o),t.addPendingData(a);if(e.position){const t=de.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=de.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(gn.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Ro._SceneComponentInitialization=e=>{throw vt("AudioSceneComponent")};class Io{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||se.LastCreatedScene)&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){gn.audioEngine?.canUseWebAudio&&gn.audioEngine.audioContext&&(this._outputAudioNode=gn.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(gn.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(gn.audioEngine&&gn.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){this._isInitialized||this._initializeSoundTrackAudioGraph(),gn.audioEngine?.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){gn.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){if(gn.audioEngine?.canUseWebAudio)for(let e=0;e{let r,n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,a=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),de.TransformNormalToRef(Mo._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(Rs.NAME_AUDIO);t||(t=new Mo(e),e._addComponent(t))};class Oo{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let s=0;for(const e of i)s+=e;const r=s>0?1/s:0;for(let e=0;e{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee),this)}serialize(){return yt.Serialize(this)}parse(e,t,i){yt.Parse((()=>this),e,t,i)}}qe([rt(),it("_markSubMeshesAsAttributesDirty")],Do.prototype,"texture",void 0),qe([st(),it("_markSubMeshesAsAttributesDirty")],Do.prototype,"isEnabled",void 0),qe([st()],Do.prototype,"animationParameters",void 0),qe([st()],Do.prototype,"time",void 0);class wo{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return!!this._texture&&this._texture.isCube}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Et.Zero(),this._cachedBaseSize=Et.Zero(),this._initialSamplingMode=2,this._texture=wo._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class No extends wo{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=ns()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=No.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new X,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?No._IsScene(e)?this._scene=e:this._engine=e:this._scene=se.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return fe.IdentityReadOnly}getReflectionTextureMatrix(){return fe.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!r,t),l=o.getLoadedTexturesCache();for(let o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=yt.Serialize(this);return yt.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Fo(e,t,i=!1){const s=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const n=document.createElement("canvas");n.width=s,n.height=r;const o=n.getContext("2d");if(!o)return null;const a=o.createImageData(s,r);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function Bo(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?Fo(r,e.getSize(),s.invertY):null}async function Lo(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?Fo(r,e.getSize(),s.invertY):null}No.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,qe([st()],No.prototype,"uniqueId",void 0),qe([st()],No.prototype,"name",void 0),qe([st()],No.prototype,"metadata",void 0),qe([st("hasAlpha")],No.prototype,"_hasAlpha",void 0),qe([st("getAlphaFromRGB")],No.prototype,"_getAlphaFromRGB",void 0),qe([st()],No.prototype,"level",void 0),qe([st("coordinatesIndex")],No.prototype,"_coordinatesIndex",void 0),qe([st()],No.prototype,"optimizeUVAllocation",void 0),qe([st("coordinatesMode")],No.prototype,"_coordinatesMode",void 0),qe([st()],No.prototype,"wrapU",null),qe([st()],No.prototype,"wrapV",null),qe([st()],No.prototype,"wrapR",void 0),qe([st()],No.prototype,"anisotropicFilteringLevel",void 0),qe([st()],No.prototype,"isCube",null),qe([st()],No.prototype,"is3D",null),qe([st()],No.prototype,"is2DArray",null),qe([st()],No.prototype,"gammaSpace",null),qe([st()],No.prototype,"invertZ",void 0),qe([st()],No.prototype,"lodLevelInAlpha",void 0),qe([st()],No.prototype,"lodGenerationOffset",null),qe([st()],No.prototype,"lodGenerationScale",null),qe([st()],No.prototype,"linearSpecularLOD",null),qe([rt()],No.prototype,"irradianceTexture",null),qe([st()],No.prototype,"isRenderTarget",void 0);const ko={GenerateBase64StringFromPixelData:Fo,GenerateBase64StringFromTexture:Bo,GenerateBase64StringFromTextureAsync:Lo};class Vo extends No{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=Vo.TRILINEAR_SAMPLINGMODE,o={},a,l=5){throw vt("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,r=Vo.TRILINEAR_SAMPLINGMODE,n=null,o=null,a=null,l=!1,h,c,u,d,_){let p;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new X,this._isBlocking=!0,this.name=e||"",this.url=e;let f=!1,m=null,g=!0;"object"==typeof i&&null!==i?(p=i.noMipmap??!1,s=i.invertY??!dn.UseOpenGLOrientationForUV,r=i.samplingMode??Vo.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,o=i.onError??null,a=i.buffer??null,l=i.deleteBuffer??!1,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,f=i.useSRGBBuffer??!1,m=i.internalTexture??null,g=i.gammaSpace??g):p=!!i,this._gammaSpace=g,this._noMipmap=p,this._invertY=void 0===s?!dn.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=a,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=f,this._forcedExtension=_,h&&(this._format=h);const v=this.getScene(),x=this._getEngine();if(!x)return;x.onBeforeTextureInitObservable.notifyObservers(this);const b=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&v&&v.resetCachedMaterial()},T=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},o&&o(e,t),Vo.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m)return this._delayedOnLoad=b,void(this._delayedOnError=T);if(this._texture=m??this._getFromCache(this.url,p,r,this._invertY,f,this.isCube),this._texture)if(this._texture.isReady)Vi.SetImmediate((()=>b()));else{const e=this._texture.onLoadedObservable.add(b);this._texture.onErrorObservable.add((t=>{T(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(v&&v.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=b,this._delayedOnError=T;else{try{this._texture=x.createTexture(this.url,p,this._invertY,v,r,b,T,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,f)}catch(e){throw T("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Vi.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,de.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=fe.Zero(),this._rowGenerationMatrix=new fe,this._t0=de.Zero(),this._t1=de.Zero(),this._t2=de.Zero()),fe.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(fe.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,ge.Matrix[0]),fe.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,ge.Matrix[1]),fe.ScalingToRef(this._cachedUScale,this._cachedVScale,0,ge.Matrix[2]),fe.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,ge.Matrix[3]),ge.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ge.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ge.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ge.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),fe.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==Vo.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=fe.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=fe.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case Vo.PLANAR_MODE:fe.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case Vo.PROJECTION_MODE:{fe.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:fe.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return yt.Clone((()=>new Vo(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;Vo.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(Vo._SerializeInternalTextureUniqueId);return t?((Vo.SerializeBuffers||Vo.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+qt(this._buffer):(Vo.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Bo(this):Lo(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,Vo._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=rs.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return Vo._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=Vo._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=ir.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(o)}),e._creationFlags??0,e._useSRGBBuffer??!1),o.name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||Vo.UseSerializedUrlIfAny)&&(a=e.url);const l={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(o)},internalTexture:r};o=new Vo(a,t,l)}return o}}),e,t);return o}static CreateFromBase64String(e,t,i,s,r,n=Vo.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h,c){return new Vo("data:"+t,i,s,r,n,o,a,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=Vo.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Vo(e,i,r,n,o,a,l,t,s,h,void 0,void 0,c,u)}}function Uo(e,t,i,s){let r,n=1;1===s?r=new Float32Array(t*i*4):2===s?(r=new Uint16Array(t*i*4),n=15360):r=7===s?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let s=0;s{throw vt("CubeTexture")},Vo._CreateMirror=(e,t,i,s)=>{throw vt("MirrorTexture")},Vo._CreateRenderTargetTexture=(e,t,i,s,r)=>{throw vt("RenderTargetTexture")},Vo.NEAREST_SAMPLINGMODE=1,Vo.NEAREST_NEAREST_MIPLINEAR=8,Vo.BILINEAR_SAMPLINGMODE=2,Vo.LINEAR_LINEAR_MIPNEAREST=11,Vo.TRILINEAR_SAMPLINGMODE=3,Vo.LINEAR_LINEAR_MIPLINEAR=3,Vo.NEAREST_NEAREST_MIPNEAREST=4,Vo.NEAREST_LINEAR_MIPNEAREST=5,Vo.NEAREST_LINEAR_MIPLINEAR=6,Vo.NEAREST_LINEAR=7,Vo.NEAREST_NEAREST=1,Vo.LINEAR_NEAREST_MIPNEAREST=9,Vo.LINEAR_NEAREST_MIPLINEAR=10,Vo.LINEAR_LINEAR=2,Vo.LINEAR_NEAREST=12,Vo.EXPLICIT_MODE=0,Vo.SPHERICAL_MODE=1,Vo.PLANAR_MODE=2,Vo.CUBIC_MODE=3,Vo.PROJECTION_MODE=4,Vo.SKYBOX_MODE=5,Vo.INVCUBIC_MODE=6,Vo.EQUIRECTANGULAR_MODE=7,Vo.FIXED_EQUIRECTANGULAR_MODE=8,Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Vo.CLAMP_ADDRESSMODE=0,Vo.WRAP_ADDRESSMODE=1,Vo.MIRROR_ADDRESSMODE=2,Vo.UseSerializedUrlIfAny=!1,qe([st()],Vo.prototype,"url",void 0),qe([st()],Vo.prototype,"uOffset",void 0),qe([st()],Vo.prototype,"vOffset",void 0),qe([st()],Vo.prototype,"uScale",void 0),qe([st()],Vo.prototype,"vScale",void 0),qe([st()],Vo.prototype,"uAng",void 0),qe([st()],Vo.prototype,"vAng",void 0),qe([st()],Vo.prototype,"wAng",void 0),qe([st()],Vo.prototype,"uRotationCenter",void 0),qe([st()],Vo.prototype,"vRotationCenter",void 0),qe([st()],Vo.prototype,"wRotationCenter",void 0),qe([st()],Vo.prototype,"homogeneousRotationInUVTransform",void 0),qe([st()],Vo.prototype,"isBlocking",null),ee("BABYLON.Texture",Vo),yt._TextureParser=Vo.Parse,ki.prototype.updateRawTexture=function(e,t,i,s,r=null,n=0,o=!1){if(!e)return;const a=this._getRGBABufferInternalSizedFormat(n,i,o),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=s,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},ki.prototype.createRawTexture=function(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new Pi(this,Ai.Raw);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(o,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},ki.prototype.createRawCubeTexture=function(e,t,i,s,r,n,o,a=null){const l=this._gl,h=new Pi(this,Ai.CubeRaw);h.isCube=!0,h.format=i,h.type=s,this._doNotHandleContextLost||(h._bufferViewArray=e);const c=this._getWebGLTextureType(s);let u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,we.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,we.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,o=1,we.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,o=1,we.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const d=t,_=d;if(h.width=d,h.height=_,h.invertY=n,h._compression=a,!this.needPOTTextures||as(h.width)&&as(h.height)||(r=!1),e)this.updateRawCubeTexture(h,e,i,s,n,a);else{const e=this._getRGBABufferInternalSizedFormat(s),t=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let i=0;i<6;i++)a?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[a],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const p=this._getSamplingParameters(o,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=r,h.samplingMode=o,h.isReady=!0,h},ki.prototype.updateRawCubeTexture=function(e,t,i,s,r,n=null,o=0){e._bufferViewArray=t,e.format=i,e.type=s,e.invertY=r,e._compression=n;const a=this._gl,l=this._getWebGLTextureType(s);let h=this._getInternalFormat(i);const c=this._getRGBABufferInternalSizedFormat(s);let u=!1;h===a.RGB&&(h=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let r=t[i];n?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,this.getCaps().s3tc[n],e.width,e.height,0,r):(u&&(r=Uo(r,e.width,e.height,s)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,c,e.width,e.height,0,h,l,r))}(!this.needPOTTextures||as(e.width)&&as(e.height))&&e.generateMipMaps&&0===o&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},ki.prototype.createRawCubeTextureFromUrl=function(e,t,i,s,r,n,o,a,l=null,h=null,c=3,u=!1){const d=this._gl,_=this.createRawCubeTexture(null,i,s,r,!n,u,c,null);t?.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_);const p=e=>{const i=_.width,n=o(e);if(n){if(a){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(s);const o=this._getRGBABufferInternalSizedFormat(r);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const h=a(n);for(let s=0;s>s;for(let i=0;i<6;i++){let a=h[s][i];l&&(a=Uo(a,n,n,r)),d.texImage2D(i,s,o,n,n,0,t,e,a)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(_,n,s,r,u);_.isReady=!0,t?.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{p(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(_),h&&e&&h(e.status+" "+e.statusText,i)})),_},ki.prototype.createRawTexture2DArray=Go(!1),ki.prototype.createRawTexture3D=Go(!0),ki.prototype.updateRawTexture2DArray=zo(!1),ki.prototype.updateRawTexture3D=zo(!0);class Wo extends Vo{constructor(e,t,i,s,r,n=!0,o=!1,a=3,l=0,h,c){super(null,r,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=s,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,s,n,o,a,null,l,h??0,c??!1),this.wrapU=Vo.CLAMP_ADDRESSMODE,this.wrapV=Vo.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,s,r=!0,n=!1,o=3){return new Wo(e,t,i,1,s,r,n,o)}static CreateLuminanceAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Wo(e,t,i,2,s,r,n,o)}static CreateAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Wo(e,t,i,0,s,r,n,o)}static CreateRGBTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new Wo(e,t,i,4,s,r,n,o,a,l,h)}static CreateRGBATexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new Wo(e,t,i,5,s,r,n,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=!1){return new Wo(e,t,i,5,s,r,n,o,a,1,l)}static CreateRTexture(e,t,i,s,r=!0,n=!1,o=Vo.TRILINEAR_SAMPLINGMODE,a=1){return new Wo(e,t,i,6,s,r,n,o,a)}static CreateRStorageTexture(e,t,i,s,r=!0,n=!1,o=Vo.TRILINEAR_SAMPLINGMODE,a=1){return new Wo(e,t,i,6,s,r,n,o,a,1)}}class Ho{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=fe.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new X,this.bones=[],this._scene=i||se.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,ge.Matrix[1]),e._updateAbsoluteBindMatrices(ge.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=Wo.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=Wo.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new Ho(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=de.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s-1&&(n=i.bones[t.parentBoneIndex]);const o=t.rest?fe.FromArray(t.rest):null,a=new pr(t.name,i,n,fe.FromArray(t.matrix),o,null,r);void 0!==t.id&&null!==t.id&&(a.id=t.id),t.length&&(a.length=t.length),t.metadata&&(a.metadata=t.metadata),t.animation&&a.animations.push(Nt.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,a._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class Xo{constructor(e,t){this._scene=e,t instanceof Ho?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}async bakeVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=e.reduce(((e,t)=>e+t.to-t.from+1),0);if(isNaN(i))throw new Error("Invalid animation ranges.");let s=0;const r=new Float32Array(4*(t+1)*4*i);this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest();for(const t of e)for(let e=t.from;e<=t.to;e++)await this._executeAnimationFrame(r,e,s++);return r}async _executeAnimationFrame(e,t,i){return new Promise(((s,r)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,(()=>{const t=this._skeleton.getTransformMatrices(this._mesh);e.set(t,i*t.length),s()}))}))}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=Wo.CreateRGBATexture(e,4*(t+1),e.length/(4*(t+1)*4),this._scene,!1,!1,Vo.NEAREST_NEAREST,1);return i.name="VAT"+this._skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=4*(t+1),s=e.length/(4*(t+1)*4);return{vertexData:qt(e),width:i,height:s}}loadBakedVertexDataFromObject(e){return new Float32Array(Jt(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}class Yo{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Ms.POINTERDOWN?e.type===Ms.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=zt.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??zt.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Qo.EasingFunction.setEasingMode(Qo.EasingMode),this._radiusBounceTransition=Nt.CreateAnimation("radius",Nt.ANIMATIONTYPE_FLOAT,60,Qo.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Nt.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(()=>this._clearAnimationLocks()));t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}Qo.EasingFunction=new Er(.3),Qo.EasingMode=Sr.EASINGMODE_EASEOUT;class jo{constructor(){this.onTargetFramingAnimationEndObservable=new X,this._mode=jo.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();jo.EasingFunction.setEasingMode(jo.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Ms.POINTERDOWN?e.type===Ms.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new de(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===jo.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=zt.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Nt.CreateAnimation("beta",Nt.ANIMATIONTYPE_FLOAT,60,jo.EasingFunction));const e=Nt.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=zt.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}jo.EasingFunction=new Ir,jo.EasingMode=Sr.EASINGMODE_EASEINOUT,jo.IgnoreBoundsSizeMode=0,jo.FitFrustumSidesMode=1;class Ko{constructor(e,t=new de,i=0,s=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=s}}class $o{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new Ko(de.Up()),new Ko(de.Down()),new Ko(de.Left()),new Ko(de.Right()),new Ko(de.Forward()),new Ko(de.Forward().scaleInPlace(-1))],this._tmpMatrix=new fe,this._tmpVector=new de,this._zeroVector=de.Zero(),this._lookAtTmpMatrix=new fe}init(){}_closestFace(e){return this._faceVectors.forEach((t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=pe.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),de.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=de.GetAngleBetweenVectors(t.rotatedDirection,e,de.Cross(t.rotatedDirection,e))})),this._faceVectors.reduce(((e,t)=>e.ignore?t:t.ignore||e.diff{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),de.TransformCoordinatesToRef(de.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach((e=>{i.direction.x&&e.direction.x&&(e.ignore=!0),i.direction.y&&e.direction.y&&(e.ignore=!0),i.direction.z&&e.direction.z&&(e.ignore=!0)}));const s=this._closestFace(this._tmpVector);this._faceVectors.forEach((e=>{e.ignore=!1})),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=pe.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,s.rotatedDirection,this._ui.rotationQuaternion),s.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),s.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),s.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)}))}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}class qo{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time)return this._hoverValue=this._time,void this._detachObserver()}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0))return this._hoverValue=0,void this._detachObserver();this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0)||(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach((e=>{this._setAllVisibility(e,t)}))}_attachObserver(){this._onBeforeRenderObserver||(this._onBeforeRenderObserver=this._ownerNode?.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){this._onBeforeRenderObserver&&(this._ownerNode?.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}class Zo{constructor(e,t,i=Number.MAX_VALUE,s=K){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new Zo(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Zo._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=Zo._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.x)return!1}else if(n=1/this.direction.x,o=(s.x-this.origin.x)*n,a=(r.x-this.origin.x)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(n=1/this.direction.y,o=(s.y-this.origin.y)*n,a=(r.y-this.origin.y)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(n=1/this.direction.z,o=(s.z-this.origin.z)*n,a=(r.z-this.origin.z)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,a=o*o;if(n<=a)return!0;const l=i*this.direction.x+s*this.direction.y+r*this.direction.z;return!(l<0)&&n-l*l<=a}intersectsTriangle(e,t,i){const s=Zo._TmpVector3[0],r=Zo._TmpVector3[1],n=Zo._TmpVector3[2],o=Zo._TmpVector3[3],a=Zo._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),de.CrossToRef(this.direction,r,n);const l=de.Dot(s,n);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,o);const c=de.Dot(o,n)*h;if(c<-this.epsilon||c>1+this.epsilon)return null;de.CrossToRef(o,s,a);const u=de.Dot(this.direction,a)*h;if(u<-this.epsilon||c+u>1+this.epsilon)return null;const d=de.Dot(r,a)*h;return d>this.length?null:new $r(1-c-u,c,d)}intersectsPlane(e){let t;const i=de.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const s=de.Dot(e.normal,this.origin);return t=(-e.d-s)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new de(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new de(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new de(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=ge.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?Zo.TransformToRef(this,o,this._tmpRay):this._tmpRay=Zo.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Vector3[2],a=ge.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(Zo._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,a);const l=de.Dot(r,r),h=de.Dot(r,o),c=de.Dot(o,o),u=de.Dot(r,a),d=de.Dot(o,a),_=l*c-h*h;let p,f,m=_,g=_;_m&&(p=m,f=d+h,g=c)),f<0?(f=0,-u<0?p=0:-u>l?p=m:(p=-u,m=l)):f>g&&(f=g,-u+h<0?p=0:-u+h>l?p=m:(p=-u+h,m=l));const v=Math.abs(p)0&&x<=this.length&&y.lengthSquared()=e.distance?null:h:null},dr.prototype._internalPick=function(e,t,i,s,r){let n=null;const o=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let o=0;o(this._tempPickingRay||(this._tempPickingRay=Zo.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null),this._tempPickingRay)),i,s,!0);return n&&(n.ray=this.createPickingRay(e,t,fe.Identity(),r||null)),n},Object.defineProperty(dr.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),dr.prototype.pick=function(e,t,i,s,r,n,o=!1){const a=this._internalPick(((i,s)=>(this._tempPickingRay||(this._tempPickingRay=Zo.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null,!1,s),this._tempPickingRay)),i,s,!1,n);return a&&(a.ray=this.createPickingRay(e,t,fe.Identity(),r||null)),a},dr.prototype.pickWithRay=function(e,t,i,s){const r=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=fe.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Zo.Zero()),Zo.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,s);return r&&(r.ray=e),r},dr.prototype.multiPick=function(e,t,i,s,r){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,s||null)),i,r)},dr.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=fe.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Zo.Zero()),Zo.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},Kr.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new Zo(de.Zero(),de.Zero(),e),e,t,i)},Kr.prototype.getForwardRayToRef=function(e,t=100,i,s){i||(i=this.getWorldMatrix()),e.length=t,s?e.origin.copyFrom(s):e.origin.copyFrom(this.position);const r=ge.Vector3[2];r.set(0,0,this._scene.useRightHandedSystem?-1:1);const n=ge.Vector3[3];return de.TransformNormalToRef(r,i,n),de.NormalizeToRef(n,e.direction),e};class Jo{static _RemoveAndStorePivotPoint(e){e&&0===Jo._PivotCached&&(e.getPivotPointToRef(Jo._OldPivotPoint),Jo._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,Jo._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(fe.IdentityReadOnly),Jo._OldPivotPoint.subtractToRef(e.getPivotPoint(),Jo._PivotTranslation),Jo._PivotTmpVector.copyFromFloats(1,1,1),Jo._PivotTmpVector.subtractInPlace(e.scaling),Jo._PivotTmpVector.multiplyInPlace(Jo._PivotTranslation),e.position.addInPlace(Jo._PivotTmpVector))),Jo._PivotCached++}static _RestorePivotPoint(e){e&&!Jo._OldPivotPoint.equalsToFloats(0,0,0)&&1===Jo._PivotCached&&(e.setPivotPoint(Jo._OldPivotPoint),e._postMultiplyPivotMatrix=Jo._PivotPostMultiplyPivotMatrix,Jo._PivotTmpVector.copyFromFloats(1,1,1),Jo._PivotTmpVector.subtractInPlace(e.scaling),Jo._PivotTmpVector.multiplyInPlace(Jo._PivotTranslation),e.position.subtractInPlace(Jo._PivotTmpVector)),this._PivotCached--}}function ea(e){const t=[],i=[],s=[],r=[],n=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,l=n/2,h=o/2;i.push(-l,-h,0),s.push(0,0,-1),r.push(0,dn.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),s.push(0,0,-1),r.push(1,dn.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),s.push(0,0,-1),r.push(1,dn.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),s.push(0,0,-1),r.push(0,dn.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),cn._ComputeSides(a,i,t,s,r,e.frontUVs,e.backUVs);const c=new cn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function ta(e,t={},i=null){const s=new bo(e,i);return t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,ea(t).applyToMesh(s,t.updatable),t.sourcePlane&&(s.translate(t.sourcePlane.normal,-t.sourcePlane.d),s.setDirection(t.sourcePlane.normal.scale(-1))),s}Jo._PivotCached=0,Jo._OldPivotPoint=new de,Jo._PivotTranslation=new de,Jo._PivotTmpVector=new de,Jo._PivotPostMultiplyPivotMatrix=!1;const ia={CreatePlane:ta};cn.CreatePlane=ea,bo.CreatePlane=(e,t,i,s,r)=>ta(e,{size:t,width:t,height:t,sideOrientation:r,updatable:s},i);class sa{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new X,this.onDragStartObservable=new X,this.onDragEndObservable=new X,this.onEnabledObservable=new X,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new de(0,0,0),this._alternatePickedPoint=new de(0,0,0),this._worldDragAxis=new de(0,0,0),this._targetPosition=new de(0,0,0),this._attachedToElement=!1,this._startDragRay=new Zo(new de,new de),this._lastPointerRay={},this._dragDelta=new de,this._pointA=new de(0,0,0),this._pointC=new de(0,0,0),this._localAxis=new de(0,0,0),this._lookAt=new de(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,sa._PlaneScene||(this._debugMode?sa._PlaneScene=this._scene:(sa._PlaneScene=new dr(this._scene.getEngine(),{virtual:!0}),sa._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{sa._PlaneScene.dispose(),sa._PlaneScene=null})))),this._dragPlane=ta("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:bo.DOUBLESIDE},sa._PlaneScene),this.lastDragPosition=new de(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==Ms.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==Ms.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==Ms.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===sa._AnyMouseId&&t!==sa._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new Zo(new de,new de)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;Jo._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),Jo._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=sa._AnyMouseId,t,i){this._startDrag(e,t,i);let s=this._lastPointerRay[e];e===sa._AnyMouseId&&(s=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),s&&this._moveDrag(s)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;Jo._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const s=this._pickWithRayOnDragPlane(this._startDragRay);s?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(s),this.onDragStartObservable.notifyObservers({dragPlanePoint:s,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),Jo._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){Jo._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?de.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=de.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),Jo._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(de.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*de.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=de.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=this._dragPlane.forward,s=this._dragPlane.position,r=e.direction.dot(i);if(Math.abs(r).999?Math.abs(de.Dot(de.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(de.Right()):this._lookAt.copyFrom(de.UpReadOnly):(de.CrossToRef(this._localAxis,this._pointC,this._lookAt),de.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?de.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}sa._AnyMouseId=-2;class ra{constructor(){this._startDistance=0,this._initialScale=new de(0,0,0),this._targetScale=new de(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new sa({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new sa({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const e=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(e,this._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}}))}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)}))}}class na{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new de,this._tmpQuaternion=new pe,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new X,this.onDragObservable=new X,this.onDragEndObservable=new X,this.allowMultiPointer=!0}get currentDraggingPointerId(){return void 0!==this.currentDraggingPointerIds[0]?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new Sn("",na._virtualScene);e.rotationQuaternion=new pe;const t=new Sn("",na._virtualScene);t.rotationQuaternion=new pe;const i=new Sn("",na._virtualScene);return i.rotationQuaternion=new pe,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new de,startingPivotOrientation:new pe,startingPosition:new de,startingOrientation:new pe,lastOriginPosition:new de,lastDragPosition:new de}}_resetVirtualMeshesPosition(){for(let e=0;el&&(l=Math.min(h-a,0)),o.scaleInPlace(l),o.addToRef(r.pivotMesh.absolutePosition,this._tmpVector),r.pivotMesh.setAbsolutePosition(this._tmpVector),o.addToRef(r.dragMesh.absolutePosition,this._tmpVector),r.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),na._virtualScene||(na._virtualScene=new dr(this._scene.getEngine(),{virtual:!0}),na._virtualScene.detachControl());const t=e=>this._ownerNode===e||e.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||-1!==this.draggableMeshes.indexOf(e));this._pointerObserver=this._scene.onPointerObservable.add((e=>{const i=e.event.pointerId;this._virtualMeshesInfo[i]||(this._virtualMeshesInfo[i]=this._createVirtualMeshInfo());const s=this._virtualMeshesInfo[i],r="xr-near"===e.event.pointerType||"xr"===e.event.pointerType;if(e.type==Ms.POINTERDOWN){if(!s.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&(!r||e.pickInfo.aimTransform)&&t(e.pickInfo.pickedMesh)){if((!this.allowMultiPointer||r)&&this.currentDraggingPointerIds.length>0)return;!this._pointerCamera||this._pointerCamera.cameraRigMode!==Kr.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||e.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const t=this._virtualMeshesInfo[i];r?(this._dragging=e.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,t.originMesh.position.copyFrom(e.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&e.pickInfo.gripTransform?t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.gripTransform.rotationQuaternion):t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,t.originMesh.position.copyFrom(e.pickInfo.ray.origin)),t.lastOriginPosition.copyFrom(t.originMesh.position),t.dragMesh.position.copyFrom(e.pickInfo.pickedPoint),t.lastDragPosition.copyFrom(e.pickInfo.pickedPoint),t.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),t.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),t.startingPosition.copyFrom(t.dragMesh.position),t.startingPivotPosition.copyFrom(t.pivotMesh.position),t.startingOrientation.copyFrom(t.dragMesh.rotationQuaternion),t.startingPivotOrientation.copyFrom(t.pivotMesh.rotationQuaternion),r?(t.originMesh.addChild(t.dragMesh),t.originMesh.addChild(t.pivotMesh)):t.originMesh.lookAt(t.dragMesh.position),t.dragging=!0,-1===this.currentDraggingPointerIds.indexOf(i)&&this.currentDraggingPointerIds.push(i),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):this.allowMultiPointer&&0!==this.currentDraggingPointerIds.length||(this._attachedToElement=!1)),this._targetDragStart(t.pivotMesh.position,t.pivotMesh.rotationQuaternion,i),this.onDragStartObservable.notifyObservers({position:t.pivotMesh.position})}}else if(e.type==Ms.POINTERUP||e.type==Ms.POINTERDOUBLETAP){const e=this.currentDraggingPointerIds.indexOf(i);s.dragging=!1,-1!==e&&(this.currentDraggingPointerIds.splice(e,1),0===this.currentDraggingPointerIds.length&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),s.originMesh.removeChild(s.dragMesh),s.originMesh.removeChild(s.pivotMesh),this._targetDragEnd(i),this.onDragEndObservable.notifyObservers({}))}else if(e.type==Ms.POINTERMOVE&&-1!==this.currentDraggingPointerIds.indexOf(i)&&s.dragging&&e.pickInfo&&(e.pickInfo.ray||e.pickInfo.aimTransform)){let t=this.zDragFactor;(this.currentDraggingPointerIds.length>1||e.pickInfo.originMesh)&&(t=0),this._ownerNode.computeWorldMatrix(!0),r?this._pointerUpdateXR(e.pickInfo.aimTransform,e.pickInfo.gripTransform,i,t):this._pointerUpdate2D(e.pickInfo.ray,i,t),this._tmpQuaternion.copyFrom(s.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,s.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),s.pivotMesh.absolutePosition.subtractToRef(s.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:s.pivotMesh.position,pickInfo:e.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,i),s.lastDragPosition.copyFrom(s.dragMesh.absolutePosition),this._moving=!0}}))}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if("ArcRotateCamera"===this._pointerCamera.getClassName()){const e=this._pointerCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(!this._pointerCamera.inputs||this._pointerCamera.inputs.noPreventDefault)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}class oa extends na{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new de(0,0,0),this._targetOrientation=new pe,this._targetScaling=new de(1,1,1),this._startingPosition=new de(0,0,0),this._startingOrientation=new pe,this._startingScaling=new de(1,1,1),this.onPositionChangedObservable=new X,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,e.getChildMeshes().forEach((e=>{e.isNearGrabbable=!0})),this._virtualTransformNode=new xn("virtual_sixDof",na._virtualScene),this._virtualTransformNode.rotationQuaternion=pe.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(1===this.currentDraggingPointerIds.length&&this._moving&&!this.disableMovement){const t=ge.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=ge.Vector3[1];if(i.copyFrom(t),e.parent){const s=ge.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(s),s.invert(),de.TransformNormalToRef(t,s,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const t=ge.Quaternion[0];if(t.copyFrom(this._targetOrientation),e.parent){const i=ge.Quaternion[0];i.copyFrom(e.parent.absoluteRotationQuaternion),i.invertInPlace(),i.multiplyToRef(this._targetOrientation,t)}pe.SlerpToRef(e.rotationQuaternion,t,this.dragDeltaRatio,e.rotationQuaternion)}}}))}_getPositionOffsetAround(e,t,i){const s=ge.Matrix[0],r=ge.Matrix[1],n=ge.Matrix[2],o=ge.Matrix[3],a=ge.Matrix[4];return fe.TranslationToRef(e.x,e.y,e.z,s),fe.TranslationToRef(-e.x,-e.y,-e.z,r),fe.FromQuaternionToRef(i,n),fe.ScalingToRef(t,t,t,o),r.multiplyToRef(n,a),a.multiplyToRef(o,a),a.multiplyToRef(s,a),a.getTranslation()}_onePointerPositionUpdated(e,t){ge.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?pe.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,ge.Quaternion[0]):ge.Quaternion[0].copyFrom(t),ge.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=ge.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const s=ge.Vector3[1];t.subtractToRef(e,s);const r=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,n=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=ge.Vector3[2];r.addToRef(n,o),o.scaleInPlace(.5);const a=ge.Vector3[3];n.subtractToRef(r,a);const l=a.length()/s.length(),h=o.subtract(i),c=pe.FromEulerAngles(0,de.GetAngleBetweenVectorsOnPlane(s.normalize(),a.normalize(),de.UpReadOnly),0),u=this._ownerNode.parent;this._ownerNode.setParent(null);const d=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),l,c);this._virtualTransformNode.rotationQuaternion.multiplyToRef(c,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(l,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(h.addInPlace(d),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(u)}_targetDragStart(){const e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=pe.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const t=this._ownerNode.getAbsolutePivotPoint();if(1===e){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const e=ge.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,e),e.normalize();const i=ge.Quaternion[0];this._scene.useRightHandedSystem?pe.FromLookDirectionRHToRef(e,new de(0,1,0),i):pe.FromLookDirectionLHToRef(e,new de(0,1,0),i),i.normalize(),pe.RotationYawPitchRollToRef(i.toEulerAngles().y,0,0,ge.Quaternion[0]),this._targetOrientation.copyFrom(ge.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else 2===e&&(this._virtualTransformNode.setPivotPoint(new de(0,0,0),lr.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,lr.WORLD),this._resetVirtualMeshesPosition())}_targetDrag(e,t){1===this.currentDraggingPointerIds.length?this._onePointerPositionUpdated(e,t):2===this.currentDraggingPointerIds.length&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(1===this.currentDraggingPointerIds.length){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}class aa{constructor(){this._attachPointLocalOffset=new de,this._workingPosition=new de,this._workingQuaternion=new pe,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=pe.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const s=ge.Vector3[0];return s.copyFrom(t),s.scaleInPlace(this.hitNormalOffset),s.addInPlace(i),this._attachedMesh.parent&&(ge.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),de.TransformNormalToRef(s,ge.Matrix[0],s)),{position:s,quaternion:pe.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const e=this._getTargetPose(t);e&&de.Distance(this._attachedMesh.position,e.position){this.enabled&&e.type==Ms.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)})),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}class la{constructor(){this._tmpQuaternion=new pe,this._tmpVectors=[new de,new de,new de,new de,new de,new de,new de],this._tmpMatrix=new fe,this._tmpInvertView=new fe,this._tmpForward=new de,this._tmpNodeForward=new de,this._tmpPosition=new de,this._workingPosition=new de,this._workingQuaternion=new pe,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(de.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,s=this.maximumDistance;const r=this.defaultDistance,n=this._tmpVectors[0];n.copyFrom(e);let o=n.length();if(n.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(n)*i,s=this._length2D(n)*s;const t=this._length2D(e);n.scaleInPlace(o/t),o=t}let a=o;return a=t?r:xe.Clamp(o,i,s),e.copyFrom(n).scaleInPlace(a),o!==a}_applyVerticalClamp(e){0!==this.verticalMaxDistance&&(e.y=xe.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){pe.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),de.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),de.TransformNormalToRef(i,e,i),pe.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const s=this._tmpVectors[6];s.copyFromFloats(1,0,0),de.TransformNormalToRef(i,e,i),de.TransformNormalToRef(s,e,s);const r=de.UpReadOnly;if(t.length()r&&(pe.RotationAxisToRef(s,-e+r,o),t.rotateByQuaternionToRef(o,t),n=!0)}const a=this._angleBetweenVectorAndPlane(t,s)*(this._scene.useRightHandedSystem?-1:1),l=this.maxViewHorizontalDegrees*Math.PI/180*.5;return a<-l?(pe.RotationAxisToRef(r,-a-l,o),t.rotateByQuaternionToRef(o,t),n=!0):a>l&&(pe.RotationAxisToRef(r,-a+l,o),t.rotateByQuaternionToRef(o,t),n=!0),n}_orientationClamp(e,t){const i=this._tmpVectors[0];i.copyFrom(e).scaleInPlace(-1).normalize();const s=this._tmpVectors[1],r=this._tmpVectors[2];s.copyFromFloats(0,1,0),de.CrossToRef(i,s,r);const n=r.length();nthis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),s=this._workingPosition,r=this._workingQuaternion,n=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),de.TransformCoordinatesToRef(n,i,s);const a=this._tmpPosition;a.copyFromFloats(0,0,0),de.TransformCoordinatesToRef(a,i,a),a.scaleInPlace(-1).subtractInPlace(n),s.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let l=!1;const h=this._tmpForward;h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),de.TransformNormalToRef(h,o,h);const c=this._tmpNodeForward;if(c.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),de.TransformNormalToRef(c,i,c),this._recenterNextUpdate)s.copyFrom(h).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const e=s.length();s.copyFrom(h).scaleInPlace(e)}else l=this._angularClamp(o,s);let u=!1;this.ignoreDistanceClamp||(u=this._distanceClamp(s,l),this._applyVerticalClamp(s)),this.useFixedVerticalOffset&&(s.y=a.y-e.globalPosition.y+this.fixedVerticalOffset),(l||u||this._passedOrientationDeadzone(s,c)||this._recenterNextUpdate)&&this._orientationClamp(s,r),this._workingPosition.subtractInPlace(n),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=pe.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose)return this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),void this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);const i=new de;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),de.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const s=new pe;s.copyFrom(this.attachedNode.rotationQuaternion),pe.SmoothToRef(s,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}class ha{}ha.ANCHOR_SYSTEM="xr-anchor-system",ha.BACKGROUND_REMOVER="xr-background-remover",ha.HIT_TEST="xr-hit-test",ha.MESH_DETECTION="xr-mesh-detection",ha.PHYSICS_CONTROLLERS="xr-physics-controller",ha.PLANE_DETECTION="xr-plane-detection",ha.POINTER_SELECTION="xr-controller-pointer-selection",ha.TELEPORTATION="xr-controller-teleportation",ha.FEATURE_POINTS="xr-feature-points",ha.HAND_TRACKING="xr-hand-tracking",ha.IMAGE_TRACKING="xr-image-tracking",ha.NEAR_INTERACTION="xr-near-interaction",ha.DOM_OVERLAY="xr-dom-overlay",ha.MOVEMENT="xr-controller-movement",ha.LIGHT_ESTIMATION="xr-light-estimation",ha.EYE_TRACKING="xr-eye-tracking",ha.WALKING_LOCOMOTION="xr-walking-locomotion",ha.LAYERS="xr-layers",ha.DEPTH_SENSING="xr-depth-sensing",ha.SPACE_WARP="xr-space-warp",ha.RAW_CAMERA_ACCESS="xr-raw-camera-access";class ca{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||hs.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||hs.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},s=!0,r=!0){const n="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(o="stable"===t?ca.GetStableVersionOfFeature(n):"latest"===t?ca.GetLatestVersionOfFeature(n):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const a=ca._ConflictingFeatures[n];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${n} cannot be enabled while ${a} is enabled.`);const l=this._features[n],h=ca.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);l&&this.disableFeature(n);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[n]={featureImplementation:c,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return hs.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],s=t.featureImplementation.xrNativeFeatureName;if(s&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(s)&&e.requiredFeatures.push(s)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(s)&&e.optionalFeatures.push(s))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}ca._AvailableFeatures={},ca._ConflictingFeatures={[ha.TELEPORTATION]:ha.MOVEMENT,[ha.MOVEMENT]:ha.TELEPORTATION};class ua{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===this._xrSessionManager.enabledFeatures?.indexOf(e)&&we.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new X,this.onFeatureDetachObservable=new X}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(this._xrSessionManager.enabledFeatures){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else we.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class da{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}da.DistanceJoint=0,da.HingeJoint=1,da.BallAndSocketJoint=2,da.WheelJoint=3,da.SliderJoint=4,da.PrismaticJoint=5,da.UniversalJoint=6,da.Hinge2Joint=da.WheelJoint,da.PointToPointJoint=8,da.SpringJoint=9,da.LockJoint=10;class _a extends da{constructor(e){super(da.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class pa extends da{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class fa extends pa{constructor(e){super(da.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class ma extends pa{constructor(e){super(da.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}bo._PhysicsImpostorParser=function(e,t,i){return new ga(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class ga{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},s){this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=de.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new pe,this._tmpQuat2=new pe,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new pe),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(this)})),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,ga._TmpVecs[0]),this.object.translate(ga._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&we.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=pe.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new pe),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&we.Warn("You must affect impostors to children before affecting impostor to parent.")):we.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):we.Error("No object was provided. A physics object is obligatory")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof Sn?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=ga.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const s=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}return ga.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):de.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):de.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):we.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):we.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let s=-1;this._onPhysicsCollideCallbacks.some(((e,r)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(s=r),t}return!1}))?this._onPhysicsCollideCallbacks.splice(s,1):we.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):pe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const s=new da(t,i);return this.addJoint(e,s),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new ga(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach((e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new pe),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,s,r){const n=ga._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const i=ga._TmpQuat;o.rotationQuaternion.multiplyToRef(r,i),e.setRotationQuaternion(i,lr.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,lr.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==s&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const i=ga._TmpQuat;e.getRotationQuaternionToRef(lr.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(lr.WORLD,t,o.rotationQuaternion);const a=ga._TmpVecs[0],l=ga._TmpVecs[1];n||((n=ga._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}}var va,xa,ba,Ta,ya,Sa,Ca,Ea,Aa;ga.DEFAULT_OBJECT_SIZE=new de(1,1,1),ga.IDENTITY_QUATERNION=pe.Identity(),ga._TmpVecs=$.BuildArray(3,de.Zero),ga._TmpQuat=pe.Identity(),ga.NoImpostor=0,ga.SphereImpostor=1,ga.BoxImpostor=2,ga.PlaneImpostor=3,ga.MeshImpostor=4,ga.CapsuleImpostor=6,ga.CylinderImpostor=7,ga.ParticleImpostor=8,ga.HeightmapImpostor=9,ga.ConvexHullImpostor=10,ga.CustomImpostor=100,ga.RopeImpostor=101,ga.ClothImpostor=102,ga.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(va||(va={}));class Pa{static get ForceFullSceneLoadingForIncremental(){return un.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){un.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return un.ShowLoadingScreen}static set ShowLoadingScreen(e){un.ShowLoadingScreen=e}static get loggingLevel(){return un.loggingLevel}static set loggingLevel(e){un.loggingLevel=e}static get CleanBoneMatrixWeights(){return un.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){un.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Pa._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return Pa._RegisteredPlugins[e]||(we.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),Pa.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Pa._RegisteredPlugins){const i=Pa._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Pa._RegisteredPlugins[t]}return Pa.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return Pa._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,r,n,o,a){const l=Pa._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?Pa._GetPluginForExtension(o):l?Pa._GetPluginForDirectLoad(e.url):Pa._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(Pa.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!Zi(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const u=h.isBinary,d=(e,s)=>{t.isDisposed?r("Scene has been disposed"):i(c,e,s)};let _=null,p=!1;const f=c.onDisposeObservable;f&&f.add((()=>{p=!0,_&&(_.abort(),_=null),n()}));const m=()=>{if(p)return;const i=(e,t)=>{r(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";_=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,s,u,i,a):t._loadFile(e.file||e.url,d,s,!0,u,i)},g=t.getEngine();let v=g.enableOfflineSupport;if(v){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}v=!i}return v&&gn.OfflineProviderFactory?t.offlineProvider=gn.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,r=e}else if(ArrayBuffer.isView(t))i="",s=ns(),n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const r=t;if("/"===r.substr(0,1))return hs.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}else i=e,s=hs.GetFilename(e),e=hs.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return Pa._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Pa._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;Pa._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Pa._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=se.LastCreatedScene,r=null,n=null,o=null,a=null,l=""){if(!s)return we.Error("No scene available to import mesh to"),null;const h=Pa._GetFileInfo(t,i);if(!h)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(e,t)=>{const i=Pa._FormatErrorMessage(h,e,t);o?o(s,i,new Qt(i,Yt.SceneLoaderError,t)):we.Error(i),u()},_=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,p=(e,t,i,n,o,a,l,u)=>{if(s.importedMeshesFiles.push(h.url),r)try{r(e,t,i,n,o,a,l,u)}catch(e){d("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return Pa._LoadData(h,s,((t,i,r)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,r)),t.importMesh){const r=[],n=[],o=[];if(!t.importMesh(e,s,i,h.rootUrl,r,n,o,d))return;s.loadingPluginName=t.name,p(r,n,o,[],[],[],[],[])}else t.importMeshAsync(e,s,i,h.rootUrl,_,h.name).then((e=>{s.loadingPluginName=t.name,p(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{d(e.message,e)}))}),_,d,u,a,l)}static ImportMeshAsync(e,t,i="",s=se.LastCreatedScene,r=null,n=null,o=""){return new Promise(((a,l)=>{Pa.ImportMesh(e,t,i,s,((e,t,i,s,r,n,o,l)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:r,geometries:n,lights:o,spriteManagers:l})}),r,((e,t,i)=>{l(i||new Error(t))}),n,o)}))}static Load(e,t="",i=se.LastCreatedEngine,s=null,r=null,n=null,o=null,a=""){return i?Pa.Append(e,t,new dr(i),s,r,n,o,a):(hs.Error("No engine available"),null)}static LoadAsync(e,t="",i=se.LastCreatedEngine,s=null,r=null,n=""){return new Promise(((o,a)=>{Pa.Load(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static Append(e,t="",i=se.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return we.Error("No scene available to append to"),null;const l=Pa._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};Pa.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const u=(e,t)=>{const s=Pa._FormatErrorMessage(l,e,t);n?n(i,s,new Qt(s,Yt.SceneLoaderError,t)):we.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=()=>{if(s)try{s(i)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Pa._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,u))return;i.loadingPluginName=e.name,_()}else e.loadAsync(i,t,l.rootUrl,d,l.name).then((()=>{i.loadingPluginName=e.name,_()})).catch((e=>{u(e.message,e)}))}),d,u,c,o,a)}static AppendAsync(e,t="",i=se.LastCreatedScene,s=null,r=null,n=""){return new Promise(((o,a)=>{Pa.Append(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static LoadAssetContainer(e,t="",i=se.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return we.Error("No scene available to load asset container to"),null;const l=Pa._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},u=(e,t)=>{const s=Pa._FormatErrorMessage(l,e,t);n?n(i,s,new Qt(s,Yt.SceneLoaderError,t)):we.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=e=>{if(s)try{s(e)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Pa._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,l.rootUrl,u);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,_(s)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,_(t)})).catch((e=>{u(e.message,e)})):u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),d,u,c,o,a)}static LoadAssetContainerAsync(e,t="",i=se.LastCreatedScene,s=null,r=null){return new Promise(((n,o)=>{Pa.LoadAssetContainer(e,t,i,(e=>{n(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=se.LastCreatedScene,s=!0,r=va.Clean,n=null,o=null,a=null,l=null,h=null){if(!i)return void we.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case va.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case va.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case va.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case va.NoSync:break;default:return void we.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h)}static ImportAnimationsAsync(e,t="",i=se.LastCreatedScene,s=!0,r=va.Clean,n=null,o=null,a=null,l=null,h=null){return new Promise(((o,l)=>{Pa.ImportAnimations(e,t,i,s,r,n,(e=>{o(e)}),a,((e,t,i)=>{l(i||new Error(t))}),h)}))}}Pa.NO_LOGGING=0,Pa.MINIMAL_LOGGING=1,Pa.SUMMARY_LOGGING=2,Pa.DETAILED_LOGGING=3,Pa.OnPluginActivatedObservable=new X,Pa._RegisteredPlugins={},Pa._ShowingLoadingScreen=!1;class Ra extends uo{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new fe,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(xa||(xa={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(ba||(ba={}));class Ia{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){const t=e.sharedData.emitComments,i=this.target===ba.Fragment;this.compilationString=`\n${t?"//Entry point\n":""}void main(void) {\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\n${t?"//Constants\n":""}${this._constantDeclaration}\n${this.compilationString}`);let s="";for(const e in this.functions)s+=this.functions[e]+"\n";this.compilationString=`\n${s}\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\n${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\n${t?"//Samplers\n":""}${this._samplerDeclaration}\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\n${t?"//Uniforms\n":""}${this._uniformDeclaration}\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\n${t?"//Attributes\n":""}${this._attributeDeclaration}\n${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defined(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString);for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\n${t}\n${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2D ${e};\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\n`,this.samplers.push(e))}_getGLType(e){switch(e){case xa.Float:return"float";case xa.Int:return"int";case xa.Vector2:return"vec2";case xa.Color3:case xa.Vector3:return"vec3";case xa.Color4:case xa.Vector4:return"vec4";case xa.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\n${t}\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`;let s=Ti.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(s=t+"\n"+s),!i)return s;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`:this.functions[r]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""}\n`,void(this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]));if(this.functions[r]=Ti.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;ethis._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;te.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ba.Vertex)return!0;if((e.ownerBlock.target===ba.Neutral||e.ownerBlock.target===ba.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===ba.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ba.Vertex)return!0;if(e.target===ba.Vertex)return!0;if((e.ownerBlock.target===ba.Neutral||e.ownerBlock.target===ba.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===ba.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ba.Fragment)return!0;if((e.ownerBlock.target===ba.Neutral||e.ownerBlock.target===ba.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=xa.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new X,this.onDisconnectionObservable=new X,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=ba.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===Ta.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===ba.Fragment){if(i.target===ba.Vertex)return Ta.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=ba.Neutral&&e.isConnectedInVertexShader)return Ta.TargetIncompatible}if(this.type!==e.type&&e.innerType!==xa.AutoDetect)return Da.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&Da.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?Ta.Compatible:Ta.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return Ta.TypeIncompatible;let s=i,r=t;return this.direction===ya.Input&&(s=t,r=i),s.isAnAncestorOf(r)?Ta.HierarchyIssue:Ta.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class wa{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=ba.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===ba.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=rr.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===ba.Neutral}initialize(e){}bind(e,t,i,s){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some((e=>e.isConnectedInFragmentShader))}registerInput(e,t,i=!1,s,r){return(r=r??new Da(e,this,ya.Input)).type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return(s=s??new Da(e,this,ya.Output)).type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==xa.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===ba.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=(()=>!0)){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===ba.Vertex||this.target!==ba.VertexAndFragment&&this.target!==ba.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,s=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,s){e.build(t,s);const r=null!=t._vertexState,n=e._buildTarget===ba.Vertex&&e.target!==ba.VertexAndFragment;if(r&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==ba.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName};\n`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==ba.Neutral){if(!(i.target&this.target))continue;if(!(i.target&e.target))continue}const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&we.Log(`${e.target===ba.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case ba.Vertex:e.sharedData.checks.emitVertex=!0;break;case ba.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\n//${this.name}\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const s of i.endpoints){const i=s.ownerBlock;i&&i.target&e.target&&-1!==t.indexOf(i)&&this._processBuild(i,e,s,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\n${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.target = ${this.target};\n`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`,s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}clone(e,t=""){const i=this.serialize(),s=te(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class Na extends wa{constructor(e){super(e,ba.Neutral),this.complementW=1,this.complementZ=0,this.target=ba.Vertex,this.registerInput("vector",xa.AutoDetect),this.registerInput("transform",xa.Matrix),this.registerOutput("output",xa.Vector4),this.registerOutput("xyz",xa.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){const s=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",s),e.sharedData.blocksWithDefines.push(this);const r=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${r} = mat3(${i.associatedVariableName});\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\n",e.compilationString+=`${r} = transposeMat3(inverseMat3(${r}));\n`,e.compilationString+="#endif\n",t.connectedPoint.type){case xa.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`;break;case xa.Vector3:case xa.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`}}else{const s=i.associatedVariableName;switch(t.connectedPoint.type){case xa.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`;break;case xa.Vector3:case xa.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${s} * ${t.associatedVariableName};\n`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\n`,e}}ee("BABYLON.TransformBlock",Na);class Fa extends wa{constructor(e){super(e,ba.Vertex,!0),this.registerInput("vector",xa.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName};\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n"),this}}function Ba(e,t=Sa.Boolean,i="PROPERTIES",s){return(r,n)=>{let o=r._propStore;o||(o=[],r._propStore=o),o.push({propertyName:n,displayName:e,type:t,groupName:i,options:s??{}})}}ee("BABYLON.VertexOutputBlock",Fa),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(Sa||(Sa={}));class La extends wa{constructor(e){super(e,ba.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",xa.Color4,!0),this.registerInput("rgb",xa.AutoDetect,!0),this.registerInput("a",xa.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&wn(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",r),t.connectedPoint)s.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${s.associatedVariableName});\n`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName};\n`;else if(i.connectedPoint){let t="1.0";s.connectedPoint&&(t=s.associatedVariableName),i.connectedPoint.type===xa.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\n`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t});\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+="gl_FragColor = toLinearSpace(gl_FragColor);\n",e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+="gl_FragColor = toGammaSpace(gl_FragColor);\n",e.compilationString+="#endif\n",(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n"),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="gl_FragData[0] = gl_FragColor;\r\n",e.compilationString+="#endif\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}qe([Ba("Convert to gamma space",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],La.prototype,"convertToGammaSpace",void 0),qe([Ba("Convert to linear space",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],La.prototype,"convertToLinearSpace",void 0),qe([Ba("Use logarithmic depth",Sa.Boolean,"PROPERTIES")],La.prototype,"useLogarithmicDepth",void 0),ee("BABYLON.FragmentOutputBlock",La),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(Ca||(Ca={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(Ea||(Ea={}));class ka{constructor(e=de.Zero(),t=de.Up()){this.position=e,this.normal=t}clone(){return new ka(this.position.clone(),this.normal.clone())}}class Va{constructor(e=de.Zero(),t=de.Up(),i=ue.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new Va(this.position.clone(),this.normal.clone(),this.uv.clone())}}!function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(Aa||(Aa={}));const Ua={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},Ga={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},za={particle_texturemask:!0};class Wa extends wa{get type(){if(this._type===xa.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=xa.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=xa.Vector2,this._type;case"Vector3":return this._type=xa.Vector3,this._type;case"Vector4":return this._type=xa.Vector4,this._type;case"Color3":return this._type=xa.Color3,this._type;case"Color4":return this._type=xa.Color4,this._type;case"Matrix":return this._type=xa.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=xa.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=xa.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=xa.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=xa.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Ea.World:case Ea.WorldView:case Ea.WorldViewProjection:case Ea.View:case Ea.ViewProjection:case Ea.Projection:return this._type=xa.Matrix,this._type;case Ea.CameraPosition:return this._type=xa.Vector3,this._type;case Ea.FogColor:return this._type=xa.Color3,this._type;case Ea.DeltaTime:case Ea.MaterialAlpha:return this._type=xa.Float,this._type;case Ea.CameraParameters:return this._type=xa.Vector4,this._type}}return this._type}constructor(e,t=ba.Vertex,i=xa.AutoDetect){super(e,t,!1),this._mode=Ca.Undefined,this._animationType=Aa.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new X,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=Ca.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===xa.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=Ca.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Ca.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===Ca.Undefined}get isUniform(){return this._mode===Ca.Uniform}set isUniform(e){this._mode=e?Ca.Uniform:Ca.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Ca.Attribute}set isAttribute(e){this._mode=e?Ca.Attribute:Ca.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Ca.Varying}set isVarying(e){this._mode=e?Ca.Varying:Ca.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Ca.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Aa.Time:this.type===xa.Float&&(this.value+=.01*e.getAnimationRatio());break;case Aa.RealTime:this.type===xa.Float&&(this.value=(zt.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\n`:`#ifdef ${e}\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case xa.Float:this.value=0;break;case xa.Vector2:this.value=ue.Zero();break;case xa.Vector3:this.value=de.Zero();break;case xa.Vector4:this.value=_e.Zero();break;case xa.Color3:this.value=Ce.White();break;case xa.Color4:this.value=new Ee(1,1,1,1);break;case xa.Matrix:this.value=fe.Identity()}}_emitConstant(e){switch(this.type){case xa.Float:return`${e._emitFloat(this.value)}`;case xa.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case xa.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case xa.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case xa.Color3:return Ae.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Ae.Color3[0].toGammaSpaceToRef(Ae.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Ae.Color3[0].toLinearSpaceToRef(Ae.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${Ae.Color3[0].r}, ${Ae.Color3[0].g}, ${Ae.Color3[0].b})`;case xa.Color4:return Ae.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Ae.Color4[0].toGammaSpaceToRef(Ae.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Ae.Color4[0].toLinearSpaceToRef(Ae.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${Ae.Color4[0].r}, ${Ae.Color4[0].g}, ${Ae.Color4[0].b}, ${Ae.Color4[0].a})`}return""}get _noContextSwitch(){return Ga[this.name]}_emit(e,t){if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)};\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName};\n`,t&&(e._uniformDeclaration+="#endif\n");const i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case Ea.WorldView:i.needWorldViewMatrix=!0;break;case Ea.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==Aa.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=Ua[this.name]??this.name,this.target===ba.Vertex&&e._vertexState)return void(Ga[this.name]?za[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),Ga[this.name]?za[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName};\n`,t&&(e._attributeDeclaration+="#endif\n"))}}_transmitWorld(e,t,i,s){if(!this._systemValue)return;const r=this.associatedVariableName;switch(this._systemValue){case Ea.World:e.setMatrix(r,t);break;case Ea.WorldView:e.setMatrix(r,i);break;case Ea.WorldViewProjection:e.setMatrix(r,s)}}_transmit(e,t,i){if(this.isAttribute)return;const s=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case Ea.World:case Ea.WorldView:case Ea.WorldViewProjection:return;case Ea.View:e.setMatrix(s,t.getViewMatrix());break;case Ea.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case Ea.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case Ea.CameraPosition:t.bindEyePosition(e,s,!0);break;case Ea.FogColor:e.setColor3(s,t.fogColor);break;case Ea.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case Ea.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Ea.MaterialAlpha:e.setFloat(s,i.alpha)}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(null!==r)switch(this.type){case xa.Float:e.setFloat(s,r);break;case xa.Int:e.setInt(s,r);break;case xa.Color3:Ae.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Ae.Color3[0].toGammaSpaceToRef(Ae.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Ae.Color3[0].toLinearSpaceToRef(Ae.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,Ae.Color3[0]);break;case xa.Color4:Ae.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Ae.Color4[0].toGammaSpaceToRef(Ae.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Ae.Color4[0].toLinearSpaceToRef(Ae.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,Ae.Color4[0]);break;case xa.Vector2:e.setVector2(s,r);break;case xa.Vector3:e.setVector3(s,r);break;case xa.Vector4:e.setVector4(s,r);break;case xa.Matrix:e.setMatrix(s,r)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${Ea[this._systemValue]});\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case xa.Float:i=`${this.value}`;break;case xa.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case xa.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case xa.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case xa.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case xa.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case xa.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===xa.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Aa[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===Ca.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===Ca.Attribute&&e.type===xa.Vector3&&(this._type=xa.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=te(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}ee("BABYLON.InputBlock",Wa);class Ha extends wa{constructor(e){super(e,ba.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",xa.AutoDetect,!1,ba.VertexAndFragment),this.registerOutput("rgba",xa.Color4,ba.Neutral),this.registerOutput("rgb",xa.Color3,ba.Neutral),this.registerOutput("r",xa.Float,ba.Neutral),this.registerOutput("g",xa.Float,ba.Neutral),this.registerOutput("b",xa.Float,ba.Neutral),this.registerOutput("a",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?ba.VertexAndFragment:ba.Fragment:ba.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ba.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}else this.uv.ownerBlock.target!==ba.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ba.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target!==ba.Fragment?(e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"):e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==ba.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}ee("BABYLON.CurrentScreenBlock",Ha);class Xa extends wa{constructor(e){super(e,ba.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",xa.AutoDetect,!1,ba.VertexAndFragment),this.registerOutput("rgba",xa.Color4,ba.Neutral),this.registerOutput("rgb",xa.Color3,ba.Neutral),this.registerOutput("r",xa.Float,ba.Neutral),this.registerOutput("g",xa.Float,ba.Neutral),this.registerOutput("b",xa.Float,ba.Neutral),this.registerOutput("a",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name&&t(e)));i||(i=new Wa("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"}_buildBlock(e){if(super._buildBlock(e),e.target===ba.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}ee("BABYLON.ParticleTextureBlock",Xa);class Ya extends wa{constructor(e){super(e,ba.Fragment),this._isUnique=!0,this.registerInput("color",xa.Color4,!1,ba.Fragment),this.registerOutput("rampColor",xa.Color4,ba.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==ba.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${this._declareOutput(this.rampColor,e)} = baseColor;\n #else\n ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}ee("BABYLON.ParticleRampGradientBlock",Ya);class Qa extends wa{constructor(e){super(e,ba.Fragment),this._isUnique=!0,this.registerInput("color",xa.Color4,!1,ba.Fragment),this.registerInput("alphaTexture",xa.Float,!1,ba.Fragment),this.registerInput("alphaColor",xa.Float,!1,ba.Fragment),this.registerOutput("blendColor",xa.Color4,ba.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==ba.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${this._declareOutput(this.blendColor,e)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}ee("BABYLON.ParticleBlendMultiplyBlock",Qa);class ja{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;n!==Ai.Depth&&n!==Ai.DepthStencil||(i=!0,r=t[t.length-1].format,s--);const o=[],a=[],l=[],h=[],c=[],u=[],d=[],_={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,o,e._hardwareTexture.underlyingResource,s)}this._engine._bindUnboundFramebuffer(n)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1&&(15===o.format?u=i.DEPTH_COMPONENT16:16===o.format?u=i.DEPTH_COMPONENT24:17===o.format||13===o.format?u=i.DEPTH24_STENCIL8:14===o.format?u=i.DEPTH_COMPONENT32F:18===o.format&&(u=i.DEPTH32F_STENCIL8)),o.is2DArray?i.texImage3D(n,0,u,o.width,o.height,s,0,c,h,null):o.is3D?i.texImage3D(n,0,u,o.width,o.height,r,0,c,h,null):i.texImage2D(n,0,u,o.width,o.height,0,c,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(o),o},ki.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t};class qa{static RegisterShaderCodeProcessing(e,t){t?qa._CustomShaderCodeProcessing[e??""]=t:delete qa._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return qa._CustomShaderCodeProcessing[e]??qa._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,o=1,a,l,h=null,c=0,u="postprocess",d,_=!1,p=5,f=ui.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new ds(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new ue(1,1),this._texelSize=ue.Zero(),this.onActivateObservable=new X,this.onSizeChangedObservable=new X,this.onApplyObservable=new X,this.onBeforeRenderObservable=new X,this.onAfterRenderObservable=new X,this.name=e;let m=1,g=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,m=e.size??1,n=e.camera??null,o=e.samplingMode??1,a=e.engine,l=e.reusable,h=e.defines??null,c=e.textureType??0,u=e.vertexUrl??"postprocess",d=e.indexParameters,_=e.blockCompilation??!1,p=e.textureFormat??5,f=e.shaderLanguage??ui.GLSL,g=e.uniformBuffers??null}else r&&(m="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):a&&(this._engine=a,this._engine.postProcesses.push(this)),this._options=m,this.renderTargetSamplingMode=o||1,this._reusable=l||!1,this._textureType=c,this._textureFormat=p,this._shaderLanguage=f,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=g||[],this._indexParameters=d,this._drawWrapper=new Fi(this._engine),_||this.updateEffect(h)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new ds(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,a){const l=qa._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=l.defineCustomBindings(this.name,e,s,r),t=s,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:a??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(e,t)=>l.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:l?.processFinalCode?(e,t)=>l.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,a/h),this._engine.bindFramebuffer(u,0,o,a,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),qa._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=yt.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=qa.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=te(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return yt.Parse((()=>new qa(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,s)}}qa._CustomShaderCodeProcessing={},qe([st()],qa.prototype,"uniqueId",void 0),qe([st()],qa.prototype,"name",void 0),qe([st()],qa.prototype,"width",void 0),qe([st()],qa.prototype,"height",void 0),qe([st()],qa.prototype,"renderTargetSamplingMode",void 0),qe([ut()],qa.prototype,"clearColor",void 0),qe([st()],qa.prototype,"autoClear",void 0),qe([st()],qa.prototype,"forceAutoClearInAlphaMode",void 0),qe([st()],qa.prototype,"alphaMode",void 0),qe([st()],qa.prototype,"alphaConstants",void 0),qe([st()],qa.prototype,"enablePixelPerfectMode",void 0),qe([st()],qa.prototype,"forceFullscreenViewport",void 0),qe([st()],qa.prototype,"scaleMode",void 0),qe([st()],qa.prototype,"alwaysForcePOT",void 0),qe([st("samples")],qa.prototype,"_samples",void 0),qe([st()],qa.prototype,"adaptScaleToCurrentViewport",void 0),ee("BABYLON.PostProcess",qa);class Za extends wa{constructor(e){super(e,ba.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",xa.Vector4,!0),this.registerInput("xyz ",xa.Vector3,!0),this.registerInput("xy ",xa.Vector2,!0),this.registerInput("zw ",xa.Vector2,!0),this.registerInput("x",xa.Float,!0),this.registerInput("y",xa.Float,!0),this.registerInput("z",xa.Float,!0),this.registerInput("w",xa.Float,!0),this.registerOutput("xyzw",xa.Vector4),this.registerOutput("xyz",xa.Vector3),this.registerOutput("xy",xa.Vector2),this.registerOutput("zw",xa.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\n`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`,e}}ee("BABYLON.VectorMergerBlock",Za);class Ja extends wa{constructor(e){super(e,ba.Neutral),this.sourceRange=new ue(-1,1),this.targetRange=new ue(0,1),this.registerInput("input",xa.AutoDetect),this.registerInput("sourceMin",xa.Float,!0),this.registerInput("sourceMax",xa.Float,!0),this.registerInput("targetMin",xa.Float,!0),this.registerInput("targetMax",xa.Float,!0),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${i});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=ue.FromArray(e.sourceRange),this.targetRange=ue.FromArray(e.targetRange)}}qe([Ba("From",Sa.Vector2)],Ja.prototype,"sourceRange",void 0),qe([Ba("To",Sa.Vector2)],Ja.prototype,"targetRange",void 0),ee("BABYLON.RemapBlock",Ja);class el extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(xa.Float),this.right.acceptedConnectionPointTypes.push(xa.Float),this._connectionObservers=[this.left.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.left.onDisconnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onDisconnectionObservable.add((()=>this._updateInputOutputTypes()))]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===xa.Int||this.left.type===xa.Float&&this.right.type!==xa.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[xa.Int,xa.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==xa.Int&&t.type!==xa.Float||e.acceptedConnectionPointTypes.push(xa.Vector2,xa.Vector3,xa.Vector4,xa.Color3,xa.Color4,xa.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}}class tl extends el{constructor(e){super(e)}getClassName(){return"MultiplyBlock"}_buildBlock(e){return super._buildBlock(e),e.compilationString+=this._declareOutput(this.output,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\n`,this}}var il;ee("BABYLON.MultiplyBlock",tl),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(il||(il={}));class sl extends Oa{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class rl{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:de.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:de.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:de.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:de.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let s=0;for(const i of t){if(i.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=de.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new de(10,10,10),this.onAnimationEnd=null,this.blendMode=rl.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new ue(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new de(0,0,0),this._useLogarithmicDepth=!1,this.gravity=de.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new Ee(1,1,1,1),this.color2=new Ee(1,1,1,1),this.colorDead=new Ee(0,0,0,1),this.textureMask=new Ee(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new sl,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new de(0,1,0),i=new de(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,s=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,s){throw new Error("Method not implemented.")}}rl.BLENDMODE_ONEONE=0,rl.BLENDMODE_STANDARD=1,rl.BLENDMODE_ADD=2,rl.BLENDMODE_MULTIPLY=3,rl.BLENDMODE_MULTIPLYADD=4;class nl extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("rgba",xa.Color4,!0),this.registerInput("rgb ",xa.Color3,!0),this.registerOutput("rgb",xa.Color3),this.registerOutput("r",xa.Float),this.registerOutput("g",xa.Float),this.registerOutput("b",xa.Float),this.registerOutput("a",xa.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb;\n`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.r;\n`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.g;\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b;\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.a;\n`),this}}ee("BABYLON.ColorSplitterBlock",nl),ki.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1);const r=this._gl,n=new Pi(this,Ai.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const o=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);1!==s.type||this._caps.textureFloat||(s.type=0,we.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,o.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const a=r.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),i.setTextures(n),i};const ol={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class al{constructor(e,t=ol){this._fullscreenViewport=new jr(0,0,1,1);const i=t.positions??ol.positions,s=t.indices??ol.indices;this.engine=e,this._vertexBuffers={[ys.PositionKind]:new ys(e,i,ys.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[ys.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[ys.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class ll{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new X;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new Fi(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new Ti(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const hl="passPixelShader",cl="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";bi.ShadersStore[hl]=cl;const ul=hl,dl=cl;class _l{static _CreateDumpRenderer(){if(!_l._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new ki(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new ki(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;const s=new al(t),r=new ll({engine:t,name:ul,fragmentShader:dl,samplerNames:["textureSampler"]});_l._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return _l._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const a=await i.readPixels(0,0,e,t),l=new Uint8Array(a.buffer);_l.DumpData(e,t,l,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,a){return new Promise((l=>{_l.DumpData(e,t,i,(e=>l(e)),s,r,n,o,a)}))}static DumpData(e,t,i,s,r="image/png",n,o=!1,a=!1,l){const h=_l._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*xe.Clamp(s))}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),a?hs.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),r,l):hs.EncodeScreenshotCanvasData(h.canvas,s,r,n,l),c.dispose()}static Dispose(){_l._DumpToolsEngine&&(_l._DumpToolsEngine.wrapper.dispose(),_l._DumpToolsEngine.renderer.dispose(),_l._DumpToolsEngine.engine.dispose()),_l._DumpToolsEngine=null}}hs.DumpData=_l.DumpData,hs.DumpDataAsync=_l.DumpDataAsync,hs.DumpFramebuffer=_l.DumpFramebuffer;class pl extends Vo{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=Z(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new X,this.onAfterUnbindObservable=new X,this.onBeforeRenderObservable=new X,this.onAfterRenderObservable=new X,this.onClearObservable=new X,this.onResizeObservable=new X,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=de.Zero(),!(i=this.getScene()))return;const x=this.getScene().getEngine();this._gammaSpace=v,this._coordinatesMode=Vo.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=x.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new Ps(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:_,creationFlags:p,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:g,label:this.name},this.samplingMode===Vo.NEAREST_SAMPLINGMODE&&(this.wrapU=Vo.CLAMP_ADDRESSMODE,this.wrapV=Vo.CLAMP_ADDRESSMODE),d||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Vo.INVCUBIC_MODE,this._textureMatrix=fe.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;return this._size.depth||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){const n=this.getScene();if(!n)return;const o=n.getEngine();if(o._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&1===o.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let a=null;const l=this.renderList?this.renderList:n.getActiveMeshes().data,h=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(a=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,l,h)),a?this._prepareRenderingManager(a,a.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(l,h,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),a=l);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,a,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&_l.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&5===e&&o.generateMipMapsForCubemap(this._texture),o._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new pl(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===pl.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=pl.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}pl.REFRESHRATE_RENDER_ONCE=0,pl.REFRESHRATE_RENDER_ONEVERYFRAME=1,pl.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Vo._CreateRenderTargetTexture=(e,t,i,s,r)=>new pl(e,t,i,s);class fl{constructor(e){this.name=Rs.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(Rs.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){hs.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}bi.ShadersStore.proceduralVertexShader="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class ml extends Vo{constructor(e,t,i,s,r=null,n=!0,o=!1,a=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new X,this.onBeforeGenerationObservable=new X,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===r||r instanceof Vo?(this._options={},this._fallbackTexture=r):(this._options=r,this._fallbackTexture=r.fallbackTexture??null);let l=(s=this.getScene()||se.LastCreatedScene)._getComponent(Rs.NAME_PROCEDURALTEXTURE);l||(l=new fl(s),s._addComponent(l)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=a,this._generateMipMaps=n,this._drawWrapper=new Fi(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,n,a);this._texture=h.texture;const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[ys.PositionKind]=new ys(this._fullEngine,c,ys.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===pl.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=pl.REFRESHRATE_RENDER_ONCE)}reset(){this._drawWrapper.effect?.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady())return void e(this);const t=this.getEffect();t&&t.executeWhenCompiled((()=>{e(this)}))}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[ys.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,(()=>{this._rtWrapper?.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;i._debugPushGroup?.(`procedural texture generation for ${this.name}`,1);const s=i.currentViewport;if(this.isCube)for(let e=0;e<6;e++)i.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(uo.TriangleFillMode,0,6);else i.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(uo.TriangleFillMode,0,6);i.unBindFramebuffer(this._rtWrapper,this.isCube),s&&i.setViewport(s),this.isCube&&i.generateMipMapsForCubemap(this._texture),i._debugPopGroup?.(1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new ml(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){const e=this.getScene();if(!e)return;const t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[ys.PositionKind];i&&(i.dispose(),this._vertexBuffers[ys.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var gl;qe([st()],ml.prototype,"isEnabled",void 0),qe([st()],ml.prototype,"autoClear",void 0),qe([st()],ml.prototype,"_generateMipMaps",void 0),qe([st()],ml.prototype,"_size",void 0),qe([st()],ml.prototype,"refreshRate",null),ee("BABYLON.ProceduralTexture",ml),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(gl||(gl={}));class vl extends wa{constructor(e){super(e,ba.Neutral),this.operation=gl.Cos,this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case gl.Cos:i="cos";break;case gl.Sin:i="sin";break;case gl.Abs:i="abs";break;case gl.Exp:i="exp";break;case gl.Exp2:i="exp2";break;case gl.Round:i="round";break;case gl.Floor:i="floor";break;case gl.Ceiling:i="ceil";break;case gl.Sqrt:i="sqrt";break;case gl.Log:i="log";break;case gl.Tan:i="tan";break;case gl.ArcTan:i="atan";break;case gl.ArcCos:i="acos";break;case gl.ArcSin:i="asin";break;case gl.Fract:i="fract";break;case gl.Sign:i="sign";break;case gl.Radians:i="radians";break;case gl.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${gl[this.operation]};\n`}}ee("BABYLON.TrigonometryBlock",vl);const xl={effect:null,subMesh:null};class bl extends Oa{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Tl extends Ra{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"ReflectionTextureBlock"===e.getClassName()||"ReflectionBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||se.LastCreatedScene),this._buildId=Tl._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new fe,this._cachedWorldViewProjectionMatrix=new fe,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new X,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=il.Material,this.forceAlphaBlending=!1,this._options={emitComments:!1,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return hs.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&ba.Vertex&&this._addVertexOutputNode(e),e.target&ba.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(e.target&ba.Vertex&&this._removeVertexOutputNode(e),e.target&ba.Fragment&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=ba.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=ba.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,s=!0){(e.target===ba.VertexAndFragment||t.target===ba.Fragment&&e.target===ba.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const r=n.ownerBlock;r!==e&&this._processInitializeOnLink(r,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===ba.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;const s=this.getScene().getEngine(),r=this._mode===il.Particle;if(0===this._vertexOutputNodes.length&&!r)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new Ia,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=ba.Vertex,this._fragmentCompilationState=new Ia,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=ba.Fragment,this._sharedData=new Ma,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=r;const n=[],o=[];for(const e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);this.optimize();for(const e of n)e.build(this._vertexCompilationState,n);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of o)this._resetDualBlocks(e,this._buildId-1);for(const e of o)e.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Tl._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(we.Log("Vertex shader:"),we.Log(this._vertexCompilationState.compilationString),we.Log("Fragment shader:"),we.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const e of a)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(ys.NormalKind),t.TANGENT=e.isVerticesDataPresent(ys.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(ys.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let i=1;i<=6;++i){const s=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==s}const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;ao(this.getScene(),t,!a),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate((e=>"PrePassOutputBlock"===e.getClassName())),t=[4];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t):t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter((e=>"PrePassTextureBlock"===e.getClassName())),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const e of t)i.texturesRequired.includes(e)||i.texturesRequired.push(e);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==il.PostProcess?(we.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,a=5){let l=this.name+this._buildId;const h=new bl,c=new Sn(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),Ti.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new qa(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete Ti.ShadersStore[l+"VertexShader"],delete Ti.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&(Ti.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Vi.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==il.ProceduralTexture)return we.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new ml(i,e,null,t),r=new Sn(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new bl,o=this._processDefines(r,n);Ti.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ys.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(a);let l=this._buildId;return s.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete Ti.ShadersStore[i+"VertexShader"],delete Ti.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);const e=this._processDefines(r,n);e&&(Ti.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Vi.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ys.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),e?.fallbacks,void 0),s._setEffect(a)}))),this._checkInternals(a)})),s}_createEffectForParticles(e,t,i,s,r,n,o,a=""){let l=this.name+this._buildId+"_"+t;n||(n=new bl),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new Sn(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=a;if(!r){const a=this._processDefines(o,n);Ti.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t),u=c.join("\n"),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,a?.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add((r=>{h!==this._buildId&&(delete Ti.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t);const d=c.join("\n");d!==u&&(n.markAllAsDirty(),u=d);const _=this._processDefines(o,n);if(_)return Ti.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,_?.fallbacks,i,s,e),e.setCustomEffect(r,t),void this._createEffectForParticles(e,t,i,s,r,n,o,a);this._checkInternals(r)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===il.Particle?(this._createEffectForParticles(e,rl.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,rl.BLENDMODE_MULTIPLY,t,i)):we.Log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===il.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):we.Log("Incompatible material mode")}_processDefines(e,t,i=!1,s){let r=null;if(lo(this.getScene(),t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((s=>{s.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((r=>{r.prepareDefines(e,this,t,i,s)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const s=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,s)}));const n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===n.indexOf(e)&&n.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new ja;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),r={lightDisposed:i,uniformBuffers:s,mergedUniforms:n,mergedSamplers:o,fallbacks:a}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const e=s.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(s);this._animationFrame=e}}const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new bl);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,n,i))))return!1;const a=this._processDefines(e,n,i,t);if(a){const e=t.effect,i=n.toString();let r=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS}},o);if(r)if(this._onEffectCreatedObservable&&(xl.effect=r,xl.subMesh=t,this._onEffectCreatedObservable.notifyObservers(xl)),this.allowShaderHotSwapping&&e&&!r.isReady()){if(r=e,n.markAsUnprocessed(),a.lightDisposed)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(r,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return`// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,i,t.visibility),o=this._sharedData;if(n){for(const e of o.bindableBlocks)e.bind(r,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);for(const e of o.inputBlocks)e._transmit(r,s,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Tl._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:Tl.EditorURL;hs.LoadBabylonScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()}))}else this._createNodeEditor(e?.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Wa("Position");e.setAsAttribute("position");const t=new Wa("World");t.setAsSystemValue(Ea.World);const i=new Na("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Wa("ViewProjection");s.setAsSystemValue(Ea.ViewProjection);const r=new Na("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new Fa("VertexOutput");r.connectTo(n);const o=new Wa("color");o.value=new Ee(.8,.8,.8,1);const a=new La("FragmentOutput");o.connectTo(a),this.addOutputNode(n),this.addOutputNode(a),this._mode=il.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Wa("Position");e.setAsAttribute("position2d");const t=new Wa("Constant1");t.isConstant=!0,t.value=1;const i=new Za("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Fa("VertexOutput");i.connectTo(s);const r=new Wa("Scale");r.visibleInInspector=!0,r.value=new ue(1,1);const n=new Ja("uv0");e.connectTo(n);const o=new tl("UV scale");n.connectTo(o),r.connectTo(o);const a=new Ha("CurrentScreen");o.connectTo(a),a.texture=new Vo("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new La("FragmentOutput");a.connectTo(l,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(l),this._mode=il.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Wa("Position");e.setAsAttribute("position2d");const t=new Wa("Constant1");t.isConstant=!0,t.value=1;const i=new Za("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Fa("VertexOutput");i.connectTo(s);const r=new Wa("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=Aa.Time,r.isConstant=!1;const n=new Wa("Color3");n.value=new Ce(1,1,1),n.isConstant=!1;const o=new La("FragmentOutput"),a=new Za("VectorMerger");a.visibleInInspector=!1;const l=new vl("Cos");l.operation=gl.Cos,e.connectTo(a),r.output.connectTo(l.input),l.output.connectTo(a.z),a.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=il.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Wa("uv");e.setAsAttribute("particle_uv");const t=new Xa("ParticleTexture");e.connectTo(t);const i=new Wa("Color");i.setAsAttribute("particle_color");const s=new tl("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new Ya("ParticleRampGradient");s.connectTo(r);const n=new nl("ColorSplitter");i.connectTo(n);const o=new Qa("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const a=new La("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=il.Particle}async loadAsync(e,t=""){return Tl.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,t);const s=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\n`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${il[this.mode]};\n`;for(const s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));for(const t of s)t.isInput&&-1===e.indexOf(t)&&(r+=t._dumpCode(i,e));e=[],r+="\n// Connections\n";for(const t of this._vertexOutputNodes)r+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)r+=t._dumpCodeForOutputConnections(e);r+="\n// Output nodes\n";for(const e of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;for(const e of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;return r+="nodeMaterial.build();\n",r}serialize(e){const t=e?{}:yt.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}parseSerializedObject(e,t="",i=!1){i||this.clear();const s={};for(const i of e.blocks){const e=te(i.customType);if(e){const r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,i=t._tempEntryPointUniqueId;i&&s[i].attachToEndpoint(t)}for(let t=0;tnew Tl(e,this.getScene(),this.options)),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach((t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise(((e,t)=>{i.onLoadedObservable.addOnce((()=>{e()})),i.onErrorObservable.addOnce((e=>{t(e)}))})))})),Promise.all(e)}static Parse(e,t,i=""){const s=yt.Parse((()=>new Tl(e.name,t)),e,t,i);return s.parseSerializedObject(e,i),s.build(),s}static async ParseFromFileAsync(e,t,i,s="",r=!1,n){const o=n??new Tl(e,i),a=await i._loadFileAsync(t),l=JSON.parse(a);return o.parseSerializedObject(l,s),r||o.build(),o}static ParseFromSnippetAsync(e,t=se.LastCreatedScene,i="",s,r=!1,n=!1){return"_BLANK"===e?Promise.resolve(Tl.CreateDefault("blank",t)):new Promise(((o,a)=>{const l=new At;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const h=JSON.parse(JSON.parse(l.responseText).jsonPayload),c=JSON.parse(h.nodeMaterial);s||((s=yt.Parse((()=>new Tl(e,t)),c,t,i)).uniqueId=t.getUniqueId()),s.parseSerializedObject(c),s.snippetId=e;try{r||s.build()}catch(e){a(e)}n?s.whenTexturesReadyAsync().then((()=>{o(s)})).catch((e=>{a(e)})):o(s)}else a("Unable to load the snippet "+e)})),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()}))}static CreateDefault(e,t){const i=new Tl(e,t);return i.setToDefault(),i.build(),i}}function yl(e){const t=e.sideOrientation||cn.DEFAULTSIDE,i=e.radius||1,s=void 0===e.flat||e.flat,r=0|(e.subdivisions||4),n=e.radiusX||i,o=e.radiusY||i,a=e.radiusZ||i,l=(1+Math.sqrt(5))/2,h=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],p=[],f=[],m=[],g=[];let v=0;const x=new Array(3),b=new Array(3);let T;for(T=0;T<3;T++)x[T]=de.Zero(),b[T]=ue.Zero();for(let e=0;e<20;e++){for(T=0;T<3;T++){const t=c[3*e+T];x[T].copyFromFloats(h[3*u[t]],h[3*u[t]+1],h[3*u[t]+2]),x[T].normalize(),b[T].copyFromFloats(.134765625*d[2*t]+.05859375+-.0390625*_[e],.2333984375*d[2*t+1]+.025390625+.01953125*_[e])}const t=(e,t,i,l)=>{const h=de.Lerp(x[0],x[2],t/r),c=de.Lerp(x[1],x[2],t/r),u=r===t?x[2]:de.Lerp(h,c,e/(r-t));let d;if(u.normalize(),s){const e=de.Lerp(x[0],x[2],l/r),t=de.Lerp(x[1],x[2],l/r);d=de.Lerp(e,t,i/(r-l))}else d=new de(u.x,u.y,u.z);d.x/=n,d.y/=o,d.z/=a,d.normalize();const _=ue.Lerp(b[0],b[2],t/r),T=ue.Lerp(b[1],b[2],t/r),y=r===t?b[2]:ue.Lerp(_,T,e/(r-t));f.push(u.x*n,u.y*o,u.z*a),m.push(d.x,d.y,d.z),g.push(y.x,dn.UseOpenGLOrientationForUV?1-y.y:y.y),p.push(v),v++};for(let e=0;eSl(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(El||(El={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(Al||(Al={}));const Pl=[Al.WRIST,Al.THUMB_METACARPAL,Al.THUMB_PHALANX_PROXIMAL,Al.THUMB_PHALANX_DISTAL,Al.THUMB_TIP,Al.INDEX_FINGER_METACARPAL,Al.INDEX_FINGER_PHALANX_PROXIMAL,Al.INDEX_FINGER_PHALANX_INTERMEDIATE,Al.INDEX_FINGER_PHALANX_DISTAL,Al.INDEX_FINGER_TIP,Al.MIDDLE_FINGER_METACARPAL,Al.MIDDLE_FINGER_PHALANX_PROXIMAL,Al.MIDDLE_FINGER_PHALANX_INTERMEDIATE,Al.MIDDLE_FINGER_PHALANX_DISTAL,Al.MIDDLE_FINGER_TIP,Al.RING_FINGER_METACARPAL,Al.RING_FINGER_PHALANX_PROXIMAL,Al.RING_FINGER_PHALANX_INTERMEDIATE,Al.RING_FINGER_PHALANX_DISTAL,Al.RING_FINGER_TIP,Al.PINKY_FINGER_METACARPAL,Al.PINKY_FINGER_PHALANX_PROXIMAL,Al.PINKY_FINGER_PHALANX_INTERMEDIATE,Al.PINKY_FINGER_PHALANX_DISTAL,Al.PINKY_FINGER_TIP],Rl={[El.WRIST]:[Al.WRIST],[El.THUMB]:[Al.THUMB_METACARPAL,Al.THUMB_PHALANX_PROXIMAL,Al.THUMB_PHALANX_DISTAL,Al.THUMB_TIP],[El.INDEX]:[Al.INDEX_FINGER_METACARPAL,Al.INDEX_FINGER_PHALANX_PROXIMAL,Al.INDEX_FINGER_PHALANX_INTERMEDIATE,Al.INDEX_FINGER_PHALANX_DISTAL,Al.INDEX_FINGER_TIP],[El.MIDDLE]:[Al.MIDDLE_FINGER_METACARPAL,Al.MIDDLE_FINGER_PHALANX_PROXIMAL,Al.MIDDLE_FINGER_PHALANX_INTERMEDIATE,Al.MIDDLE_FINGER_PHALANX_DISTAL,Al.MIDDLE_FINGER_TIP],[El.RING]:[Al.RING_FINGER_METACARPAL,Al.RING_FINGER_PHALANX_PROXIMAL,Al.RING_FINGER_PHALANX_INTERMEDIATE,Al.RING_FINGER_PHALANX_DISTAL,Al.RING_FINGER_TIP],[El.LITTLE]:[Al.PINKY_FINGER_METACARPAL,Al.PINKY_FINGER_PHALANX_PROXIMAL,Al.PINKY_FINGER_PHALANX_INTERMEDIATE,Al.PINKY_FINGER_PHALANX_DISTAL,Al.PINKY_FINGER_TIP]};class Il{get handMesh(){return this._handMesh}getHandPartMeshes(e){return Rl[e].map((e=>this._jointMeshes[Pl.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[Pl.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new X,this._jointTransforms=new Array(Pl.length),this._jointTransformMatrices=new Float32Array(16*Pl.length),this._tempJointMatrix=new fe,this._jointRadii=new Float32Array(Pl.length),this._scene=t[0].getScene();for(let e=0;e{e._doNotLoadControllerMesh=!0}))}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>{e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){const e=this._handMesh.skeleton;Pl.forEach(((i,s)=>{const r=e.getBoneIndexByName(t?t[i]:i);-1!==r&&e.bones[r].linkTransformNode(this._jointTransforms[s])}))}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=Pl.map((e=>s[e]||i.get(e)));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let i=0;i{const i=this._jointTransforms[t];fe.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const s=this._jointRadii[t]*this._jointScaleFactor,r=this._jointMeshes[t];r.isVisible=!this._handMesh&&!this._jointsInvisible,r.position.copyFrom(i.position),r.rotationQuaternion.copyFrom(i.rotationQuaternion),r.scaling.setAll(s),this._scene.useRightHandedSystem||(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){this._handMesh&&(e?(this._handMesh.skeleton?.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class Ml extends ua{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{const s=[],r=e.jointMeshes?.sourceMesh||Sl("jointParent",Ml._ICOSPHERE_PARAMS);r.isVisible=!!e.jointMeshes?.keepOriginalVisible;for(let t=0;t{const r={};Ml._RightHandGLB?.meshes[1]?.isDisposed()&&(Ml._RightHandGLB=null),Ml._LeftHandGLB?.meshes[1]?.isDisposed()&&(Ml._LeftHandGLB=null);const n=!(!Ml._RightHandGLB||!Ml._LeftHandGLB),o=await Promise.all([Ml._RightHandGLB||Pa.ImportMeshAsync("",Ml.DEFAULT_HAND_MODEL_BASE_URL,Ml.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Ml._LeftHandGLB||Pa.ImportMeshAsync("",Ml.DEFAULT_HAND_MODEL_BASE_URL,Ml.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Ml._RightHandGLB=o[0],Ml._LeftHandGLB=o[1];const a=await Tl.ParseFromFileAsync("handShader",Ml.DEFAULT_HAND_MODEL_SHADER_URL,e);a.needDepthPrePass=!0,a.transparencyMode=uo.MATERIAL_ALPHABLEND,a.alphaMode=2,a.build(!1);const l={base:Ce.FromInts(116,63,203),fresnel:Ce.FromInts(149,102,229),fingerColor:Ce.FromInts(177,130,255),tipFresnel:Ce.FromInts(220,200,255),...i?.handMeshes?.customColors},h={base:a.getBlockByName("baseColor"),fresnel:a.getBlockByName("fresnelColor"),fingerColor:a.getBlockByName("fingerColor"),tipFresnel:a.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const c=t._getBaseLayerWrapper()?.isMultiview;["left","right"].forEach((t=>{const i="left"==t?Ml._LeftHandGLB:Ml._RightHandGLB;if(!i)throw new Error("Could not load hand model");const s=i.meshes[1];s._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,c||(s.material=a.clone(`${t}HandShaderClone`,!0)),s.isVisible=!1,r[t]=s,n||e.useRightHandedSystem||i.meshes[1].rotate(_r.Y,Math.PI)})),a.dispose(),s({left:r.left,right:r.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[Al.WRIST]:`wrist_${t}`,[Al.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[Al.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[Al.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[Al.THUMB_TIP]:`thumb_tip_${t}`,[Al.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[Al.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[Al.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[Al.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[Al.INDEX_FINGER_TIP]:`index_tip_${t}`,[Al.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[Al.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[Al.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[Al.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[Al.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[Al.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[Al.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[Al.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[Al.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[Al.RING_FINGER_TIP]:`ring_tip_${t}`,[Al.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[Al.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[Al.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[Al.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[Al.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new X,this.onHandRemovedObservable=new X,this._attachHand=e=>{if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const t=e.inputSource.handedness,i=new Il(e,this._handResources.jointMeshes[t],this._handResources.handMeshes&&this._handResources.handMeshes[t],this._handResources.rigMappings&&this._handResources.rigMappings[t],this.options.handMeshes?.meshesUseLeftHandedCoordinates,this.options.jointMeshes?.invisible,this.options.jointMeshes?.scaleFactor);this._attachedHands[e.uniqueId]=i,this._trackingHands[t]=i,this.onHandAddedObservable.notifyObservers(i)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},s={};[[i.rigMapping.left,e],[i.rigMapping.right,s]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[Pl[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:s}}}attach(){return!!super.attach()&&(this._handResources={jointMeshes:Ml._GenerateTrackedJointMeshes(this.options),handMeshes:this.options.handMeshes?.customMeshes||null,rigMappings:this.options.handMeshes?.customRigMappings||null},this.options.handMeshes?.customMeshes||this.options.handMeshes?.disableDefaultMeshes||(Ml._GenerateDefaultHandMeshesAsync(se.LastCreatedScene,this._xrSessionManager,this.options).then((e=>{this._handResources.handMeshes=e,this._handResources.rigMappings={left:Ml._GenerateDefaultHandMeshRigMapping("left"),right:Ml._GenerateDefaultHandMeshRigMapping("right")},this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),this._trackingHands.right?.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)})),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add((e=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor))}))),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){this._trackingHands.left?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),this._trackingHands.right?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){const i=this.getHandByControllerId(e);if(i){const s="left"==i.xrController.inputSource.handedness?"left":"right";this._trackingHands[s]?.xrController.uniqueId===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e,this.options.handMeshes?.disposeOnSessionEnd))),this.options.handMeshes?.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose()))),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)}dispose(){super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!this.options.handMeshes?.customMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Ml._RightHandGLB=null,Ml._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}var Ol,Dl,wl;Ml.Name=ha.HAND_TRACKING,Ml.Version=1,Ml.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",Ml.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",Ml.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",Ml.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",Ml._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},Ml._RightHandGLB=null,Ml._LeftHandGLB=null,ca.AddWebXRFeature(Ml.Name,((e,t)=>()=>new Ml(e,t)),Ml.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(Ol||(Ol={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(Dl||(Dl={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(wl||(wl={}));class Nl{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=wl.PALM_AND_GAZE,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=Ol.ULNAR_SIDE,this.zoneOrientationMode=Dl.HAND_ROTATION,this.nodeOrientationMode=Dl.HAND_ROTATION,this.handedness="none",this.lerpTime=100,this._zoneAxis[Ol.ABOVE_FINGER_TIPS]=new de(0,1,0),this._zoneAxis[Ol.RADIAL_SIDE]=new de(-1,0,0),this._zoneAxis[Ol.ULNAR_SIDE]=new de(1,0,0),this._zoneAxis[Ol.BELOW_WRIST]=new de(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(e="none"===this.handedness?this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh(Al.PINKY_FINGER_METACARPAL),i=e.getJointMesh(Al.MIDDLE_FINGER_METACARPAL),s=e.getJointMesh(Al.WRIST);if(s&&i&&t){const r={position:i.absolutePosition,quaternion:new pe,id:e.xrController.uniqueId},n=ge.Vector3[0],o=ge.Vector3[1],a=ge.Vector3[2];return n.copyFrom(i.absolutePosition).subtractInPlace(s.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),de.CrossToRef(n,o,o),de.CrossToRef(o,n,a),pe.FromLookDirectionLHToRef(o,n,r.quaternion),r}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=pe.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{const e=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,e){const i=ge.Vector3[0],s=this._scene.activeCamera;i.copyFrom(this._zoneAxis[this.targetZone]);const r=ge.Quaternion[0];if(s&&(this.zoneOrientationMode===Dl.LOOK_AT_CAMERA||this.nodeOrientationMode===Dl.LOOK_AT_CAMERA)){const t=ge.Vector3[1];t.copyFrom(s.position).subtractInPlace(e.position).normalize(),this._scene.useRightHandedSystem?pe.FromLookDirectionRHToRef(t,de.UpReadOnly,r):pe.FromLookDirectionLHToRef(t,de.UpReadOnly,r)}this.zoneOrientationMode===Dl.HAND_ROTATION?e.quaternion.toRotationMatrix(ge.Matrix[0]):r.toRotationMatrix(ge.Matrix[0]),de.TransformNormalToRef(i,ge.Matrix[0],i),i.scaleInPlace(this.targetOffset);const n=ge.Vector3[2],o=ge.Quaternion[1];n.copyFrom(e.position).addInPlace(i),this.nodeOrientationMode===Dl.HAND_ROTATION?o.copyFrom(e.quaternion):o.copyFrom(r);const a=Date.now()-t;de.SmoothToRef(this._node.position,n,a,this.lerpTime,this._node.position),pe.SmoothToRef(this._node.rotationQuaternion,o,a,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=e.id}this._setVisibility(e),t=Date.now()}))}_setVisibility(e){let t=!0,i=!0;const s=this._scene.activeCamera;if(s){const r=s.getForwardRay();if(this.handConstraintVisibility===wl.GAZE_FOCUS||this.handConstraintVisibility===wl.PALM_AND_GAZE){let t;i=!1,this._eyeTracking&&(t=this._eyeTracking.getEyeGaze()),t=t||r;const s=ge.Vector3[0];e?e.position.subtractToRef(t.origin,s):this._node.getAbsolutePosition().subtractToRef(t.origin,s);const n=de.Dot(s,t.direction),o=n*n;n>0&&s.lengthSquared()-o2*this.palmUpStrictness-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(t){try{this._eyeTracking=t.getEnabledFeature(ha.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(ha.HAND_TRACKING)}catch{hs.Error("Hand tracking must be enabled for the Hand Menu to work")}}else hs.Error("XR features manager must be available or provided directly for the Hand Menu to work")}}class Fl{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=de.Zero(),this.poleTargetPosition=de.Zero(),this.poleTargetLocalOffset=de.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=pe.Identity(),this._bone1Mat=fe.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=de.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const s=t.getParent();if(!s)return this._notEnoughInformation=!0,void we.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=s,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void we.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const r=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,r.x>r.y&&r.x>r.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone2Length=de.Distance(t,i),this._bone1Length=de.Distance(i,s)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone1Length=de.Distance(i,s)}this._bone1.getRotationMatrixToRef(lr.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Fl._TmpMats[0],s=Fl._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&de.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const r=Fl._TmpVecs[0],n=Fl._TmpVecs[1],o=Fl._TmpVecs[2],a=Fl._TmpVecs[3],l=Fl._TmpVecs[4],h=Fl._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,r),t.subtractToRef(r,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(r,a),a.normalize(),de.CrossToRef(a,l,n),n.normalize(),de.CrossToRef(a,n,o),o.normalize(),fe.FromXYZAxesToRef(o,a,n,i);const c=this._bone1Length,u=this._bone2Length;let d=de.Distance(r,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let _=(u*u+d*d-c*c)/(2*u*d),p=(d*d+c*c-u*u)/(2*d*c);_>1&&(_=1),p>1&&(p=1),_<-1&&(_=-1),p<-1&&(p=-1);const f=Math.acos(_),m=Math.acos(p);let g=-f-m;if(this._rightHandedSystem)fe.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(i,i),fe.RotationAxisToRef(this._bendAxis,m,s),s.multiplyToRef(i,i);else{const e=Fl._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,fe.RotationAxisToRef(e,-m,s),s.multiplyToRef(i,i)}this.poleAngle&&(fe.RotationAxisToRef(a,this.poleAngle,s),i.multiplyToRef(s,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||pe.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),pe.FromRotationMatrixToRef(i,h),pe.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,lr.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,lr.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,lr.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new pe),e.getRotationQuaternionToRef(lr.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Fl._TmpVecs=[de.Zero(),de.Zero(),de.Zero(),de.Zero(),de.Zero(),de.Zero()],Fl._TmpQuat=pe.Identity(),Fl._TmpMats=[fe.Identity(),fe.Identity()];class Bl{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,s){if(this.upAxis=de.Up(),this.upAxisSpace=lr.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=pe.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=de.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,s){if(s.adjustYaw&&(this.adjustYaw=s.adjustYaw),s.adjustPitch&&(this.adjustPitch=s.adjustPitch),s.adjustRoll&&(this.adjustRoll=s.adjustRoll),null!=s.maxYaw?this.maxYaw=s.maxYaw:this.maxYaw=Math.PI,null!=s.minYaw?this.minYaw=s.minYaw:this.minYaw=-Math.PI,null!=s.maxPitch?this.maxPitch=s.maxPitch:this.maxPitch=Math.PI,null!=s.minPitch?this.minPitch=s.minPitch:this.minPitch=-Math.PI,null!=s.slerpAmount&&(this.slerpAmount=s.slerpAmount),null!=s.upAxis&&(this.upAxis=s.upAxis),null!=s.upAxisSpace&&(this.upAxisSpace=s.upAxisSpace),null!=s.yawAxis||null!=s.pitchAxis){let e=_r.Y,t=_r.X;null!=s.yawAxis&&(e=s.yawAxis.clone(),e.normalize()),null!=s.pitchAxis&&(t=s.pitchAxis.clone(),t.normalize());const i=de.Cross(t,e);this._transformYawPitch=fe.Identity(),fe.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==s.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=s.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=lr.BONE||(this.upAxisSpace=lr.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=Bl._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const s=Bl._TmpMats[0],r=Bl._TmpMats[1],n=this.mesh,o=e.getParent(),a=Bl._TmpVecs[1];a.copyFrom(this.upAxis),this.upAxisSpace==lr.BONE&&o?(this._transformYawPitch&&de.TransformCoordinatesToRef(a,this._transformYawPitchInv,a),o.getDirectionToRef(a,this.mesh,a)):this.upAxisSpace==lr.LOCAL&&(n.getDirectionToRef(a,a),1==n.scaling.x&&1==n.scaling.y&&1==n.scaling.z||a.normalize());let l=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(l=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),l||h){const e=Bl._TmpMats[2],s=Bl._TmpMats[3];if(this.upAxisSpace==lr.BONE&&1==a.y&&o)o.getRotationMatrixToRef(lr.WORLD,this.mesh,e);else if(this.upAxisSpace!=lr.LOCAL||1!=a.y||o){let t=Bl._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&de.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),o?o.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);const i=de.Cross(a,t);i.normalize(),t=de.Cross(i,a),fe.FromXYZAxesToRef(i,a,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(s);let r=null;if(h){const n=Bl._TmpVecs[3];i.subtractToRef(t,n),de.TransformCoordinatesToRef(n,s,n),r=Math.sqrt(n.x*n.x+n.z*n.z);const o=Math.atan2(n.y,r);let a=o;o>this._maxPitch?(n.y=this._maxPitchTan*r,a=this._maxPitch):othis._maxYaw||aMath.PI?this._isAngleBetween(o,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,l=this._maxYaw):this._isAngleBetween(o,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*r,n.x=this._minYawSin*r,l=this._minYaw):a>this._maxYaw?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,o<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):aMath.PI){const e=Bl._TmpVecs[8];e.copyFrom(_r.Z),this._transformYawPitch&&de.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=Bl._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),de.TransformCoordinatesToRef(e,t,e),de.TransformCoordinatesToRef(e,s,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,o)>this._getAngleBetween(i,this._midYawConstraint)){null==r&&(r=Math.sqrt(n.x*n.x+n.z*n.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e{const e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(ys.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(ys.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(ys.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),ys.prototype._rebuild=function(){this._buffer?._rebuild(),this._alignedBuffer?._rebuild()},ys.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._alignedBuffer?.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},ys.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},ys.prototype._alignBuffer=function(){const e=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4==0&&this.byteOffset%4==0||!e)return;const t=ys.GetTypeByteLength(this.type),i=this.byteStride+3&-4,s=i/t,r=this._maxVerticesCount,n=r*i/t;let o,a;if(Array.isArray(e)){const t=new Float32Array(e);o=new DataView(t.buffer,t.byteOffset,t.byteLength)}else o=e instanceof ArrayBuffer?new DataView(e,0,e.byteLength):new DataView(e.buffer,e.byteOffset,e.byteLength);a=this.type===ys.BYTE?new Int8Array(n):this.type===ys.UNSIGNED_BYTE?new Uint8Array(n):this.type===ys.SHORT?new Int16Array(n):this.type===ys.UNSIGNED_SHORT?new Uint16Array(n):this.type===ys.INT?new Int32Array(n):this.type===ys.UNSIGNED_INT?new Uint32Array(n):new Float32Array(n);const l=this.getSize();let h=this.byteOffset;for(let e=0;e{if(t.type!==Ms.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===Xs.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ms.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}qe([st()],Vl.prototype,"wheelPrecisionX",void 0),qe([st()],Vl.prototype,"wheelPrecisionY",void 0),qe([st()],Vl.prototype,"wheelPrecisionZ",void 0);class Ul{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const o=n.event,a="touch"===o.pointerType;if(n.type!==Ms.POINTERMOVE&&-1===this.buttons.indexOf(o.button))return;const l=o.target;if(this._altKey=o.altKey,this._ctrlKey=o.ctrlKey,this._metaKey=o.metaKey,this._shiftKey=o.shiftKey,this._buttonsPressed=o.buttons,t.isPointerLock){const e=o.movementX,t=o.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==Ms.POINTERDOWN&&a&&this._pointA?.pointerId!==o.pointerId&&this._pointB?.pointerId!==o.pointerId)return;if(n.type!==Ms.POINTERDOWN||-1!==this._currentActiveButton&&!a)if(n.type===Ms.POINTERDOUBLETAP)this.onDoubleTap(o.pointerType);else if(n.type!==Ms.POINTERUP||this._currentActiveButton!==o.button&&!a){if(n.type===Ms.POINTERMOVE)if(e||o.preventDefault(),this._pointA&&null===this._pointB){const e=o.clientX-this._pointA.x,t=o.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=o.clientX,this._pointA.y=o.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===o.pointerId?this._pointA:this._pointB;e.x=o.clientX,e.y=o.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:o.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,s,a,r,l),r=l,s=a}}else{try{l?.releasePointerCapture(o.pointerId)}catch(e){}a||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==o.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==o.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==s||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(o),e||o.preventDefault()}else{try{l?.setPointerCapture(o.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType};else{if(null!==this._pointB)return;this._pointB={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType}}-1!==this._currentActiveButton||a||(this._currentActiveButton=o.button),this.onButtonDown(o),e||(o.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ms.POINTERDOWN|Ms.POINTERUP|Ms.POINTERMOVE|Ms.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&hs.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&hs.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}qe([st()],Ul.prototype,"buttons",void 0);var Gl,zl,Wl,Hl,Xl,Yl,Ql={};class jl{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?we.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!Kr.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const i=this.attached[e],s=yt.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=Ql[e];if(i){const s=t[e],r=yt.Parse((()=>new i),s,null);this.add(r)}}}else for(const t in this.attached){const i=Ql[this.attached[t].getClassName()];if(i){const s=yt.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class Kl{constructor(e,t){this.x=e,this.y=t}}class $l{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=$l.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}$l.GAMEPAD=0,$l.GENERIC=1,$l.XBOX=2,$l.POSE_ENABLED=3,$l.DUALSHOCK=4;class ql extends $l{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new X,this.onButtonUpObservable=new X,this.type=$l.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==$l.POSE_ENABLED&&(this.gamepad&&e.type!==$l.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType($l.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}qe([st()],Zl.prototype,"gamepadRotationSensibility",void 0),qe([st()],Zl.prototype,"gamepadMoveSensibility",void 0),Ql.ArcRotateCameraGamepadInput=Zl;class Jl{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===Ns.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ms.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===Xs.DOM_DELTA_LINE?40:1,n=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=xe.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else s=n/(40*this.wheelPrecision);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ms.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=ir.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,fe.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=de.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/is&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,r=this._getPosition(),n=ge.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(s),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}th.MinimumRadiusForPinch=.001,qe([st()],th.prototype,"buttons",void 0),qe([st()],th.prototype,"angularSensibilityX",void 0),qe([st()],th.prototype,"angularSensibilityY",void 0),qe([st()],th.prototype,"pinchPrecision",void 0),qe([st()],th.prototype,"pinchDeltaPercentage",void 0),qe([st()],th.prototype,"useNaturalPinchZoom",void 0),qe([st()],th.prototype,"pinchZoom",void 0),qe([st()],th.prototype,"panningSensibility",void 0),qe([st()],th.prototype,"multiTouchPanning",void 0),qe([st()],th.prototype,"multiTouchPanAndZoom",void 0),Ql.ArcRotateCameraPointersInput=th;class ih extends jl{constructor(e){super(e)}addMouseWheel(){return this.add(new eh),this}addPointers(){return this.add(new th),this}addKeyboard(){return this.add(new Jl),this}}ih.prototype.addVRDeviceOrientation=function(){return this.add(new sh),this};class sh{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):hs.Warn("Permission not granted.")})).catch((e=>{hs.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Ql.ArcRotateCameraVRDeviceOrientationInput=sh;class rh{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(t.type===Ns.KEYDOWN)-1===this.keysForward.indexOf(i.keyCode)&&-1===this.keysBackward.indexOf(i.keyCode)&&-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(e)}),Ms.POINTERDOWN|Ms.POINTERUP|Ms.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)}))}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==Ms.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const s=t.target;if(e.type===Ms.POINTERDOWN){try{s?.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===Ms.POINTERUP){try{s?.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===Ms.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const s=t.clientX-this._previousPosition.x,r=t.clientY-this._previousPosition.y;this._rotateCamera(s,r),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=(e*=i._calculateHandednessMultiplier())/this.angularSensibility,r=t/this.angularSensibility,n=pe.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let o;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(o=pe.RotationAxis(_r.X,r),n.multiplyInPlace(o)),this.buttonsYaw.some((e=>e===this.activeButton))){o=pe.RotationAxis(_r.Y,s),n.multiplyInPlace(o);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(o=pe.RotationAxis(_r.Z,-s),i._trackRoll-=s,n.multiplyInPlace(o)),n.toEulerAnglesToRef(i.rotation)}}qe([st()],nh.prototype,"buttons",void 0),qe([st()],nh.prototype,"angularSensibility",void 0),Ql.FlyCameraMouseInput=nh;class oh{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===Ns.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)}))}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}qe([st()],oh.prototype,"keysHeightOffsetIncr",void 0),qe([st()],oh.prototype,"keysHeightOffsetDecr",void 0),qe([st()],oh.prototype,"keysHeightOffsetModifierAlt",void 0),qe([st()],oh.prototype,"keysHeightOffsetModifierCtrl",void 0),qe([st()],oh.prototype,"keysHeightOffsetModifierShift",void 0),qe([st()],oh.prototype,"keysRotationOffsetIncr",void 0),qe([st()],oh.prototype,"keysRotationOffsetDecr",void 0),qe([st()],oh.prototype,"keysRotationOffsetModifierAlt",void 0),qe([st()],oh.prototype,"keysRotationOffsetModifierCtrl",void 0),qe([st()],oh.prototype,"keysRotationOffsetModifierShift",void 0),qe([st()],oh.prototype,"keysRadiusIncr",void 0),qe([st()],oh.prototype,"keysRadiusDecr",void 0),qe([st()],oh.prototype,"keysRadiusModifierAlt",void 0),qe([st()],oh.prototype,"keysRadiusModifierCtrl",void 0),qe([st()],oh.prototype,"keysRadiusModifierShift",void 0),qe([st()],oh.prototype,"heightSensibility",void 0),qe([st()],oh.prototype,"rotationSensibility",void 0),qe([st()],oh.prototype,"radiusSensibility",void 0),Ql.FollowCameraKeyboardMoveInput=oh;class ah{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ms.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&we.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=.01*r*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=.01*r*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=.01*r*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ms.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}qe([st()],ah.prototype,"axisControlRadius",void 0),qe([st()],ah.prototype,"axisControlHeight",void 0),qe([st()],ah.prototype,"axisControlRotation",void 0),qe([st()],ah.prototype,"wheelPrecision",void 0),qe([st()],ah.prototype,"wheelDeltaPercentage",void 0),Ql.FollowCameraMouseWheelInput=ah;class lh extends Ul{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,s,r,n){if(0===i&&null===r)return;if(0===s&&null===n)return;let o=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&we.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&we.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&we.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}qe([st()],lh.prototype,"angularSensibilityX",void 0),qe([st()],lh.prototype,"angularSensibilityY",void 0),qe([st()],lh.prototype,"pinchPrecision",void 0),qe([st()],lh.prototype,"pinchDeltaPercentage",void 0),qe([st()],lh.prototype,"axisXControlRadius",void 0),qe([st()],lh.prototype,"axisXControlHeight",void 0),qe([st()],lh.prototype,"axisXControlRotation",void 0),qe([st()],lh.prototype,"axisYControlRadius",void 0),qe([st()],lh.prototype,"axisYControlHeight",void 0),qe([st()],lh.prototype,"axisYControlRotation",void 0),qe([st()],lh.prototype,"axisPinchControlRadius",void 0),qe([st()],lh.prototype,"axisPinchControlHeight",void 0),qe([st()],lh.prototype,"axisPinchControlRotation",void 0),Ql.FollowCameraPointersInput=lh;class hh{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===Ns.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const r=s.event,n="touch"===r.pointerType;if(!this.touchEnabled&&n)return;if(s.type!==Ms.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const o=r.target;if(s.type===Ms.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{o?.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===Ms.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o?.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===Ms.POINTERMOVE&&(this._activePointerId===r.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(r.clientX-this._previousPosition.x)*t,s=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=s/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:s}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),r=i.movementX*s;this.camera.cameraRotation.y+=r/this.angularSensibility;const n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ms.POINTERDOWN|Ms.POINTERUP|Ms.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}qe([st()],ch.prototype,"buttons",void 0),qe([st()],ch.prototype,"angularSensibility",void 0),Ql.FreeCameraMouseInput=ch,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(Gl||(Gl={}));class uh extends Vl{constructor(){super(...arguments),this._moveRelative=de.Zero(),this._rotateRelative=de.Zero(),this._moveScene=de.Zero(),this._wheelXAction=Gl.MoveRelative,this._wheelXActionCoordinate=hr.X,this._wheelYAction=Gl.MoveRelative,this._wheelYActionCoordinate=hr.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==Gl.MoveRelative||(this._wheelXAction=Gl.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Gl.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==Gl.MoveRelative||(this._wheelYAction=Gl.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Gl.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==Gl.MoveRelative||(this._wheelZAction=Gl.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Gl.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==Gl.RotateRelative||(this._wheelXAction=Gl.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Gl.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==Gl.RotateRelative||(this._wheelYAction=Gl.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Gl.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==Gl.RotateRelative||(this._wheelZAction=Gl.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Gl.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==Gl.MoveScene||(this._wheelXAction=Gl.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Gl.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==Gl.MoveScene||(this._wheelYAction=Gl.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Gl.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==Gl.MoveScene||(this._wheelZAction=Gl.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Gl.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=fe.Zero();this.camera.getViewMatrix().invertToRef(e);const t=de.Zero();de.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(0===e)return;if(null===t||null===i)return;let s=null;switch(t){case Gl.MoveRelative:s=this._moveRelative;break;case Gl.RotateRelative:s=this._rotateRelative;break;case Gl.MoveScene:s=this._moveScene}switch(i){case hr.X:s.set(e,0,0);break;case hr.Y:s.set(0,e,0);break;case hr.Z:s.set(0,0,e)}}}qe([st()],uh.prototype,"wheelXMoveRelative",null),qe([st()],uh.prototype,"wheelYMoveRelative",null),qe([st()],uh.prototype,"wheelZMoveRelative",null),qe([st()],uh.prototype,"wheelXRotateRelative",null),qe([st()],uh.prototype,"wheelYRotateRelative",null),qe([st()],uh.prototype,"wheelZRotateRelative",null),qe([st()],uh.prototype,"wheelXMoveScene",null),qe([st()],uh.prototype,"wheelYMoveScene",null),qe([st()],uh.prototype,"wheelZMoveScene",null),Ql.FreeCameraMouseWheelInput=uh;class dh{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=hs.IsSafari()}attachControl(e){e=hs.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r="mouse"===s.pointerType||this._isSafari&&void 0===s.pointerType;if(this.allowMouse||!r)if(i.type===Ms.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),1!==this._pointerPressed.length)return;t={x:s.clientX,y:s.clientY}}else if(i.type===Ms.POINTERUP){e||s.preventDefault();const i=this._pointerPressed.indexOf(s.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===Ms.POINTERMOVE){if(e||s.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(s.pointerId))return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ms.POINTERDOWN|Ms.POINTERUP|Ms.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new de(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);fe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(de.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}qe([st()],dh.prototype,"touchAngularSensibility",void 0),qe([st()],dh.prototype,"touchMoveSensibility",void 0),Ql.FreeCameraTouchInput=dh;class _h extends jl{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new hh),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new ch(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new uh,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new dh),this}clear(){super.clear(),this._mouseInput=null}}_h.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new ph,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class ph{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout((()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",r):hs.Warn("Permission not granted.")})).catch((e=>{hs.Error(e)})):window.addEventListener("deviceorientation",r)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new pe,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new X,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-hs.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?hs.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?hs.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?hs.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new pe(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new pe),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():hs.Warn("Permission not granted.")})).catch((e=>{hs.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(pe.RotationYawPitchRollToRef(hs.ToRadians(this._alpha),hs.ToRadians(this._beta),-hs.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Ql.FreeCameraDeviceOrientationInput=ph;class fh{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=fe.Identity(),this._deltaTransform=de.Zero(),this._vector3=de.Zero(),this._vector2=ue.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==$l.POSE_ENABLED&&(this.gamepad&&e.type!==$l.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType($l.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):fe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*s,0,-t.y*s),de.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}qe([st()],fh.prototype,"gamepadAngularSensibility",void 0),qe([st()],fh.prototype,"gamepadMoveSensibility",void 0),Ql.FreeCameraGamepadInput=fh,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(zl||(zl={}));class mh{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...mh._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,mh._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=zl.X,this._axisTargetedByUpAndDown=zl.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new ps,this.deltaPosition=de.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{mh._VJCanvasWidth=window.innerWidth,mh._VJCanvasHeight=window.innerHeight,mh.Canvas&&(mh.Canvas.width=mh._VJCanvasWidth,mh.Canvas.height=mh._VJCanvasHeight),mh._HalfWidth=mh._VJCanvasWidth/2},!mh.Canvas){window.addEventListener("resize",this._onResize,!1),mh.Canvas=document.createElement("canvas"),mh._VJCanvasWidth=window.innerWidth,mh._VJCanvasHeight=window.innerHeight,mh.Canvas.width=window.innerWidth,mh.Canvas.height=window.innerHeight,mh.Canvas.style.width="100%",mh.Canvas.style.height="100%",mh.Canvas.style.position="absolute",mh.Canvas.style.backgroundColor="transparent",mh.Canvas.style.top="0px",mh.Canvas.style.left="0px",mh.Canvas.style.zIndex="5",mh.Canvas.style.touchAction="none",mh.Canvas.setAttribute("touch-action","none");const e=mh.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");mh._VJCanvasContext=e,mh._VJCanvasContext.strokeStyle="#ffffff",mh._VJCanvasContext.lineWidth=2,document.body.appendChild(mh.Canvas)}mh._HalfWidth=mh.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&mh._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new ue(0,0),this._joystickPreviousPointerPos=new ue(0,0),this._joystickPointerStartPos=new ue(0,0),this._deltaJoystickVector=new ue(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},mh.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),mh.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),mh.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),mh.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),mh.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXmh._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):mh._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new ue(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?mh._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.strokeStyle=this._joystickColor,mh._VJCanvasContext.lineWidth=2,mh._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),mh._VJCanvasContext.stroke(),mh._VJCanvasContext.closePath(),mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.lineWidth=6,mh._VJCanvasContext.strokeStyle=this._joystickColor,mh._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),mh._VJCanvasContext.stroke(),mh._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?mh._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.strokeStyle=this._joystickColor,mh._VJCanvasContext.lineWidth=2,mh._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),mh._VJCanvasContext.stroke(),mh._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(mh._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.fillStyle="white",mh._VJCanvasContext.beginPath(),mh._VJCanvasContext.strokeStyle="red",mh._VJCanvasContext.lineWidth=6,mh._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),mh._VJCanvasContext.stroke(),mh._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){mh.Canvas&&(mh.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),mh.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),mh.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),mh.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(mh.Canvas),mh.Canvas=null),this._released=!0}}mh._GlobalJoystickIndex=0,mh._AlwaysVisibleSticks=0,_h.prototype.addVirtualJoystick=function(){return this.add(new gh),this};class gh{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=fe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=de.TransformCoordinates(new de(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new mh(!0),this._leftjoystick.setAxisForUpDown(zl.Z),this._leftjoystick.setAxisForLeftRight(zl.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new mh(!1),this._rightjoystick.setAxisForUpDown(zl.X),this._rightjoystick.setAxisForLeftRight(zl.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Ql.FreeCameraVirtualJoystickInput=gh,Ct.AddNodeConstructor("TargetCamera",((e,t)=>()=>new vh(e,de.Zero(),t)));class vh extends Kr{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=de.Zero(),this._tmpTargetVector=de.Zero(),this.cameraDirection=new de(0,0,0),this.cameraRotation=new ue(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new pe,this.rotation=new de(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=de.Zero(),this._initialFocalDistance=1,this._viewMatrix=fe.Zero(),this._camMatrix=fe.Zero(),this._cameraTransformMatrix=fe.Zero(),this._cameraRotationMatrix=fe.Zero(),this._referencePoint=new de(0,0,1),this._transformedReferencePoint=de.Zero(),this._deferredPositionUpdate=new de,this._deferredRotationQuaternionUpdate=new pe,this._deferredRotationUpdate=new de,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=de.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new pe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=K),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),fe.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&pe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(ge.Matrix[0]),de.TransformNormalToRef(this.cameraDirection,ge.Matrix[0],ge.Vector3[0]),this._deferredPositionUpdate.addInPlace(ge.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(pe.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x){this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>gn.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new _h(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=hs.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new de(0,0,0),this.cameraRotation=new ue(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?de.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=de.Zero(),this._transformedDirection=de.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}qe([lt()],xh.prototype,"ellipsoid",void 0),qe([lt()],xh.prototype,"ellipsoidOffset",void 0),qe([st()],xh.prototype,"checkCollisions",void 0),qe([st()],xh.prototype,"applyGravity",void 0),Ct.AddNodeConstructor("TouchCamera",((e,t)=>()=>new bh(e,de.Zero(),t)));class bh extends xh{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}Ct.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new Th(e,0,0,1,de.Zero(),t)));class Th extends vh{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new fe,this._upToYMatrix=new fe,this._upVector=de.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){fe.RotationAlignToRef(de.UpReadOnly,this._upVector,this._yToUpMatrix),fe.RotationAlignToRef(this._upVector,de.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Qo,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new jo,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Yo,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,de.Zero(),n,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=de.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=ue.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new fe,this.panningAxis=new de(1,1,0),this._transformedDirection=new de,this.mapPanning=!1,this.onMeshTargetChangedObservable=new X,this.checkCollisions=!1,this.collisionRadius=new de(.5,.5,.5),this._previousPosition=de.Zero(),this._collisionVelocity=de.Zero(),this._newPosition=de.Zero(),this._computationVector=de.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*o,this.radius*n,this.radius*r*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=de.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new ih(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=ue.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)}attachControl(e,t,i=!0,s=2){const r=arguments;t=hs.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||de.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||de.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=bo.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(void 0===e.min){const t=e||this.getScene().meshes;i=bo.MinMax(t),s=de.Distance(i.min,i.max)}else i=e,s=e.distance;this._target=bo.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Kr.RIG_MODE_STEREOSCOPIC_INTERLACED:case Kr.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new Th(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Kr.RIG_MODE_STEREOSCOPIC_INTERLACED:case Kr.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=de.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),o=n*r,a=.5*s*i,l=a*Math.sqrt(1+1/(o*o)),h=a*Math.sqrt(1+1/(n*n));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}qe([st()],Th.prototype,"alpha",void 0),qe([st()],Th.prototype,"beta",void 0),qe([st()],Th.prototype,"radius",void 0),qe([st()],Th.prototype,"overrideCloneAlphaBetaRadius",void 0),qe([lt("target")],Th.prototype,"_target",void 0),qe([ht("targetHost")],Th.prototype,"_targetHost",void 0),qe([st()],Th.prototype,"inertialAlphaOffset",void 0),qe([st()],Th.prototype,"inertialBetaOffset",void 0),qe([st()],Th.prototype,"inertialRadiusOffset",void 0),qe([st()],Th.prototype,"lowerAlphaLimit",void 0),qe([st()],Th.prototype,"upperAlphaLimit",void 0),qe([st()],Th.prototype,"lowerBetaLimit",void 0),qe([st()],Th.prototype,"upperBetaLimit",void 0),qe([st()],Th.prototype,"lowerRadiusLimit",void 0),qe([st()],Th.prototype,"upperRadiusLimit",void 0),qe([st()],Th.prototype,"inertialPanningX",void 0),qe([st()],Th.prototype,"inertialPanningY",void 0),qe([st()],Th.prototype,"pinchToPanMaxDistance",void 0),qe([st()],Th.prototype,"panningDistanceLimit",void 0),qe([lt()],Th.prototype,"panningOriginTarget",void 0),qe([st()],Th.prototype,"panningInertia",void 0),qe([st()],Th.prototype,"zoomToMouseLocation",null),qe([st()],Th.prototype,"zoomOnFactor",void 0),qe([at()],Th.prototype,"targetScreenOffset",void 0),qe([st()],Th.prototype,"allowUpsideDown",void 0),qe([st()],Th.prototype,"useInputToRestoreState",void 0),Ct.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new yh(e,de.Zero(),t)));class yh extends xh{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new pe,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new pe,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new pe),pe.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=_r.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new pe),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class Sh extends jl{constructor(e){super(e)}addKeyboard(){return this.add(new rh),this}addMouse(){return this.add(new nh),this}}class Ch extends vh{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new de(1,1,1),this.ellipsoidOffset=new de(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=de.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=de.Zero(),this._diffPosition=de.Zero(),this._newPosition=de.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>gn.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new Sh(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=hs.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new de(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?de.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=de.Zero(),this._transformedDirection=de.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}qe([lt()],Ch.prototype,"ellipsoid",void 0),qe([lt()],Ch.prototype,"ellipsoidOffset",void 0),qe([st()],Ch.prototype,"checkCollisions",void 0),qe([st()],Ch.prototype,"applyGravity",void 0);class Eh extends jl{constructor(e){super(e)}addKeyboard(){return this.add(new oh),this}addMouseWheel(){return this.add(new ah),this}addPointers(){return this.add(new lh),this}addVRDeviceOrientation(){return we.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Ct.AddNodeConstructor("FollowCamera",((e,t)=>()=>new Ah(e,de.Zero(),t))),Ct.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new Ph(e,0,0,1,null,t)));class Ah extends vh{constructor(e,t,i,s=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=s,this.inputs=new Eh(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=ge.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=hs.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,a=n-this.position.x,l=r.y+this.heightOffset-this.position.y,h=o-this.position.z;let c=a*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new de(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(r)}attachControl(e,t){t=hs.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}qe([st()],Ah.prototype,"radius",void 0),qe([st()],Ah.prototype,"lowerRadiusLimit",void 0),qe([st()],Ah.prototype,"upperRadiusLimit",void 0),qe([st()],Ah.prototype,"rotationOffset",void 0),qe([st()],Ah.prototype,"lowerRotationOffsetLimit",void 0),qe([st()],Ah.prototype,"upperRotationOffsetLimit",void 0),qe([st()],Ah.prototype,"heightOffset",void 0),qe([st()],Ah.prototype,"lowerHeightOffsetLimit",void 0),qe([st()],Ah.prototype,"upperHeightOffsetLimit",void 0),qe([st()],Ah.prototype,"cameraAcceleration",void 0),qe([st()],Ah.prototype,"maxCameraSpeed",void 0),qe([ht("lockedTargetId")],Ah.prototype,"lockedTarget",void 0);class Ph extends vh{constructor(e,t,i,s,r,n){super(e,de.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=de.Zero(),this.setMeshTarget(r)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}!function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Wl||(Wl={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Hl||(Hl={}));class Rh extends $l{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new X,this.onButtonUpObservable=new X,this.onPadDownObservable=new X,this.onPadUpObservable=new X,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=$l.XBOX,this._isXboxOnePad=s}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,Wl.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,Wl.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,Wl.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,Wl.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Wl.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Wl.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Wl.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Wl.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Wl.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Wl.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Hl.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Hl.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Hl.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Hl.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Xl||(Xl={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Yl||(Yl={}));class Ih extends $l{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new X,this.onButtonUpObservable=new X,this.onPadDownObservable=new X,this.onPadUpObservable=new X,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=$l.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Xl.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Xl.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Xl.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Xl.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Xl.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Xl.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Xl.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Xl.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Xl.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Xl.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Yl.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Yl.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Yl.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Yl.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class Mh{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new X,Lt()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new X((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=$l.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),s=-1!==e.id.search("Xbox One");return t=s||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Rh(e.id,e.index,e,s):i?new Ih(e.id,e.index,e):new ql(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch{-1===this._loggedErrors.indexOf(t.index)&&(hs.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&gn.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new Dh(e,de.Zero(),t)));class Dh extends bh{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}Kr._CreateDefaultParsedCamera=(e,t)=>new Dh(e,de.Zero(),t),Ct.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new wh(e,de.Zero(),t)));class wh extends Dh{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}bi.ShadersStore.passCubePixelShader="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";class Nh extends qa{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,a)}static _Parse(e,t,i,s){return yt.Parse((()=>new Nh(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}ee("BABYLON.PassPostProcess",Nh);class Fh extends qa{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"passCube",null,null,t,i,s,r,n,"#define POSITIVEX",o,void 0,null,a),this._face=0}static _Parse(e,t,i,s){return yt.Parse((()=>new Fh(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}gn._RescalePostProcessFactory=e=>new Nh("rescale",1,null,2,e,!1,0);bi.ShadersStore.anaglyphPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}";class Bh extends qa{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function Lh(e){e._rigCameras[0]._rigPostProcess=new Nh(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Bh(e.name+"_anaglyph",1,e._rigCameras)}ee("BABYLON.AnaglyphPostProcess",Bh),Ct.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new kh(e,0,0,1,de.Zero(),i.interaxial_distance,t)));class kh extends Th{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=()=>Lh(this),this.interaxialDistance=n,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Ct.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new Vh(e,de.Zero(),i.interaxial_distance,t)));class Vh extends xh{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Lh(this),this.interaxialDistance=i,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Ct.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new Uh(e,de.Zero(),i.interaxial_distance,t)));class Uh extends wh{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Lh(this),this.interaxialDistance=i,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Ct.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new Gh(e,de.Zero(),i.interaxial_distance,t)));class Gh extends Dh{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Lh(this),this.interaxialDistance=i,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}bi.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";class zh extends qa{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new ue(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new ue(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}class Wh extends qa{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,s,r,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,r,n,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new ue(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new ue(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function Hh(e){const t=e.cameraRigMode===Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===Kr.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new Nh(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new zh(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new jr(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new jr(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}Ct.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new Xh(e,0,0,1,de.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Xh extends Th{constructor(e,t,i,s,r,n,o,a){super(e,t,i,s,r,a),this._setRigMode=()=>Hh(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Ct.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Yh(e,de.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Yh extends xh{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hh(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Ct.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new Qh(e,de.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Qh extends wh{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hh(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Ct.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new jh(e,de.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class jh extends Dh{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Hh(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Kr.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class Kh extends Dh{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,s=1,r=.065){super(e,t,i),this._distanceBetweenEyes=r,this._distanceToProjectionPlane=s,this.setCameraRigMode(Kr.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=r}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new vh(e,de.Zero(),this.getScene()),i=new xn("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(fe.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new $h(e,de.Zero(),t)));class $h extends xh{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class qh{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return fe.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return fe.Translation(-e,0,0)}get leftPreViewMatrix(){return fe.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return fe.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new qh;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}bi.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";class Zh extends qa{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,Vo.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new ue(2,2/this.aspectRatio),this._scaleFactor=new ue(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new ue(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}bi.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";class Jh extends pl{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function ec(e,t){const i=new bs(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}gn.prototype.createMultiviewRenderTargetTexture=function(e,t,i,s){const r=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=r.createFramebuffer();const o=new Pi(this,Ai.Unknown,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,i),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.RGBA8,e,t,2)),n._colorTextureArray=i,s||(s=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,s),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=s,o.isReady=!0,n.setTextures(o),n._depthStencilTexture=o,n},gn.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},gn.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},Kr.prototype._useMultiviewToSingleView=!1,Kr.prototype._multiviewTexture=null,Kr.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Jh(this.getScene(),{width:e,height:t})):this._multiviewTexture=new Jh(this.getScene(),{width:e,height:t})};const tc=dr.prototype.createSceneUniformBuffer;dr.prototype._transformMatrixR=fe.Zero(),dr.prototype._multiviewSceneUbo=null,dr.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=ec(this.getEngine(),"scene_multiview")},dr.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?ec(this.getEngine(),e):tc.bind(this)(e)},dr.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,ge.Matrix[0]),sr.GetRightPlaneToRef(ge.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},dr.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",s._multiviewTexture)}))}}function sc(e,t){const i=t.vrCameraMetrics||qh.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new jr(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new fe,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new jr(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new fe,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new ic("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(we.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Zh("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Zh("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}Ct.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new rc(e,0,0,1,de.Zero(),t)));class rc extends Th{constructor(e,t,i,s,r,n,o=!0,a=qh.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=e=>sc(this,e),a.compensateDistortion=o,this.setCameraRigMode(Kr.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Ct.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new nc(e,de.Zero(),t)));class nc extends yh{constructor(e,t,i,s=!0,r=qh.GetDefault()){super(e,t,i),this._setRigMode=e=>sc(this,e),r.compensateDistortion=s,this.setCameraRigMode(Kr.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Ct.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new oc(e,de.Zero(),t)));class oc extends nc{constructor(e,t,i,s=!0,r=qh.GetDefault()){super(e,t,i,s,r),this._setRigMode=e=>sc(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class ac{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class lc{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,gn.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,gn.MarkAllMaterialsAsDirty(1))}}lc._DiffuseTextureEnabled=!0,lc._DetailTextureEnabled=!0,lc._DecalMapEnabled=!0,lc._AmbientTextureEnabled=!0,lc._OpacityTextureEnabled=!0,lc._ReflectionTextureEnabled=!0,lc._EmissiveTextureEnabled=!0,lc._SpecularTextureEnabled=!0,lc._BumpTextureEnabled=!0,lc._LightmapTextureEnabled=!0,lc._RefractionTextureEnabled=!0,lc._ColorGradingTextureEnabled=!0,lc._FresnelEnabled=!0,lc._ClearCoatTextureEnabled=!0,lc._ClearCoatBumpTextureEnabled=!0,lc._ClearCoatTintTextureEnabled=!0,lc._SheenTextureEnabled=!0,lc._AnisotropicTextureEnabled=!0,lc._ThicknessTextureEnabled=!0,lc._RefractionIntensityTextureEnabled=!0,lc._TranslucencyIntensityTextureEnabled=!0,lc._IridescenceTextureEnabled=!0;bi.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";bi.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";bi.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n";bi.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n";bi.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";bi.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";bi.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n";bi.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";bi.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";bi.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X};\n#endif\n#endif\n";bi.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";bi.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";bi.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n/* disable_uniformity_analysis */\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; ithis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[cc._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case En.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let t in r){let r="";for(const s of this._activePlugins){let o=s.getCustomCode(i)?.[t];if(o){if(s.resolveIncludes){if(null===n){const t=ui.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:bi.GetShadersRepository(t),includesShadersStore:bi.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,xi._ProcessIncludes(o,n,(e=>o=e))}r+=o+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=hc.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,n=new RegExp(t,e);let o=n.exec(i);for(;null!==o;){let e=r;for(let t=0;t{mc()}));const uc=[];let dc=!1,_c=null;function pc(e,t){dc||(_c=uo.OnEventObservable.add((e=>{for(const[,t]of uc)t(e)}),En.Created),dc=!0);const i=uc.filter((([t,i])=>t===e));i.length>0?i[0][1]=t:uc.push([e,t])}function fc(e){for(let t=0;t{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){yt.Clone((()=>e),this)}serialize(){return yt.Serialize(this)}parse(e,t,i){yt.Parse((()=>this),e,t,i)}}qe([st()],gc.prototype,"name",void 0),qe([st()],gc.prototype,"priority",void 0),qe([st()],gc.prototype,"resolveIncludes",void 0),qe([st()],gc.prototype,"registerForExtraEvents",void 0);class vc extends Oa{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class xc extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new vc,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=uo.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&lc.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&lc.DetailTextureEnabled&&this._isEnabled?(Un(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||this._texture&&lc.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Gn(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&lc.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}qe([rt("detailTexture"),it("_markAllSubMeshesAsTexturesDirty")],xc.prototype,"texture",void 0),qe([st()],xc.prototype,"diffuseBlendLevel",void 0),qe([st()],xc.prototype,"roughnessBlendLevel",void 0),qe([st()],xc.prototype,"bumpLevel",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],xc.prototype,"normalBlendMethod",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],xc.prototype,"isEnabled",void 0);const bc={effect:null,subMesh:null};class Tc extends Oa{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class yc extends Ra{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Ce(0,0,0),this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(1,1,1),this.emissiveColor=new Ce(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new ds(16),this._worldViewProjectionMatrix=fe.Zero(),this._globalAmbientColor=new Ce(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new xc(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new ac,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),yc.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),yc.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(yc.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(yc.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===uo.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==uo.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(En.GetDefineNames,this._eventInfo),t.materialDefines=new Tc(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();n._needNormals=Zn(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),no(r,n);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(ao(r,n,this.canRenderToMRT&&!a),oo(r,n,a),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let e=1;e<=6;++e)n["MAINUV"+e]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&yc.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Un(this._diffuseTexture,n,"DIFFUSE")}else n.DIFFUSE=!1;if(this._ambientTexture&&yc.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;Un(this._ambientTexture,n,"AMBIENT")}else n.AMBIENT=!1;if(this._opacityTexture&&yc.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;Un(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else n.OPACITY=!1;if(this._reflectionTexture&&yc.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Vo.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Vo.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Vo.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Vo.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Vo.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Vo.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Vo.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Vo.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Vo.CUBIC_MODE:case Vo.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC")}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&yc.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;Un(this._emissiveTexture,n,"EMISSIVE")}else n.EMISSIVE=!1;if(this._lightmapTexture&&yc.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;Un(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else n.LIGHTMAP=!1;if(this._specularTexture&&yc.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;Un(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&yc.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;Un(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&yc.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,n.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(yc.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),qn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),eo(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ro(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(n.isDirty){const i=n._areLightsDisposed;n.markAsProcessed();const s=new ja;n.REFLECTION&&s.addFallback(0,"REFLECTION"),n.SPECULAR&&s.addFallback(0,"SPECULAR"),n.BUMP&&s.addFallback(0,"BUMP"),n.PARALLAX&&s.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&s.addFallback(1,"FOG"),n.POINTSIZE&&s.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),Kn(n,s,this._maxSimultaneousLights),n.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&s.addFallback(4,"FRESNEL"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const a=[ys.PositionKind];n.NORMAL&&a.push(ys.NormalKind),n.TANGENT&&a.push(ys.TangentKind);for(let e=1;e<=6;++e)n["UV"+e]&&a.push(`uv${1===e?"":e}`);n.VERTEXCOLOR&&a.push(ys.ColorKind),Qn(a,e,n,s),jn(a,n),Bn(a,e,n),zn(a,0,n);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=c,this._eventInfo.attributes=a,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(En.PrepareEffect,this._eventInfo),ac.AddUniforms(c),ac.AddSamplers(u),xs&&(xs.PrepareUniforms(c,n),xs.PrepareSamplers(u,n)),co({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),An(c);const p={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,n,a,p));const f=n.toString(),m=t.effect;let g=r.getEngine().createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:_,processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},o);if(this._eventInfo.customCode=void 0,g)if(this._onEffectCreatedObservable&&(bc.effect=g,bc.subMesh=t,this._onEffectCreatedObservable.notifyObservers(bc)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,n.markAsUnprocessed(),l=this.isFrozen,i)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!l,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,n,i,t.visibility);Wn(t,n);const a=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!a.useUbo||!this.isFrozen||!a.isSync||i._drawWrapper._forceRebindOnNextCall){if(yc.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(a.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),a.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&a.updateColor4("opacityParts",new Ce(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(a.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),a.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(a.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),a.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(a.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),a.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&yc.DiffuseTextureEnabled&&(a.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Gn(this._diffuseTexture,a,"diffuse")),this._ambientTexture&&yc.AmbientTextureEnabled&&(a.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Gn(this._ambientTexture,a,"ambient")),this._opacityTexture&&yc.OpacityTextureEnabled&&(a.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Gn(this._opacityTexture,a,"opacity")),this._hasAlphaChannel()&&a.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&yc.ReflectionTextureEnabled&&(a.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),a.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;a.updateVector3("vReflectionPosition",e.boundingBoxPosition),a.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&yc.EmissiveTextureEnabled&&(a.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Gn(this._emissiveTexture,a,"emissive")),this._lightmapTexture&&yc.LightmapTextureEnabled&&(a.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Gn(this._lightmapTexture,a,"lightmap")),this._specularTexture&&yc.SpecularTextureEnabled&&(a.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Gn(this._specularTexture,a,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&yc.BumpTextureEnabled&&(a.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Gn(this._bumpTexture,a,"bump"),s._mirroredCameraPosition?a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&yc.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(a.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),a.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;a.updateVector3("vRefractionPosition",e.boundingBoxPosition),a.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&a.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&a.updateColor4("vSpecularColor",this.specularColor,this.specularPower),a.updateColor3("vEmissiveColor",yc.EmissiveTextureEnabled?this.emissiveColor:Ce.BlackReadOnly),a.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),a.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&yc.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&yc.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&yc.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&yc.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&yc.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&yc.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&yc.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&yc.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&yc.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),In(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&Yn(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Nn(s,t,n),r.NUM_MORPH_INFLUENCERS&&kn(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this.useLogarithmicDepth&&wn(r,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),a.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=yt.Clone((()=>new yc(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=yt.Parse((()=>new yc(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),uo._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return lc.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){lc.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return lc.DetailTextureEnabled}static set DetailTextureEnabled(e){lc.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return lc.AmbientTextureEnabled}static set AmbientTextureEnabled(e){lc.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return lc.OpacityTextureEnabled}static set OpacityTextureEnabled(e){lc.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return lc.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){lc.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return lc.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){lc.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return lc.SpecularTextureEnabled}static set SpecularTextureEnabled(e){lc.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return lc.BumpTextureEnabled}static set BumpTextureEnabled(e){lc.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return lc.LightmapTextureEnabled}static set LightmapTextureEnabled(e){lc.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return lc.RefractionTextureEnabled}static set RefractionTextureEnabled(e){lc.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return lc.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){lc.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return lc.FresnelEnabled}static set FresnelEnabled(e){lc.FresnelEnabled=e}}qe([rt("diffuseTexture")],yc.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesAndMiscDirty")],yc.prototype,"diffuseTexture",void 0),qe([rt("ambientTexture")],yc.prototype,"_ambientTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"ambientTexture",void 0),qe([rt("opacityTexture")],yc.prototype,"_opacityTexture",void 0),qe([it("_markAllSubMeshesAsTexturesAndMiscDirty")],yc.prototype,"opacityTexture",void 0),qe([rt("reflectionTexture")],yc.prototype,"_reflectionTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"reflectionTexture",void 0),qe([rt("emissiveTexture")],yc.prototype,"_emissiveTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"emissiveTexture",void 0),qe([rt("specularTexture")],yc.prototype,"_specularTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"specularTexture",void 0),qe([rt("bumpTexture")],yc.prototype,"_bumpTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"bumpTexture",void 0),qe([rt("lightmapTexture")],yc.prototype,"_lightmapTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"lightmapTexture",void 0),qe([rt("refractionTexture")],yc.prototype,"_refractionTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"refractionTexture",void 0),qe([nt("ambient")],yc.prototype,"ambientColor",void 0),qe([nt("diffuse")],yc.prototype,"diffuseColor",void 0),qe([nt("specular")],yc.prototype,"specularColor",void 0),qe([nt("emissive")],yc.prototype,"emissiveColor",void 0),qe([st()],yc.prototype,"specularPower",void 0),qe([st("useAlphaFromDiffuseTexture")],yc.prototype,"_useAlphaFromDiffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesAndMiscDirty")],yc.prototype,"useAlphaFromDiffuseTexture",void 0),qe([st("useEmissiveAsIllumination")],yc.prototype,"_useEmissiveAsIllumination",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useEmissiveAsIllumination",void 0),qe([st("linkEmissiveWithDiffuse")],yc.prototype,"_linkEmissiveWithDiffuse",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"linkEmissiveWithDiffuse",void 0),qe([st("useSpecularOverAlpha")],yc.prototype,"_useSpecularOverAlpha",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useSpecularOverAlpha",void 0),qe([st("useReflectionOverAlpha")],yc.prototype,"_useReflectionOverAlpha",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useReflectionOverAlpha",void 0),qe([st("disableLighting")],yc.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],yc.prototype,"disableLighting",void 0),qe([st("useObjectSpaceNormalMap")],yc.prototype,"_useObjectSpaceNormalMap",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useObjectSpaceNormalMap",void 0),qe([st("useParallax")],yc.prototype,"_useParallax",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useParallax",void 0),qe([st("useParallaxOcclusion")],yc.prototype,"_useParallaxOcclusion",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useParallaxOcclusion",void 0),qe([st()],yc.prototype,"parallaxScaleBias",void 0),qe([st("roughness")],yc.prototype,"_roughness",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"roughness",void 0),qe([st()],yc.prototype,"indexOfRefraction",void 0),qe([st()],yc.prototype,"invertRefractionY",void 0),qe([st()],yc.prototype,"alphaCutOff",void 0),qe([st("useLightmapAsShadowmap")],yc.prototype,"_useLightmapAsShadowmap",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useLightmapAsShadowmap",void 0),qe([ot("diffuseFresnelParameters")],yc.prototype,"_diffuseFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"diffuseFresnelParameters",void 0),qe([ot("opacityFresnelParameters")],yc.prototype,"_opacityFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelAndMiscDirty")],yc.prototype,"opacityFresnelParameters",void 0),qe([ot("reflectionFresnelParameters")],yc.prototype,"_reflectionFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"reflectionFresnelParameters",void 0),qe([ot("refractionFresnelParameters")],yc.prototype,"_refractionFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"refractionFresnelParameters",void 0),qe([ot("emissiveFresnelParameters")],yc.prototype,"_emissiveFresnelParameters",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"emissiveFresnelParameters",void 0),qe([st("useReflectionFresnelFromSpecular")],yc.prototype,"_useReflectionFresnelFromSpecular",void 0),qe([it("_markAllSubMeshesAsFresnelDirty")],yc.prototype,"useReflectionFresnelFromSpecular",void 0),qe([st("useGlossinessFromSpecularMapAlpha")],yc.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"useGlossinessFromSpecularMapAlpha",void 0),qe([st("maxSimultaneousLights")],yc.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],yc.prototype,"maxSimultaneousLights",void 0),qe([st("invertNormalMapX")],yc.prototype,"_invertNormalMapX",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"invertNormalMapX",void 0),qe([st("invertNormalMapY")],yc.prototype,"_invertNormalMapY",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"invertNormalMapY",void 0),qe([st("twoSidedLighting")],yc.prototype,"_twoSidedLighting",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],yc.prototype,"twoSidedLighting",void 0),qe([st("applyDecalMapAfterDetailMap")],yc.prototype,"_applyDecalMapAfterDetailMap",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],yc.prototype,"applyDecalMapAfterDetailMap",void 0),ee("BABYLON.StandardMaterial",yc),dr.DefaultMaterialFactory=e=>new yc("default material",e),ki.prototype.createDynamicTexture=function(e,t,i,s){const r=new Pi(this,Ai.Dynamic);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?ki.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?ki.GetExponentOfTwo(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=s,this.updateTextureSamplingMode(s,r),this._internalTexturesCache.push(r),r},ki.prototype.updateDynamicTexture=function(e,t,i,s=!1,r,n=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(r||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(e.format=r),e._dynamicTextureSource=t,e._premulAlpha=s,e.invertY=i||!1,e.isReady=!0};class Sc extends Vo{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=Vo.CLAMP_ADDRESSMODE,this.wrapV=Vo.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const a=this._getEngine();if(!a)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=a.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=a.createCanvas(1,1),this._ownCanvas=!0,t.width||0===t.width?this._texture=a.createDynamicTexture(t.width,t.height,s,r):this._texture=a.createDynamicTexture(t,t,s,r));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,r,n,o,a=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=s,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(s.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),a&&this.update(o)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Sc(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&we.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Sc._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class Cc{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this._createRenderTargetTextureProvider=r,this._rttWrapper=null}}class Ec{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Pi(this._engine,Ai.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Ni(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=n?new Jh(this._scene,o):new pl("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&s||(l._framebuffer=i),s)if(n)l._colorTextureArray=s;else{const e=this._createInternalTexture(o,s);l.setTexture(e,0),a._texture=e}return r&&(n?l._depthStencilTextureArray=r:l._depthStencilTexture=this._createInternalTexture(o,r)),a.disableRescaling(),this._renderTargetTextures.push(a),a}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class Ac extends Cc{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Pc(e.scene,this))),this.layer=e}}class Pc extends Ec{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&s===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class Rc{static GetDefaults(e){const t=new Rc;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class Ic{constructor(e,t=Rc.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new X,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()}))}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new Ac(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{}),(()=>{hs.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t())):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class Mc extends Cc{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Oc(e,this))),this.layer=e}}class Oc extends Ec{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class Dc{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class wc{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new X,this.onXRReferenceSpaceChanged=new X,this.onXRSessionEnded=new X,this.onXRSessionInit=new X,this.onXRReferenceSpaceInitialized=new X,this.onXRReady=new X,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new X(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{we.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){return this._baseLayerRTTProvider?.trySetViewportForView(e,t)||!1}getRenderTargetTextureForEye(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(e)||null}getRenderTargetTextureForView(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForView(e)||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new Dc(this):((e=e||Rc.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new Ic(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(t),this.session.addEventListener("end",(()=>{this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return wc.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{if(this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t)){this.inXRFrameLoop=!0;const e=this._baseLayerRTTProvider?.getFramebufferDimensions()||null;this._engine.framebufferDimensionsObject!==e&&(this._engine.framebufferDimensionsObject=e),this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=this._baseLayerRTTProvider?.getFramebufferDimensions()||null,this.onXRFrameObservable.addOnce((()=>{this.onXRReady.notifyObservers(this)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(we.Error("XR.requestReferenceSpace failed for the following reason: "),we.Error(e),we.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw we.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.onXRReferenceSpaceInitialized.notifyObservers(e),this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerWrapper=e,this._baseLayerRTTProvider=this._baseLayerWrapper?.createRenderTargetTextureProvider(this)||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Mc(e.baseLayer):new Ac(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(we.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){return this.session?.frameRate}get supportedFrameRates(){return this.session?.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){return this._baseLayerWrapper?.isFixedFoveationSupported||!1}get fixedFoveation(){return this._baseLayerWrapper?.fixedFoveation||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){return this.session?.enabledFeatures??null}}var Nc,Fc;!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(Nc||(Nc={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(Fc||(Fc={})),bo._GroundMeshParser=(e,t)=>Bc.Parse(e,t);class Bc extends bo{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=ge.Matrix[5];i.invertToRef(s);const r=ge.Vector3[8];if(de.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return de.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new de(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=ge.Matrix[5];s.invertToRef(r);const n=ge.Vector3[8];if(de.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return de.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return n=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new de(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,_=e.buffer[c+2]/255;const p=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,_=1-_);const f=u*a.r+d*a.g+_*a.b;t.y=p>=l?e.minHeight+(e.maxHeight-e.minHeight)*f:e.minHeight-K,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),r.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*r+1]>=e.minHeight,u=i[3*a+1]>=e.minHeight;h&&c&&u&&(t.push(s),t.push(r),t.push(a)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(s),t.push(a))}cn.ComputeNormals(i,t,s);const c=new cn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Uc(e,t={},i){const s=new Bc(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,Lc(t).applyToMesh(s,t.updatable),s._setReady(!0),s}function Gc(e,t,i=null){const s=new bo(e,i);return kc(t).applyToMesh(s,t.updatable),s}function zc(e,t,i={},s=null){const r=i.width||10,n=i.height||10,o=i.subdivisions||1,a=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new Ce(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;s=s||se.LastCreatedScene;const _=new Bc(e,s);let p;_._subdivisionsX=o,_._subdivisionsY=o,_._width=r,_._height=n,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((o+1)*(o+1)));const f=(e,t,i)=>{Vc({width:r,height:n,subdivisions:o,minHeight:a,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:p}).applyToMesh(_,u),d&&d(_,p),_._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const r=s?.getEngine().resizeImageBitmap(e,t,i);f(r,t,i)};hs.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else f(t.data,t.width,t.height);return _}const Wc={CreateGround:Uc,CreateGroundFromHeightMap:zc,CreateTiledGround:Gc};function Hc(e){const t=[],i=[],s=[],r=[],n=e.diameter||1,o=e.thickness||.5,a=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,h=a+1;for(let e=0;e<=a;e++){const l=e/a,c=e*Math.PI*2/a-Math.PI/2,u=fe.Translation(n/2,0,0).multiply(fe.RotationY(c));for(let n=0;n<=a;n++){const c=1-n/a,d=n*Math.PI*2/a+Math.PI,_=Math.cos(d),p=Math.sin(d);let f=new de(_,p,0),m=f.scale(o/2);const g=new ue(l,c);m=de.TransformCoordinates(m,u),f=de.TransformNormal(f,u),i.push(m.x,m.y,m.z),s.push(f.x,f.y,f.z),r.push(g.x,dn.UseOpenGLOrientationForUV?1-g.y:g.y);const v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}cn._ComputeSides(l,i,t,s,r,e.frontUVs,e.backUVs);const c=new cn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Xc(e,t={},i){const s=new bo(e,i);return t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Hc(t).applyToMesh(s,t.updatable),s}cn.CreateGround=Lc,cn.CreateTiledGround=kc,cn.CreateGroundFromHeightMap=Vc,bo.CreateGround=(e,t,i,s,r,n)=>Uc(e,{width:t,height:i,subdivisions:s,updatable:n},r),bo.CreateTiledGround=(e,t,i,s,r,n,o,a,l)=>Gc(e,{xmin:t,zmin:i,xmax:s,zmax:r,subdivisions:n,precision:o,updatable:l},a),bo.CreateGroundFromHeightMap=(e,t,i,s,r,n,o,a,l,h,c)=>zc(e,t,{width:i,height:s,subdivisions:r,minHeight:n,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a);const Yc={CreateTorus:Xc};cn.CreateTorus=Hc,bo.CreateTorus=(e,t,i,s,r,n,o)=>Xc(e,{diameter:t,thickness:i,tessellation:s,sideOrientation:o,updatable:n},r);class Qc{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=Qc._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=Xc("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new yc("targetMat",e);t.specularColor=Ce.Black(),t.emissiveColor=new Ce(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new Zo(de.Zero(),new de(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}Qc._IdCounter=0;class jc extends Qc{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Zo(de.Zero(),de.Forward())}}class Kc{}class $c{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new X,this.onAfterEnteringVRObservable=new X,this.onExitingVRObservable=new X,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=$c.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new de(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new de(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Ce(.2,.2,1),this._pickedGazeColor=new Ce(0,0,1),this.onNewMeshSelected=new X,this.onNewMeshPicked=new X,this.onBeforeCameraTeleport=new X,this.onAfterCameraTeleport=new X,this.onSelectedMeshUnselected=new X,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==$l.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===$l.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===Wl.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===Wl.A&&this._cameraGazer._selectionPointerUp()}))))},this._workingVector=de.Zero(),this._workingQuaternion=pe.Identity(),this._workingMatrix=fe.Identity(),we.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new de(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new yh("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof vh&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(pe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?wc.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(we.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new jc((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case Nc.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Nc.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Nc.IN_XR:this._hasEnteredVR=!0;break;case Nc.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new nc("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new jc((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode||this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),Ms.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((()=>{this.dispose()})),this._updateButtonVisibility(),this._circleEase=new Cr,this._circleEase.setEasingMode(Sr.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===Ms.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===Ms.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Nc.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){we.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=pe.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){we.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr)return void(this.xr.baseExperience.state===Nc.IN_XR&&this.xr.pointerSelection.attach());this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);const t=new xs;t.vignetteColor=new Ee(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const e=pe.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,pe.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),de.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const s=new Zo(i,this._workingVector),r=this._scene.pickWithRay(s,this._raySelectionPredicate);r&&r.pickedPoint&&r.pickedMesh&&this._isTeleportationFloor(r.pickedMesh)&&r.distance<5&&this.teleportCamera(r.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=Uc("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new Sc("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new yc("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const s=Xc("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);s.isPickable=!1,s.parent=this._teleportationTarget;const r=new Nt("animationInnerCircle","position.y",30,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new Nr;o.setEasingMode(Sr.EASINGMODE_EASEINOUT),r.setEasingFunction(o),s.animations=[],s.animations.push(r),this._scene.beginAnimation(s,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof xh))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=pe.FromRotationMatrix(fe.RotationY(Math.PI/4*this._rotationAngle)),i=new Nt("animationRotation","rotationQuaternion",90,Nt.ANIMATIONTYPE_QUATERNION,Nt.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new Nt("animationPP","vignetteWeight",90,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new Nt("animationPP2","vignetteStretch",90,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:10}),a.push({frame:6,value:0}),o.setKeys(a),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof xh))return;let t,i;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==$c.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=de.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const s=new Nt("animationCameraTeleportation","position",90,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT),r=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];s.setKeys(r),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];const n=Math.round(i/2),o=new Nt("animationPP","vignetteWeight",90,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:n,value:8}),a.push({frame:i,value:0}),o.setKeys(a),this._postProcessMove.animations.push(o);const l=new Nt("animationPP2","vignetteStretch",90,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}$c.TELEPORTATIONMODE_CONSTANTTIME=0,$c.TELEPORTATIONMODE_CONSTANTSPEED=1;const qc=function(){const e={root:0,found:!1};return function(t,i,s,r){e.root=0,e.found=!1;const n=i*i-4*t*s;if(n<0)return e;const o=Math.sqrt(n);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,s){const r=de.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!((e,t,i,s)=>!(e.x>i.x+s||i.x-s>t.x||e.y>i.y+s||i.y-s>t.y||e.z>i.z+s||i.z-s>t.z))(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let a,l=!1;t||(t=[]),t[e]||(t[e]=new ir(0,0,0,0),t[e].copyFromPoints(i,s,r));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const c=h.signedDistanceTo(this._basePoint),u=de.Dot(h.normal,this._velocity);if(Zc.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,a=0}else{a=(-1-c)/u;let e=(1-c)/u;if(a>e){const t=e;e=a,a=t}if(a>1||e<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,_=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,h.normal)&&(d=!0,_=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*de.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=qc(e,t,n,_);o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),t=2*de.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=qc(e,t,n,_),o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),t=2*de.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=qc(e,t,n,_),o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let a=this._edge.lengthSquared(),l=de.Dot(this._edge,this._velocity),h=de.Dot(this._edge,this._baseToVertex);if(e=a*-this._velocitySquaredLength+l*l,t=2*(a*de.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=qc(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=de.Dot(this._edge,this._velocity),h=de.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*de.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=qc(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=de.Dot(this._edge,this._velocity),h=de.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*de.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=qc(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}}if(d){const e=_*_*this._velocitySquaredLength;(!this.collisionFound||e=s)return void r.copyFrom(e);const a=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew Jc;class eu{constructor(e,t,i,s=""){let r;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new X,this.onErrorObservable=new X,this.onBindObservable=new X,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=ui.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=eu._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=bi.GetShadersStore(this._shaderLanguage),this._shaderRepository=bi.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=bi.GetIncludesShadersStore(this._shaderLanguage);const n=Lt()?this._engine.getHostDocument():null;r="string"==typeof e?e:e.computeSource?"source:"+e.computeSource:e.computeElement?n?.getElementById(e.computeElement)||e.computeElement:e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(r,"Compute","",(i=>{xi.Initialize(o),xi.PreProcess(i,o,(s=>{this._rawComputeSourceCode=i,t.processFinalCode&&(s=t.processFinalCode(s));const r=xi.Finalize(s,"",o);this._useFinalCode(r.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Ut(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));if(this._shaderStore[e+t+"Shader"])return void s(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void s(this._shaderStore[e+i+"Shader"]);let r;r="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){return this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._pipelineContext?._getComputeShaderCode()??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,(e=>{e&&e.numErrors>0?this._processCompilationErrors(e,t):(this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t))})),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_processCompilationErrors(e,t=null){if(this._compilationError="",we.Error("Unable to compile compute effect:"),this.defines&&we.Error("Defines:\n"+this.defines),eu.LogShaderCodeOnCompilationError){const e=this._pipelineContext?._getComputeShaderCode();e&&(we.Error("Compute code:"),we.Error(e))}if("string"==typeof e)this._compilationError=e,we.Error("Error: "+this._compilationError);else for(const t of e.messages){let e="";void 0!==t.line&&(e+="Line "+t.line+", "),void 0!==t.offset&&(e+="Offset "+t.offset+", "),void 0!==t.length&&(e+="Length "+t.length+", "),e+=t.type+": "+t.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=e,we.Error(e)}t&&(this._pipelineContext=t,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){bi.GetShadersStore(ui.WGSL)[`${e}ComputeShader`]=t}}var tu;eu._UniqueIdSeed=0,eu.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(tu||(tu={})),ki.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},ki.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},ki.prototype.createComputeContext=function(){},ki.prototype.computeDispatch=function(e,t,i,s,r,n,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},ki.prototype.areAllComputeEffectsReady=function(){return!0},ki.prototype.releaseComputeEffects=function(){},ki.prototype._prepareComputePipelineContext=function(e,t,i,s,r){},ki.prototype._rebuildComputeEffects=function(){},ki.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},ki.prototype._releaseComputeEffect=function(e){},ki.prototype._deleteComputePipelineContext=function(e){};class iu{constructor(){this._gpuTimeInFrameId=-1,this.counter=new tr}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()}))}serialize(){const e=yt.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],s=i.object;switch(i.type){case tu.Texture:case tu.TextureWithoutSampler:case tu.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case tu.UniformBuffer:}}return e}static Parse(e,t,i){const s=yt.Parse((()=>new su(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=Vo.Parse(e.textures[r],t,i);n.type===tu.Texture?s.setTexture(r,o):n.type===tu.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}static _BufferIsDataBuffer(e){return void 0!==e.underlyingResource}}qe([st()],su.prototype,"name",void 0),qe([st()],su.prototype,"fastMode",void 0),ee("BABYLON.ComputeShader",su);class ru{constructor(e,t,i,s,r,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},nu.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},dr.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(Rs.NAME_OCTREE);i||(i=new ou(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new nu(nu.CreationFuncForMeshes,e,t));const s=this.getWorldExtends();return this._selectionOctree.update(s.min,s.max,this.meshes),this._selectionOctree},Object.defineProperty(dr.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Sn.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let s=i._getComponent(Rs.NAME_OCTREE);s||(s=new ou(i),i._addComponent(s)),this._submeshesOctree||(this._submeshesOctree=new nu(nu.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class ou{constructor(e){this.name=Rs.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Zo(de.Zero(),new de(1,1,1)),(e=e||se.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){return this.scene._selectionOctree?.select(this.scene.frustumPlanes)||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(Zo.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function au(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,s=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,s=s||1e-5;const r=0|(e.tessellation||24),n=0|(e.subdivisions||1),o=!!e.hasRings,a=!!e.enclose,l=0===e.cap?0:e.cap||bo.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,_=2+(1+(1!==h&&a?2:0))*(o?n:1);let p;for(p=0;p<_;p++)d&&void 0===d[p]&&(d[p]=new Ee(1,1,1,1));for(p=0;p<_;p++)u&&void 0===u[p]&&(u[p]=new _e(0,0,1,1));const f=[],m=[],g=[],v=[],x=[],b=2*Math.PI*h/r;let T,y,S;const C=(s-i)/2/t,E=de.Zero(),A=de.Zero(),P=de.Zero(),R=de.Zero(),I=de.Zero(),M=_r.Y;let O,D,w,N=1,F=1,B=0,L=0;for(O=0;O<=n;O++)for(y=O/n,S=(y*(i-s)+s)/2,N=o&&0!==O&&O!==n?2:1,w=0;w{const n=e?i/2:s/2;if(0===n)return;let o,a,l;const c=e?u[_-1]:u[0];let p=null;d&&(p=e?d[_-1]:d[0]);const b=m.length/3,T=e?t/2:-t/2,y=new de(0,T,0);m.push(y.x,y.y,y.z),g.push(0,e?1:-1,0);const S=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),dn.UseOpenGLOrientationForUV?1-S:S),p&&x.push(p.r,p.g,p.b,p.a);const C=new ue(.5,.5);for(l=0;l<=r;l++){o=2*Math.PI*l*h/r;const t=Math.cos(-o),i=Math.sin(-o);a=new de(t*n,T,i*n);const s=new ue(t*C.x+.5,i*C.y+.5);m.push(a.x,a.y,a.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*s.y;v.push(c.x+(c.z-c.x)*s.x,dn.UseOpenGLOrientationForUV?1-u:u),p&&x.push(p.r,p.g,p.b,p.a)}for(l=0;l(void 0!==o&&o instanceof dr||(void 0!==o&&(l=a||bo.DEFAULTSIDE,a=o),o=n,n=1),lu(e,{height:t,diameterTop:i,diameterBottom:s,tessellation:r,subdivisions:n,sideOrientation:l,updatable:a},o)),Ct.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new cu(e,de.Zero(),t)));class cu extends yo{constructor(e,t,i){super(e,i),this.groundColor=new Ce(0,0,0),this.direction=t||de.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=de.Normalize(e.subtract(de.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=de.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=de.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=fe.Identity()),this._worldMatrix}getTypeID(){return yo.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}qe([nt()],cu.prototype,"groundColor",void 0),qe([lt()],cu.prototype,"direction",void 0);class uu{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new cu("shared gizmo light",new de(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Ce.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==uu._DefaultUtilityLayer?uu._CreateDefaultUtilityLayerFromScene(se.LastCreatedScene):uu._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return uu._DefaultUtilityLayer=new uu(e),uu._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{uu._DefaultUtilityLayer=null})),uu._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==uu._DefaultKeepDepthUtilityLayer&&(uu._DefaultKeepDepthUtilityLayer=new uu(se.LastCreatedScene),uu._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,uu._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{uu._DefaultKeepDepthUtilityLayer=null}))),uu._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new X,this.utilityLayerScene=new dr(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==Ms.POINTERMOVE&&t.type!==Ms.POINTERUP&&t.type!==Ms.POINTERDOWN&&t.type!==Ms.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const s=i=>{let s=null;if(t.nearInteractionPickingInfo)s=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new Ss;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)s=t.originalPickingInfo;else{let r=null;this._renderCamera&&(r=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),s=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),r&&(i._activeCamera=r)}return s},r=s(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=Ms.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ws(t.type,t.event,r),t.type),void(t.type===Ms.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ws(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{const i=s(e),n=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===Ms.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:t.type!==Ms.POINTERMOVE&&t.type!==Ms.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(r.distance0)):!this._pointerCaptures[n.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):(t.type!==Ms.POINTERMOVE&&t.type!==Ms.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,r,n))),t.type===Ms.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new ws(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}var du,_u,pu;uu._DefaultUtilityLayer=null,uu._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(du||(du={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(_u||(_u={}));class fu{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==_u.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=uu.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=du.Origin,this._updateScale=!0,this._coordinatesMode=_u.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=fe.RotationY(Math.PI),this._rootMesh=new bo("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=pe.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==du.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new de(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,fu.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,ge.Vector3[0]);let s=this.scaleRatio;if(t.mode==Kr.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(s*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?de.RightHandedForwardReadOnly:de.LeftHandedForwardReadOnly,i=t.getDirection(e);s*=de.Dot(ge.Vector3[0],i)}this._rootMesh.scaling.setAll(s),e._getWorldMatrixDeterminant()<0&&!fu.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),ge.Matrix[0]),ge.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(ge.Matrix[5]),void ge.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=ge.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,ge.Matrix[0]),t=ge.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,ge.Matrix[1]),i=ge.Matrix[1]):i=t,i.decompose(ge.Vector3[1],ge.Quaternion[0],ge.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=ge.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(ge.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(ge.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=ge.Matrix[0],i=ge.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const s=ge.Matrix[4];if(this._handlePivotMatrixInverse(e,i,s),s.decompose(ge.Vector3[0],ge.Quaternion[0],e.position,fu.PreserveScaling?e:void 0,fu.UseAbsoluteScaling),ge.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const t=ge.Quaternion[1];pe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);const i=ge.Matrix[2];fe.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);const s=ge.Matrix[2];t.toRotationMatrix(s);const r=e.getPivotMatrix(),n=ge.Matrix[3];r.invertToRef(n),r.multiplyToRef(i,ge.Matrix[4]),ge.Matrix[4].multiplyToRef(s,ge.Matrix[5]),ge.Matrix[5].multiplyToRef(n,ge.Matrix[6]),ge.Matrix[6].getTranslationToRef(ge.Vector3[1]),e.position.subtractInPlace(ge.Vector3[1])}}else{const t=ge.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(ge.Vector3[0],ge.Quaternion[0],e.position,fu.PreserveScaling?e:void 0,fu.UseAbsoluteScaling)}ge.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(ge.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(ge.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=ge.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=ge.Matrix[0],s=ge.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,s),e.getLocalMatrix().copyFrom(s)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===yo.LIGHTTYPEID_DIRECTIONALLIGHT||t===yo.LIGHTTYPEID_SPOTLIGHT||t===yo.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=ge.Matrix[0],s=ge.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,s),s.decompose(void 0,ge.Quaternion[0],ge.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,ge.Quaternion[0],ge.Vector3[0]);e.position=new de(ge.Vector3[0].x,ge.Vector3[0].y,ge.Vector3[0].z),e.direction&&(e.direction=new de(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{if(e.pickInfo){if(e.type===Ms.POINTERMOVE){if(i)return;t.forEach((t=>{if(t.colliderMeshes&&t.gizmoMeshes){const i=-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh),s=t.dragBehavior.enabled?i||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}}))}e.type===Ms.POINTERDOWN&&t.has(e.pickInfo.pickedMesh?.parent)&&(i=!0,t.get(e.pickInfo.pickedMesh?.parent).active=!0,t.forEach((t=>{const i=(-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh)||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=i,e.color&&(e.color=i.diffuseColor)}))}))),e.type===Ms.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}fu.PreserveScaling=!1,fu.UseAbsoluteScaling=!0;class mu extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,s=!1){const r=new xn("arrow",e),n=lu("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=lu("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return n.parent=r,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,o.parent=r,o.material=t,o.position.z+=.1375,o.rotation.x=Math.PI/2,s&&(o.visibility=0,n.visibility=0),r}static _CreateArrowInstance(e,t){const i=new xn("arrow",e);for(const e of t.getChildMeshes())e.createInstance(e.name).parent=i;return i}constructor(e,t=Ce.Gray(),i=uu.DefaultUtilityLayer,s=null,r=1,n=Ce.Yellow(),o=Ce.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new X,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new yc("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ce(.1,.1,.1)),this._hoverMaterial=new yc("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new yc("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const a=mu._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r),l=mu._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r+4,!0);this._gizmoMesh=new bo("",i.utilityLayerScene),this._gizmoMesh.addChild(a),this._gizmoMesh.addChild(l),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let h=0;const c={snapDistance:0};this.dragBehavior=new sa({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){let t=!1;if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(ge.Vector3[2]),ge.Vector3[2].addInPlace(e.delta),this.dragBehavior.validateDrag(ge.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.updateCache(),t=!0);else if(h+=e.dragDistance,Math.abs(h)>this.snapDistance){const i=Math.floor(Math.abs(h)/this.snapDistance);h%=this.snapDistance,e.delta.normalizeToRef(ge.Vector3[1]),ge.Vector3[1].scaleInPlace(this.snapDistance*i),this.attachedNode.getWorldMatrix().getTranslationToRef(ge.Vector3[2]),ge.Vector3[2].addInPlace(ge.Vector3[1]),this.dragBehavior.validateDrag(ge.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(ge.Vector3[1].x,ge.Vector3[1].y,ge.Vector3[1].z),this.attachedNode.updateCache(),c.snapDistance=this.snapDistance*i*Math.sign(h),this.onSnapObservable.notifyObservers(c),t=!0)}t&&this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const d={gizmoMeshes:a.getChildMeshes(),colliderMeshes:l.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(l,d),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==d.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(d.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(d.gizmoMeshes,e?d.material:d.disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}class gu{get scaleLines(){return this._scaleLines}set scaleLines(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)}get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,s,r,n,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||se.LastCreatedScene){if(!s){const t=new yc("xAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ce.Red().scale(.5),s=mu._CreateArrow(e,t,o)}if(!r){const t=new yc("yAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ce.Green().scale(.5),r=mu._CreateArrow(e,t,o)}if(!n){const t=new yc("zAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ce.Blue().scale(.5),n=mu._CreateArrow(e,t,o)}this._xAxis=s,this._yAxis=r,this._zAxis=n,this.scaleLines=t,null!=i&&(gu._SetRenderingGroupId(this._xAxis,i),gu._SetRenderingGroupId(this._yAxis,i),gu._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new de,de.Right(),de.Up(),de.Forward())}}update(e,t,i,s){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(s)}createInstance(){const e=mu._CreateArrowInstance(this.scene,this._xAxis),t=mu._CreateArrowInstance(this.scene,this._yAxis),i=mu._CreateArrowInstance(this.scene,this._zAxis),s=new gu(this.scene,this.scaleLines,null,e,t,i);return s._instanced=!0,s}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach((e=>{e.renderingGroupId=t}))}}class vu extends gu{constructor(e,t,i,s=1){super(e,s),this.pos=de.Zero(),this.xaxis=de.Zero(),this.yaxis=de.Zero(),this.zaxis=de.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef(_r.X,this.mesh,this.xaxis),e.getDirectionToRef(_r.Y,this.mesh,this.yaxis),e.getDirectionToRef(_r.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(dr.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new xu(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(pu||(pu={}));class xu{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new X),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new X),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||se.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()}))}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...xu.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:xu.InspectorURL;hs.LoadBabylonScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function bu(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[];let r=[];const n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const s=[17,18,19,16],r=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),s.unshift(s.pop()),u--;for(;d>0;)i.unshift(i.pop()),r.unshift(r.pop()),d--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(s[0],s[2],s[3],s[0],s[1],s[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const p=[n/2,o/2,a/2];r=_.reduce(((e,t,i)=>e.concat(t*p[i%3])),[]);const f=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new _e(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new Ee(1,1,1,1));for(let e=0;e<6;e++)if(s.push(m[e].z,dn.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,dn.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,dn.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),s.push(m[e].z,dn.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);cn._ComputeSides(f,r,t,i,s,e.frontUVs,e.backUVs);const x=new cn;if(x.indices=t,x.positions=r,x.normals=i,x.uvs=s,g){const e=f===cn.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function Tu(e){const t=e.width||e.size||1,i=e.height||e.size||1,s=e.depth||e.size||1,r=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),o=0|(e.depthSegments||e.segments||1),a=new fe,l=new fe,h=new fe,c=Lc({width:t,height:s,subdivisionsX:r,subdivisionsY:o});fe.TranslationToRef(0,-i/2,0,l),fe.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=Lc({width:t,height:s,subdivisionsX:r,subdivisionsY:o});fe.TranslationToRef(0,i/2,0,h),u.transform(h);const d=Lc({width:i,height:s,subdivisionsX:n,subdivisionsY:o});fe.TranslationToRef(-t/2,0,0,l),fe.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const _=Lc({width:i,height:s,subdivisionsX:n,subdivisionsY:o});fe.TranslationToRef(t/2,0,0,l),fe.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h);const p=Lc({width:t,height:i,subdivisionsX:r,subdivisionsY:n});fe.TranslationToRef(0,0,-s/2,l),fe.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const f=Lc({width:t,height:i,subdivisionsX:r,subdivisionsY:n});return fe.TranslationToRef(0,0,s/2,l),fe.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h),c.merge([u,_,d,p,f],!0),c}function yu(e,t={},i=null){const s=new bo(e,i);return t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,bu(t).applyToMesh(s,t.updatable),s}xu.InspectorURL=`${hs._DefaultCdnUrl}/v${gn.Version}/inspector/babylon.inspector.bundle.js`,xu.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};const Su={CreateBox:yu};function Cu(e){const t=0|(e.segments||32),i=e.diameterX||e.diameter||1,s=e.diameterY||e.diameter||1,r=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,o=e.slice&&e.slice<=0?1:e.slice||1,a=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new de(i/2,s/2,r/2),c=2+t,u=2*c,d=[],_=[],p=[],f=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*o;for(let e=0;e<=u;e++){const s=e/u,r=s*Math.PI*2*n,o=fe.RotationZ(-i),a=fe.RotationY(r),l=de.TransformCoordinates(de.Up(),o),c=de.TransformCoordinates(l,a),d=c.multiply(h),m=c.divide(h).normalize();_.push(d.x,d.y,d.z),p.push(m.x,m.y,m.z),f.push(s,dn.UseOpenGLOrientationForUV?1-t:t)}if(e>0){const t=_.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(eyu(e,{size:t,sideOrientation:r,updatable:s},i);const Au={CreateSphere:Eu};function Pu(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=0|Math.max(e.subdivisions?e.subdivisions:2,1),i=0|Math.max(e.tessellation?e.tessellation:16,3),s=Math.max(e.height?e.height:1,0),r=Math.max(e.radius?e.radius:.25,0),n=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),o=i,a=t,l=Math.max(e.radiusTop?e.radiusTop:r,0),h=Math.max(e.radiusBottom?e.radiusBottom:r,0),c=s-(l+h),u=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:n,1),_=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:n,1),p=Math.acos((h-l)/s);let f=[];const m=[],g=[],v=[];let x=0;const b=[],T=.5*c,y=.5*Math.PI;let S,C;const E=de.Zero(),A=de.Zero(),P=Math.cos(p),R=Math.sin(p),I=new ue(l*R,T+l*P).subtract(new ue(h*R,h*P-T)).length(),M=l*p+I+h*(y-p);let O=0;for(C=0;C<=d;C++){const e=[],t=y-p*(C/d);O+=l*p/d;const i=Math.cos(t),s=Math.sin(t),r=i*l;for(S=0;S<=o;S++){const t=S/o,n=t*u+0,a=Math.sin(n),h=Math.cos(n);A.x=r*a,A.y=T+s*l,A.z=r*h,m.push(A.x,A.y,A.z),E.set(i*a,s,i*h),g.push(E.x,E.y,E.z),v.push(t,dn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}const D=s-l-h+P*l-P*h,w=R*(h-l)/D;for(C=1;C<=a;C++){const e=[];O+=I/a;const t=R*(C*(h-l)/a+l);for(S=0;S<=o;S++){const i=S/o,s=i*u+0,r=Math.sin(s),n=Math.cos(s);A.x=t*r,A.y=T+P*l-C*D/a,A.z=t*n,m.push(A.x,A.y,A.z),E.set(r,w,n).normalize(),g.push(E.x,E.y,E.z),v.push(i,dn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}for(C=1;C<=_;C++){const e=[],t=y-p-(Math.PI-p)*(C/_);O+=h*p/_;const i=Math.cos(t),s=Math.sin(t),r=i*h;for(S=0;S<=o;S++){const t=S/o,n=t*u+0,a=Math.sin(n),l=Math.cos(n);A.x=r*a,A.y=s*h-T,A.z=r*l,m.push(A.x,A.y,A.z),E.set(i*a,s,i*l),g.push(E.x,E.y,E.z),v.push(t,dn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}for(S=0;SEu(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:r},s);const Iu={CreateCapsule:Ru};function Mu(e){let t=e.pathArray;const i=e.closeArray||!1,s=e.closePath||!1,r=e.invertUV||!1,n=Math.floor(t[0].length/2);let o=e.offset||n;o=o>n?n:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],_=[],p=[],f=[],m=[],g=[];let v;const x=[],b=[];let T,y,S;if(t.length<2){const e=[],i=[];for(y=0;y0&&(I=P[S].subtract(P[S-1]).length(),M=I+m[T],p[T].push(M),m[T]=M),S++;s&&(S--,c.push(P[0].x,P[0].y,P[0].z),I=P[S].subtract(P[0]).length(),M=I+m[T],p[T].push(M),m[T]=M),x[T]=R+E,b[T]=C,C+=R+E}let w,N,F=null,B=null;for(y=0;y{let r=s[0].length;const n=a;let o=0;const l=n._originalBuilderSideOrientation===bo.DOUBLESIDE?2:1;for(let a=1;a<=l;++a)for(let a=0;aRu(e,t,i),cn.CreateCapsule=Pu;const Du={CreateRibbon:Ou};function wu(e){const t=[],i=[],s=[],r=[],n=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE;t.push(0,0,0),r.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;eOu(e,{pathArray:t,closeArray:i,closePath:s,offset:r,updatable:o,sideOrientation:a,instance:l},n);const Fu={CreateDisc:Nu};function Bu(e){const t=e.pattern||bo.NO_FLIP,i=e.tileWidth||e.tileSize||1,s=e.tileHeight||e.tileSize||1,r=e.alignHorizontal||0,n=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/s);let u=h-c*s;const d=i*a/2,_=s*c/2;let p=0,f=0,m=0,g=0,v=0,x=0;if(l>0||u>0){switch(m=-d,g=-_,v=d,x=_,r){case bo.CENTER:l/=2,m-=l,v+=l;break;case bo.LEFT:v+=l,p=-l/2;break;case bo.RIGHT:m-=l,p=l/2}switch(n){case bo.CENTER:u/=2,g-=u,x+=u;break;case bo.BOTTOM:x+=u,f=-u/2;break;case bo.TOP:g-=u,f=u/2}}const b=[],T=[],y=[];y[0]=[0,0,1,0,1,1,0,1],y[1]=[0,0,1,0,1,1,0,1],t!==bo.ROTATE_TILE&&t!==bo.ROTATE_ROW||(y[1]=[1,1,0,1,0,0,1,0]),t!==bo.FLIP_TILE&&t!==bo.FLIP_ROW||(y[1]=[1,0,0,0,0,1,1,1]),t!==bo.FLIP_N_ROTATE_TILE&&t!==bo.FLIP_N_ROTATE_ROW||(y[1]=[0,1,1,1,1,0,0,0]);let S=[];const C=[],E=[];let A=0;for(let e=0;e0||u>0){const e=u>0&&(n===bo.CENTER||n===bo.TOP),o=u>0&&(n===bo.CENTER||n===bo.BOTTOM),h=l>0&&(r===bo.CENTER||r===bo.RIGHT),y=l>0&&(r===bo.CENTER||r===bo.LEFT);let P,R,I,M,O=[];if(e&&h&&(b.push(m+p,g+f,0),b.push(-d+p,g+f,0),b.push(-d+p,g+u+f,0),b.push(m+p,g+u+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,R=1-u/s,I=1,M=1,O=[P,R,I,R,I,M,P,M],t===bo.ROTATE_ROW&&(O=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),t===bo.FLIP_ROW&&(O=[1-P,R,1-I,R,1-I,M,1-P,M]),t===bo.FLIP_N_ROTATE_ROW&&(O=[P,1-R,I,1-R,I,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&y&&(b.push(d+p,g+f,0),b.push(v+p,g+f,0),b.push(v+p,g+u+f,0),b.push(d+p,g+u+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,R=1-u/s,I=l/i,M=1,O=[P,R,I,R,I,M,P,M],(t===bo.ROTATE_ROW||t===bo.ROTATE_TILE&&a%2==0)&&(O=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),(t===bo.FLIP_ROW||t===bo.FLIP_TILE&&a%2==0)&&(O=[1-P,R,1-I,R,1-I,M,1-P,M]),(t===bo.FLIP_N_ROTATE_ROW||t===bo.FLIP_N_ROTATE_TILE&&a%2==0)&&(O=[P,1-R,I,1-R,I,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(b.push(m+p,_+f,0),b.push(-d+p,_+f,0),b.push(-d+p,x+f,0),b.push(m+p,x+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,R=0,I=1,M=u/s,O=[P,R,I,R,I,M,P,M],(t===bo.ROTATE_ROW&&c%2==1||t===bo.ROTATE_TILE&&c%1==0)&&(O=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),(t===bo.FLIP_ROW&&c%2==1||t===bo.FLIP_TILE&&c%2==0)&&(O=[1-P,R,1-I,R,1-I,M,1-P,M]),(t===bo.FLIP_N_ROTATE_ROW&&c%2==1||t===bo.FLIP_N_ROTATE_TILE&&c%2==0)&&(O=[P,1-R,I,1-R,I,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&y&&(b.push(d+p,_+f,0),b.push(v+p,_+f,0),b.push(v+p,x+f,0),b.push(d+p,x+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,R=0,I=l/i,M=u/s,O=[P,R,I,R,I,M,P,M],(t===bo.ROTATE_ROW&&c%2==1||t===bo.ROTATE_TILE&&(c+a)%2==1)&&(O=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),(t===bo.FLIP_ROW&&c%2==1||t===bo.FLIP_TILE&&(c+a)%2==1)&&(O=[1-P,R,1-I,R,1-I,M,1-P,M]),(t===bo.FLIP_N_ROTATE_ROW&&c%2==1||t===bo.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(O=[P,1-R,I,1-R,I,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];P=0,R=1-u/s,I=1,M=1,e[0]=[P,R,I,R,I,M,P,M],e[1]=[P,R,I,R,I,M,P,M],t!==bo.ROTATE_TILE&&t!==bo.ROTATE_ROW||(e[1]=[1-P,1-R,1-I,1-R,1-I,1-M,1-P,1-M]),t!==bo.FLIP_TILE&&t!==bo.FLIP_ROW||(e[1]=[1-P,R,1-I,R,1-I,M,1-P,M]),t!==bo.FLIP_N_ROTATE_TILE&&t!==bo.FLIP_N_ROTATE_ROW||(e[1]=[P,1-R,I,1-R,I,1-M,P,1-M]);for(let s=0;sNu(e,{radius:t,tessellation:i,sideOrientation:n,updatable:r},s);const ku={CreateTiledPlane:Lu};function Vu(e){const t=e.faceUV||new Array(6),i=e.faceColors,s=e.pattern||bo.NO_FLIP,r=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,a=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new _e(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new Ee(1,1,1,1));const d=r/2,_=n/2,p=o/2,f=[];for(let e=0;e<2;e++)f[e]=Bu({pattern:s,tileWidth:a,tileHeight:l,width:r,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)f[e]=Bu({pattern:s,tileWidth:a,tileHeight:l,width:o,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});let m=c;c===bo.BOTTOM?m=bo.TOP:c===bo.TOP&&(m=bo.BOTTOM);for(let e=4;e<6;e++)f[e]=Bu({pattern:s,tileWidth:a,tileHeight:l,width:r,height:o,alignVertical:m,alignHorizontal:h,sideOrientation:u});let g=[],v=[],x=[],b=[];const T=[],y=[],S=[],C=[];let E=0,A=0;for(let e=0;e<6;e++){const s=f[e].positions.length;y[e]=[],S[e]=[];for(let t=0;te+A))),A+=y[e].length,i)for(let t=0;t<4;t++)T.push(i[e].r,i[e].g,i[e].b,i[e].a)}const P=new de(0,0,p),R=fe.RotationY(Math.PI);g=y[0].map((e=>de.TransformNormal(e,R).add(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),v=S[0].map((e=>de.TransformNormal(e,R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),g=g.concat(y[1].map((e=>e.subtract(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const I=new de(d,0,0),M=fe.RotationY(-Math.PI/2);g=g.concat(y[2].map((e=>de.TransformNormal(e,M).add(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[2].map((e=>de.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=fe.RotationY(Math.PI/2);g=g.concat(y[3].map((e=>de.TransformNormal(e,O).subtract(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[3].map((e=>de.TransformNormal(e,O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=new de(0,_,0),w=fe.RotationX(Math.PI/2);g=g.concat(y[4].map((e=>de.TransformNormal(e,w).add(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[4].map((e=>de.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=fe.RotationX(-Math.PI/2);g=g.concat(y[5].map((e=>de.TransformNormal(e,N).subtract(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[5].map((e=>de.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),cn._ComputeSides(u,g,b,v,x);const F=new cn;if(F.indices=b,F.positions=g,F.normals=v,F.uvs=x,i){const e=u===cn.DOUBLESIDE?T.concat(T):T;F.colors=e}return F}function Uu(e,t,i=null){const s=new bo(e,i);return t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Vu(t).applyToMesh(s,t.updatable),s}cn.CreateTiledPlane=Bu;const Gu={CreateTiledBox:Uu};function zu(e){const t=[],i=[],s=[],r=[],n=e.radius||2,o=e.tube||.5,a=e.radialSegments||32,l=e.tubularSegments||32,h=e.p||2,c=e.q||3,u=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,d=e=>{const t=Math.cos(e),i=Math.sin(e),s=c/h*e,r=Math.cos(s),o=n*(2+r)*.5*t,a=n*(2+r)*i*.5,l=n*Math.sin(s)*.5;return new de(o,a,l)};let _,p;for(_=0;_<=a;_++){const e=_%a/a*2*h*Math.PI,t=d(e),s=d(e+.01),n=s.subtract(t);let c=s.add(t);const u=de.Cross(n,c);for(c=de.Cross(u,n),u.normalize(),c.normalize(),p=0;pWu(e,{radius:t,tube:i,radialSegments:s,tubularSegments:r,p:n,q:o,sideOrientation:h,updatable:l},a);const Xu={effect:null,subMesh:null};class Yu extends Ra{constructor(e,t,i,s={},r=!0){super(e,t,r),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new fe,this._cachedWorldViewProjectionMatrix=new fe,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...s}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return s>=0&&this.options.defines.splice(s,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=s?i._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),o=[],a=[],l=new ja;let h=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(a.push(ys.MatricesIndicesExtraKind),a.push(ys.MatricesWeightsExtraKind));const t=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let _=0;const p=e?e.morphTargetManager:null;if(p){const e=p.supportsUVs&&-1!==o.indexOf("#define UV1"),t=p.supportsTangents&&-1!==o.indexOf("#define TANGENT"),i=p.supportsNormals&&-1!==o.indexOf("#define NORMAL");_=p.numMaxInfluencers||p.numInfluencers,e&&o.push("#define MORPHTARGETS_UV"),t&&o.push("#define MORPHTARGETS_TANGENT"),i&&o.push("#define MORPHTARGETS_NORMAL"),_>0&&o.push("#define MORPHTARGETS"),p.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+_);for(let s=0;s<_;s++)a.push(ys.PositionKind+s),i&&a.push(ys.NormalKind+s),t&&a.push(ys.TangentKind+s),e&&a.push(ys.UVKind+"_"+s);_>0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),zn(a,0,o)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(An(c),Pn(this,r,o)),r.fogEnabled&&e?.applyFog&&r.fogMode!==dr.FOGMODE_NONE&&(o.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),h=this.customShaderNameResolve(this.name,c,u,d,o,a));const f=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=f?.effect??null,g=f?.defines??null,v=o.join("\n");let x=m;return g!==v&&(x=n.createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:v,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(x,v,this._materialContext):f&&f.setEffect(x,v),this._onEffectCreatedObservable&&(Xu.effect=x,Xu.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(Xu))),f._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(m!==x&&r.resetCachedMaterial(),f._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(-1!==this._options.uniforms.indexOf("world")&&s.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(n&&a&&a.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&kn(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew Yu(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew Yu(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,Vo.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Ce.FromArray(e)));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,Ee.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Ee.FromArray(e)));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,ue.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,de.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,_e.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,pe.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,fe.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise(((r,n)=>{const o=new At;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=this.Parse(t,i||se.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((s,r)=>{const n=new At;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.shaderMaterial),a=this.Parse(o,t||se.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Yu.SnippetUrl="https://snippet.babylonjs.com",Yu.CreateFromSnippetAsync=Yu.ParseFromSnippetAsync,ee("BABYLON.ShaderMaterial",Yu);bi.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",bo._LinesMeshParser=(e,t)=>Qu.Parse(e,t);class Qu extends bo{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,s=null,r,n,o,a){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new Ce(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const l={attributes:[ys.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===o?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(ys.ColorKind)):(l.uniforms.push("color"),this._color4=new Ee),a?this.material=a:(this.material=new Yu("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=uo.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(uo.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(uo.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new Qu(e,this.getScene(),t,this,i)}createInstance(e){const t=new ju(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Qu(e.name,t);return i.color=Ce.FromArray(e.color),i.alpha=e.alpha,i}}class ju extends To{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Ku(e){const t=[],i=[],s=e.lines,r=e.colors,n=[];let o=0;for(let e=0;e0&&(t.push(o-1),t.push(o)),o++}}const a=new cn;return a.indices=t,a.positions=i,r&&(a.colors=n),a}function $u(e){const t=e.dashSize||3,i=e.gapSize||1,s=e.dashNb||200,r=e.points,n=[],o=[],a=de.Zero();let l=0,h=0,c=0,u=0,d=0,_=0,p=0;for(p=0;p{const t=de.Zero(),i=e.length/6;let n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0;for(u=0;uZu(e,{points:t,updatable:s,instance:r},i),bo.CreateDashedLines=(e,t,i,s,r,n=null,o,a)=>Ju(e,{points:t,dashSize:i,gapSize:s,dashNb:r,updatable:o,instance:a},n);class td extends ue{constructor(e,t){super(e.x,e.y),this.index=t}}class id{constructor(){this.elements=[]}add(e){const t=[];return e.forEach((e=>{const i=new td(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new ue(this.elements[0].x,this.elements[0].y),t=new ue(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class sd{static Rectangle(e,t,i,s){return[new ue(e,t),new ue(i,t),new ue(i,s),new ue(e,s)]}static Circle(e,t=0,i=0,s=32){const r=[];let n=0;const o=2*Math.PI/s;for(let a=0;a!isNaN(e)));let i;const s=[];for(i=0;i<(2147483646&t.length);i+=2)s.push(new ue(t[i],t[i+1]));return s}static StartingAt(e,t){return br.StartingAt(e,t)}}class rd{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){let r;this._points=new id,this._outlinepoints=new id,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||se.LastCreatedScene,r=t instanceof br?t.getPoints():t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),void 0===this.bjsEarcut&&we.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new id;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new bo(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(ys.PositionKind,r.positions,e),s.setVerticesData(ys.NormalKind,r.normals,e),s.setVerticesData(ys.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new cn,s=[],r=[],n=[],o=this._points.computeBounds();this._points.elements.forEach((e=>{s.push(0,1,0),r.push(e.x,0,e.y),n.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){const i=r.length/3;this._points.elements.forEach((t=>{s.push(0,-1,0),r.push(t.x,-e,t.y),n.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(r,s,n,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,a,l){let h=e.length/3,c=0;for(let u=0;ul?yl?S1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||bo.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return ud(e,r,s,null,null,n,o,a,l,h,!0,i,!!c,bo._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function ud(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x){const b=(e,t,i,s,r,n,o,a,l,h,c)=>{const u=i.getTangents(),d=i.getNormals(),_=i.getBinormals(),p=i.getDistances();if(c)for(let e=0;e0){let t=u[e-1];de.Dot(t,u[e])<0&&u[e].scaleInPlace(-1),t=d[e-1],de.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=_[e-1],de.Dot(t,_[e])<0&&_[e].scaleInPlace(-1)}let f=0;const m=h&&a?a:()=>null!==n?n:0,g=h&&o?o:()=>null!==r?r:1;let v=l===bo.NO_CAP||l===bo.CAP_END?0:2;const x=ge.Matrix[0];for(let i=0;i{const t=Array(),i=de.Zero();let s;for(s=0;s3?0:h,c,x);const S=Ou(e,{pathArray:y,closeArray:a,closePath:l,updatable:d,sideOrientation:_,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},u);return S._creationDataStorage.pathArray=y,S._creationDataStorage.path3D=T,S._creationDataStorage.cap=h,S}cn.CreatePolygon=nd,bo.CreatePolygon=(e,t,i,s,r,n,o=earcut)=>od(e,{shape:t,holes:s,updatable:r,sideOrientation:n},i,o),bo.ExtrudePolygon=(e,t,i,s,r,n,o,a=earcut)=>ad(e,{shape:t,holes:r,depth:i,updatable:n,sideOrientation:o},s,a);const dd={ExtrudeShape:hd,ExtrudeShapeCustom:cd};function _d(e,t,i=null){const s=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,r=void 0===t.closed||t.closed,n=t.shape,o=t.radius||1,a=t.tessellation||64,l=t.clip||0,h=t.updatable,c=bo._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||bo.NO_CAP,d=2*Math.PI,_=[],p=t.invertUV||!1;let f=0,m=0;const g=d/a*s;let v,x;for(f=0;f<=a-l;f++){for(x=[],u!=bo.CAP_START&&u!=bo.CAP_ALL||(x.push(new de(0,n[0].y,0)),x.push(new de(Math.cos(f*g)*n[0].x*o,n[0].y,Math.sin(f*g)*n[0].x*o))),m=0;mhd(e,{shape:t,path:i,scale:s,rotation:r,cap:0===n?0:n||bo.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),bo.ExtrudeShapeCustom=(e,t,i,s,r,n,o,a,l,h,c,u)=>cd(e,{shape:t,path:i,scaleFunction:s,rotationFunction:r,ribbonCloseArray:n,ribbonClosePath:o,cap:0===a?0:a||bo.NO_CAP,sideOrientation:c,instance:u,updatable:h},l);const pd={CreateLathe:_d};function fd(e,t,i=null){const s=t.path;let r=t.instance,n=1;void 0!==t.radius?n=t.radius:r&&(n=r._creationDataStorage.radius);const o=t.tessellation||64,a=t.radiusFunction||null;let l=t.cap||bo.NO_CAP;const h=t.invertUV||!1,c=t.updatable,u=bo._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const d=(e,t,i,s,r,n,o,a)=>{const l=t.getTangents(),h=t.getNormals(),c=t.getDistances(),u=2*Math.PI/r*a,d=n||(()=>s);let _,p,f,m;const g=ge.Matrix[0];let v=o===bo.NO_CAP||o===bo.CAP_END?0:2;for(let t=0;t{const s=Array();for(let r=0;r3?0:l,p=d(s,_,new Array,n,o,a,l,t.arc);const f=Ou(e,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return f._creationDataStorage.pathArray=p,f._creationDataStorage.path3D=_,f._creationDataStorage.tessellation=o,f._creationDataStorage.cap=l,f._creationDataStorage.arc=t.arc,f._creationDataStorage.radius=n,f}bo.CreateLathe=(e,t,i,s,r,n,o)=>_d(e,{shape:t,radius:i,tessellation:s,sideOrientation:o,updatable:n},r);const md={CreateTube:fd};function gd(e){const t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,s=e.size,r=e.sizeX||s||1,n=e.sizeY||s||1,o=e.sizeZ||s||1,a=e.custom||t[i],l=a.face.length,h=e.faceUV||new Array(l),c=e.faceColors,u=void 0===e.flat||e.flat,d=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,_=[],p=[],f=[],m=[],g=[];let v=0,x=0;const b=[];let T,y,S,C,E,A,P=0,R=0;if(u)for(R=0;Rfd(e,{path:t,radius:i,tessellation:s,radiusFunction:r,arc:1,cap:n,updatable:a,sideOrientation:l,instance:h},o);const xd={CreatePolyhedron:vd};cn.CreatePolyhedron=gd,bo.CreatePolyhedron=(e,t,i)=>vd(e,t,i);const bd=new de(1,0,0),Td=new de(-1,0,0),yd=new de(0,1,0),Sd=new de(0,-1,0),Cd=new de(0,0,1),Ed=new de(0,0,-1);class Ad{constructor(e=de.Zero(),t=de.Up(),i=ue.Zero(),s=0,r=0,n=null,o=null,a=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=a,this.matrixWeightsOverride=l}clone(){return new Ad(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}function Pd(e,t,i){const s=!!t.skeleton,r=i.localMode||s,n=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,o=t.getIndices(),a=s?t.getPositionData(!0,!0):t.getVerticesData(ys.PositionKind),l=s?t.getNormalsData(!0,!0):t.getVerticesData(ys.NormalKind),h=r?s?t.getVerticesData(ys.PositionKind):a:null,c=r?s?t.getVerticesData(ys.NormalKind):l:null,u=t.getVerticesData(ys.UVKind),d=s?t.getVerticesData(ys.MatricesIndicesKind):null,_=s?t.getVerticesData(ys.MatricesWeightsKind):null,p=s?t.getVerticesData(ys.MatricesIndicesExtraKind):null,f=s?t.getVerticesData(ys.MatricesWeightsExtraKind):null,m=i.position||de.Zero();let g=i.normal||de.Up();const v=i.size||de.One(),x=i.angle||0;if(!g){const e=new de(0,0,1),i=t.getScene().activeCamera,s=de.TransformCoordinates(e,i.getWorldMatrix());g=i.globalPosition.subtract(s)}const b=-Math.atan2(g.z,g.x)-Math.PI/2,T=Math.sqrt(g.x*g.x+g.z*g.z),y=Math.atan2(g.y,T),S=new cn;S.indices=[],S.positions=[],S.normals=[],S.uvs=[],S.matricesIndices=s?[]:null,S.matricesWeights=s?[]:null,S.matricesIndicesExtra=p?[]:null,S.matricesWeightsExtra=f?[]:null;let C=0;const E=(e,t)=>{const s=new Ad;if(!o||!a||!l)return s;const r=o[e];if(s.vertexIdx=3*r,s.vertexIdxForBones=4*r,s.position=new de(a[3*r],a[3*r+1],a[3*r+2]),de.TransformCoordinatesToRef(s.position,t,s.position),s.normal=new de(l[3*r],l[3*r+1],l[3*r+2]),de.TransformNormalToRef(s.normal,t,s.normal),i.captureUVS&&u){const e=u[2*r+1];s.uv=new ue(u[2*r],dn.UseOpenGLOrientationForUV?1-e:e)}return s},A=[0,0,0,0],P=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(de.Dot(v,t)),s=(e,t,i,s)=>{for(let r=0;r{const n=de.GetClipFactor(e.position,r.position,t,i);let o=A,a=A;if(d&&_){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=e.matrixIndicesOverride??d,l=e.matrixWeightsOverride??_,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,c=r.matrixIndicesOverride??d,u=r.matrixWeightsOverride??_;o=[0,0,0,0],a=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(l[t+e]>0){const r=s(c,i[t+e],h,4);o[p]=i[t+e],a[p]=xe.Lerp(l[t+e],r>=0?u[r]:0,n),p++}for(let e=0;e<4&&p<4;++e){const r=c[h+e];-1===s(i,r,t,4)&&(o[p]=r,a[p]=xe.Lerp(0,u[h+e],n),p++)}const f=a[0]+a[1]+a[2]+a[3];a[0]/=f,a[1]/=f,a[2]/=f,a[3]/=f}const l=e.localPositionOverride?e.localPositionOverride[0]:h?.[e.vertexIdx]??0,u=e.localPositionOverride?e.localPositionOverride[1]:h?.[e.vertexIdx+1]??0,p=e.localPositionOverride?e.localPositionOverride[2]:h?.[e.vertexIdx+2]??0,f=r.localPositionOverride?r.localPositionOverride[0]:h?.[r.vertexIdx]??0,m=r.localPositionOverride?r.localPositionOverride[1]:h?.[r.vertexIdx+1]??0,g=r.localPositionOverride?r.localPositionOverride[2]:h?.[r.vertexIdx+2]??0,v=e.localNormalOverride?e.localNormalOverride[0]:c?.[e.vertexIdx]??0,x=e.localNormalOverride?e.localNormalOverride[1]:c?.[e.vertexIdx+1]??0,b=e.localNormalOverride?e.localNormalOverride[2]:c?.[e.vertexIdx+2]??0,T=v+((r.localNormalOverride?r.localNormalOverride[0]:c?.[r.vertexIdx]??0)-v)*n,y=x+((r.localNormalOverride?r.localNormalOverride[1]:c?.[r.vertexIdx+1]??0)-x)*n,S=b+((r.localNormalOverride?r.localNormalOverride[2]:c?.[r.vertexIdx+2]??0)-b)*n,C=Math.sqrt(T*T+y*y+S*S);return new Ad(de.Lerp(e.position,r.position,n),de.Lerp(e.normal,r.normal,n).normalize(),ue.Lerp(e.uv,r.uv,n),-1,-1,h?[l+(f-l)*n,u+(m-u)*n,p+(g-p)*n]:null,c?[T/C,y/C,S/C]:null,o,a)};let n=null;e.length>3&&(n=[]);for(let s=0;s0,d=de.Dot(e[s+1].position,t)-i>0,_=de.Dot(e[s+2].position,t)-i>0;switch(o=(u?1:0)+(d?1:0)+(_?1:0),o){case 0:e.length>3?(n.push(e[s]),n.push(e[s+1]),n.push(e[s+2])):n=e;break;case 1:if(n=n??new Array,u&&(a=e[s+1],l=e[s+2],h=r(e[s],a),c=r(e[s],l)),d){a=e[s],l=e[s+2],h=r(e[s+1],a),c=r(e[s+1],l),n.push(h),n.push(l.clone()),n.push(a.clone()),n.push(l.clone()),n.push(h.clone()),n.push(c);break}_&&(a=e[s],l=e[s+1],h=r(e[s+2],a),c=r(e[s+2],l)),a&&l&&h&&c&&(n.push(a.clone()),n.push(l.clone()),n.push(h),n.push(c),n.push(h.clone()),n.push(l.clone()));break;case 2:n=n??new Array,u||(a=e[s].clone(),l=r(a,e[s+1]),h=r(a,e[s+2]),n.push(a),n.push(l),n.push(h)),d||(a=e[s+1].clone(),l=r(a,e[s+2]),h=r(a,e[s]),n.push(a),n.push(l),n.push(h)),_||(a=e[s+2].clone(),l=r(a,e[s]),h=r(a,e[s+1]),n.push(a),n.push(l),n.push(h))}}return n},R=t instanceof bo?t:null,I=R?._thinInstanceDataStorage.matrixData,M=R?.thinInstanceCount||1,O=ge.Matrix[0];O.copyFrom(fe.IdentityReadOnly);for(let e=0;ePd(e,t,{position:i,normal:s,size:r,angle:n});class Id{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(Math.floor(e),we.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(Math.floor(t),we.Warn("y is not an integer, floor(y) used"))}clone(){return new Id(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(Math.floor(e),we.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),we.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(Math.floor(e),we.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),we.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=de.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new Id(0,0)}}class Md{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Od("icosahedron","Regular",[[0,j,-1],[-j,1,0],[-1,0,-j],[1,0,-j],[j,1,0],[0,j,1],[-1,0,j],[-j,-1,0],[0,-j,-1],[j,-1,0],[1,0,j],[0,-j,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,s=this.n;let r,n,o,a,l,h=i,c=1,u=0;0!==s&&(h=xe.HCF(i,s)),c=i/h,u=s/h;const d=Id.Zero(),_=new Id(i,s),p=new Id(-s,i+s),f=Id.Zero(),m=Id.Zero(),g=Id.Zero();let v,x,b,T,y=[];const S=[],C=this.vertByDist,E=(i,s,r,n)=>{v=i+"|"+r,x=s+"|"+n,v in t||x in t?v in t&&!(x in t)?t[x]=t[v]:x in t&&!(v in t)&&(t[v]=t[x]):(t[v]=e,t[x]=e,e++),C[r][0]>2?S[t[v]]=[-C[r][0],C[r][1],t[v]]:S[t[v]]=[y[C[r][0]],C[r][1],t[v]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let x=0;x<20;x++){if(y=this.IDATA.face[x],o=y[2],a=y[1],l=y[0],b=d.x+"|"+d.y,v=x+"|"+b,v in t||(t[v]=o,S[o]=[y[C[b][0]],C[b][1]]),b=_.x+"|"+_.y,v=x+"|"+b,v in t||(t[v]=a,S[a]=[y[C[b][0]],C[b][1]]),b=p.x+"|"+p.y,v=x+"|"+b,v in t||(t[v]=l,S[l]=[y[C[b][0]],C[b][1]]),r=this.IDATA.edgematch[x][0],n=this.IDATA.edgematch[x][1],"B"===n)for(let e=1;e2?S[t[v]]=[-C[b][0],C[b][1],t[v]]:S[t[v]]=[y[C[b][0]],C[b][1],t[v]])}this.closestTo=S,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&e0){const s=xe.HCF(e,t),r=e/s,n=t/s;for(let o=1;oe.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let e=0;e{const r=i.clone();return"A"===s&&r.rotateNeg120(e,t),"B"===s&&r.rotate120(e,t),r.x<0?r.y:r.x+r.y},d=[],_=[],p=[],f=[],m={},g=[];let v=-1,x=-1;for(let e=0;ee[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let e=0;et.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);const s=[];for(let e=0;e<12;e++)s[e]=e;let r=12;for(let e=0;e<12;e++){t[e].sort(((e,t)=>e[1]-t[1]));for(let i=0;ie[3]-t[3]));for(let e=0;e0;)r=t[a],this.face[r].indexOf(o)>-1?(n=(this.face[r].indexOf(o)+1)%3,o=this.face[r][n],i.push(o),s.push(r),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new Od("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let e=0;e{s=0,r=0,n=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],s+=a[0],r+=a[1],n+=a[2];e.vertex[t]=[s/3,r/3,n/3]}));return e}static BuildGeodesicData(e){const t=new Dd("Geodesic-m-n","Geodesic",[[0,j,-1],[-j,1,0],[-1,0,-j],[1,0,-j],[j,1,0],[0,j,1],[-1,0,j],[-j,-1,0],[0,-j,-1],[j,-1,0],[1,0,j],[0,-j,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;is){const e=r;r=s,s=e,we.Warn("n > m therefore m and n swapped")}const n=new Md;return n.build(s,r),vd(e,{custom:Dd.BuildGeodesicData(n),size:t.size,sizeX:t.sizeX,sizeY:t.sizeY,sizeZ:t.sizeZ,faceUV:t.faceUV,faceColors:t.faceColors,flat:t.flat,updatable:t.updatable,sideOrientation:t.sideOrientation,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}bo._GoldbergMeshParser=(e,t)=>Nd.Parse(e,t);class Nd extends bo{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(we.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(we.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(we.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=n.x+o*Math.cos(a+e*Math.PI/3),u=n.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=s;eEe.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>de.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>de.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>de.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>de.FromArray(e)));const s=new Nd(e.name,t);return s.goldbergData=i,s}}function Fd(e,t){const i=e.size,s=e.sizeX||i||1,r=e.sizeY||i||1,n=e.sizeZ||i||1,o=0===e.sideOrientation?0:e.sideOrientation||cn.DEFAULTSIDE,a=[],l=[],h=[],c=[];let u=1/0,d=-1/0,_=1/0,p=-1/0;for(let e=0;ea){const e=l;l=a,a=e,we.Warn("n > m therefore m and n swapped")}const h=new Md;h.build(a,l);const c=Dd.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new Nd(e,i);t.sideOrientation=bo._GetDefaultSideOrientation(t.sideOrientation),d._originalBuilderSideOrientation=t.sideOrientation,Fd(t,u).applyToMesh(d,t.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let e=0;e0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function kd(e,t,i,s,r,n){const o=n.glyphs[e]||n.glyphs["?"];if(!o)return null;const a=new Ld(r);if(o.o){const e=o.o.split(" ");for(let r=0,n=e.length;rK&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>K&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>K&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;i&&s&&r&&n&&o&&a&&t.getDescendants(!0).forEach((e=>{const t=e.getDescendants(!0)[0],l=e.getDescendants(!0)[1],{parentBody:h,parentBodyIndex:c}=t.metadata,{childBody:u,childBodyIndex:d}=l.metadata,_=this._getTransformFromBodyToRef(h,ge.Matrix[0],c),p=this._getTransformFromBodyToRef(u,ge.Matrix[1],d);_.decomposeToTransformNode(t),this._makeScalingUnitInPlace(t.scaling),p.decomposeToTransformNode(l),this._makeScalingUnitInPlace(l.scaling);const f=t.getDescendants(!0)[0];f.position.copyFrom(i);const m=l.getDescendants(!0)[0];m.position.copyFrom(s),pe.FromRotationMatrixToRef(fe.FromXYZAxesToRef(r,o,de.CrossToRef(r,o,ge.Vector3[0]),ge.Matrix[0]),f.rotationQuaternion),pe.FromRotationMatrixToRef(fe.FromXYZAxesToRef(n,a,de.CrossToRef(n,a,ge.Vector3[1]),ge.Matrix[1]),m.rotationQuaternion)}))}showImpostor(e,t){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}showInertia(e){if(!this._scene)return null;for(let t=0;tthis._updateInertiaMeshes(),this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),t}showConstraint(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugConstraints(),this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s-1&&this._debugMeshMeshes.splice(r,1),this._numMeshes--,this._numMeshes>0?(this._meshes[s]=this._meshes[this._numMeshes],this._impostors[s]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s0?(this._bodyMeshes[s]=this._bodyMeshes[this._numBodies],this._bodies[s]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}t&&0===this._numBodies&&this._scene.unregisterBeforeRender(this._renderFunction)}hideInertia(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s0?(this._constraints[s]=this._constraints[this._numConstraints],this._constraintMeshes[s]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&0===this._numConstraints&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new yc("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Ce.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new yc("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=yu("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=pe.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=Eu("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=pe.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=Ru("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=pe.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=lu("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=pe.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new bo(e.name,t,null,e);return i.setParent(e),i.position=de.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const s=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return we.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case ga.BoxImpostor:i=this._getDebugBoxMesh(s),e.getBoxSizeToRef(i.scaling);break;case ga.SphereImpostor:{i=this._getDebugSphereMesh(s);const t=e.getRadius();i.scaling.x=2*t,i.scaling.y=2*t,i.scaling.z=2*t;break}case ga.CapsuleImpostor:{i=this._getDebugCapsuleMesh(s);const t=e.object.getBoundingInfo();i.scaling.x=2*(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=2*(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}case ga.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,s));break;case ga.NoImpostor:t?t.getChildMeshes().filter((e=>e.physicsImpostor?1:0)).forEach((e=>{if(e.physicsImpostor&&"Mesh"===e.getClassName()){const t=e.getBoundingInfo(),r=t.boundingBox.minimum,n=t.boundingBox.maximum;switch(e.physicsImpostor.type){case ga.BoxImpostor:i=this._getDebugBoxMesh(s),i.position.copyFrom(r),i.position.addInPlace(n),i.position.scaleInPlace(.5);break;case ga.SphereImpostor:i=this._getDebugSphereMesh(s);break;case ga.CylinderImpostor:i=this._getDebugCylinderMesh(s);break;default:i=null}i&&(i.scaling.x=n.x-r.x,i.scaling.y=n.y-r.y,i.scaling.z=n.z-r.z,i.parent=e)}})):we.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case ga.CylinderImpostor:{i=this._getDebugCylinderMesh(s);const t=e.object.getBoundingInfo();i.scaling.x=(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new bo("custom",t),s=new cn,r=e.getGeometry();if(s.positions=r.positions,s.indices=r.indices,s.applyToMesh(i),e._pluginDataInstances){const t=new Float32Array(16*e._pluginDataInstances.length);i.thinInstanceSetBuffer("matrix",t,16,!1)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){const i=e.inertiaOrientation??pe.Identity(),s=e.inertia??de.Zero(),r=e.centerOfMass??de.Zero(),n=6*(s.x-s.y+s.z),o=Math.sqrt(Math.max(n,0)),a=12*s.x-n,l=Math.sqrt(Math.max(a,0)),h=12*s.z-n,c=Math.sqrt(Math.max(h,0)),u=ge.Vector3[0];u.set(c,o,l);const d=fe.ScalingToRef(u.x,u.y,u.z,ge.Matrix[0]),_=i.toRotationMatrix(ge.Matrix[1]),p=fe.TranslationToRef(r.x,r.y,r.z,ge.Matrix[2]);return d.multiplyToRef(_,t),t.multiplyToRef(p,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=Gd.CreateBox("custom",{size:1},t),s=fe.Identity();if(e._pluginDataInstances.length){const t=new Float32Array(16*e._pluginDataInstances.length);for(let i=0;i=0?fe.FromArrayToRef(s._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(s.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;if(!(i&&s&&r&&n&&o&&a))return null;const l=new bo("parentingDebugConstraint",t),h=e.getBodiesUsingConstraint();for(const e of h){const h=new xn("parentOfPair",t);h.parent=l;const{parentBody:c,parentBodyIndex:u,childBody:d,childBodyIndex:_}=e,p=this._getTransformFromBodyToRef(c,ge.Matrix[0],u),f=this._getTransformFromBodyToRef(d,ge.Matrix[1],_),m=new xn("parentCoordSystem",t);m.parent=h,m.metadata={parentBody:c,parentBodyIndex:u},p.decomposeToTransformNode(m);const g=new xn("childCoordSystem",t);g.parent=h,g.metadata={childBody:d,childBodyIndex:_},f.decomposeToTransformNode(g);const v=pe.FromRotationMatrix(fe.FromXYZAxesToRef(r,o,r.cross(o),ge.Matrix[0])),x=pe.FromRotationMatrix(fe.FromXYZAxesToRef(n,a,n.cross(a),ge.Matrix[0])),b=i,T=s,y=new xn("constraint_parent",t);y.position.copyFrom(b),y.rotationQuaternion=v,y.parent=m;const S=new xn("constraint_child",t);S.parent=g,S.position.copyFrom(T),S.rotationQuaternion=x;const C=new gu(t,this._constraintAxesSize);C.xAxis.parent=y,C.yAxis.parent=y,C.zAxis.parent=y;const E=new gu(t,this._constraintAxesSize);E.xAxis.parent=S,E.yAxis.parent=S,E.zAxis.parent=S}return l}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(let e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}class Wd{static CreateAndShow(e,t,i){const s=new Wd(e);return s.show(t,i),s}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const t=this.ray;this._renderFunction=()=>this._render(),this._scene=e,this._renderPoints=[t.origin,t.origin.add(t.direction.scale(t.length))],this._renderLine=Zu("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){const e=this.ray;if(!e)return;const t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),this._renderPoints[0].copyFrom(e.origin),Zu("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),this._renderLine?.refreshBoundingInfo()}attachToMesh(e,t,i,s){this._attachedToMesh=e;const r=this.ray;r&&(r.direction||(r.direction=de.Zero()),r.origin||(r.origin=de.Zero()),s&&(r.length=s),i||(i=de.Zero()),t||(t=new de(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add((()=>this._updateToMesh())),this._onAfterStepObserver=this._scene.onAfterStepObservable.add((()=>this._updateToMesh()))),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh.isDisposed()?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),de.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}class Hd{static CreateBoneWeightShader(e,t){const i=e.skeleton,s=e.colorBase??Ce.Black(),r=e.colorZero??Ce.Blue(),n=e.colorQuarter??Ce.Green(),o=e.colorHalf??Ce.Yellow(),a=e.colorFull??Ce.Red(),l=e.targetBoneIndex??0;Ti.ShadersStore["boneWeights:"+i.name+"VertexShader"]="precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",Ti.ShadersStore["boneWeights:"+i.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const h=new Yu("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",s),h.setColor3("colorZero",r),h.setColor3("colorQuarter",n),h.setColor3("colorHalf",o),h.setColor3("colorFull",a),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=uo.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,s=e.colorMap??[{color:new Ce(1,.38,.18),location:0},{color:new Ce(.59,.18,1),location:.2},{color:new Ce(.59,1,.18),location:.4},{color:new Ce(1,.87,.17),location:.6},{color:new Ce(1,.17,.42),location:.8},{color:new Ce(.17,.68,1),location:1}],r=i.bones.length+1,n=Hd._CreateBoneMapColorBuffer(r,s,t),o=new Yu("boneWeights:"+i.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*i.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=uo.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const s=new Sc("temp",{width:e,height:1},i,!1),r=s.getContext(),n=r.createLinearGradient(0,0,e,0);t.forEach((e=>{n.addColorStop(e.location,e.color.toHexString())})),r.fillStyle=n,r.fillRect(0,0,e,1),s.update();const o=[],a=r.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eHd.DISPLAY_SPHERE_AND_SPURS&&(e=Hd.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,s=!0,r=3,n={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=s,this.renderingGroupId=r,this.options=n,this.color=Ce.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=n.pauseAnimations??!0,n.returnToRest=n.returnToRest??!1,n.displayMode=n.displayMode??Hd.DISPLAY_LINES,n.displayOptions=n.displayOptions??{},n.displayOptions.midStep=n.displayOptions.midStep??.235,n.displayOptions.midStepFactor=n.displayOptions.midStepFactor??.155,n.displayOptions.sphereBaseSize=n.displayOptions.sphereBaseSize??.15,n.displayOptions.sphereScaleUnit=n.displayOptions.sphereScaleUnit??2,n.displayOptions.sphereFactor=n.displayOptions.sphereFactor??.865,n.displayOptions.spurFollowsChild=n.displayOptions.spurFollowsChild??!1,n.displayOptions.showLocalAxes=n.displayOptions.showLocalAxes??!1,n.displayOptions.localAxesSize=n.displayOptions.localAxesSize??.075,n.computeBonesUsingShaders=n.computeBonesUsingShaders??!0,n.useAllBones=n.useAllBones??!0,this._boneIndices=new Set,!n.useAllBones){const e=t?.getVerticesData(ys.MatricesIndicesKind),i=t?.getVerticesData(ys.MatricesWeightsKind);if(e&&i)for(let t=0;tHd.DISPLAY_SPHERE_AND_SPURS&&(o=Hd.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){this.displayMode===Hd.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case Hd.DISPLAY_LINES:this._displayLinesUpdate();break;case Hd.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case Hd.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,s=0,r=0,n=0){const o=ge.Matrix[0],a=t.getParent();if(o.copyFrom(t.getLocalMatrix()),0!==s||0!==r||0!==n){const e=ge.Matrix[1];fe.IdentityToRef(e),e.setTranslationFromFloats(s,r,n),e.multiplyToRef(o,o)}a&&o.multiplyToRef(a.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let s,r;t?(s=t.getWorldMatrix(),r=t.position):(s=new fe,r=e[0].position);let n=0;for(let t=0;t=0;s--){const t=e[s],o=t.getParent();if(!o||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let a=this._debugLines[i];a||(a=[de.Zero(),de.Zero()],this._debugLines[i]=a),t.getAbsolutePositionToRef(r,a[0]),o.getAbsolutePositionToRef(r,a[1]),a[0].subtractInPlace(n),a[1].subtractInPlace(n),i++}s||r.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(fe.Identity())}_createSpur(e,t,i,s,r,n){const o=i.subtract(e),a=o.length(),l=o.normalize().scale(a),h=r.midStep||.165,c=r.midStepFactor||.215,u=l.scale(h),d=cd("skeletonViewer",{shape:[new de(1,-1,0),new de(1,1,0),new de(-1,1,0),new de(-1,-1,0),new de(1,-1,0)],path:[de.Zero(),u,l],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return a*c}return 0},sideOrientation:bo.DEFAULTSIDE,updatable:!1},n),_=d.getTotalVertices(),p=[],f=[];for(let e=0;e<_;e++)p.push(1,0,0,0),s&&r.spurFollowsChild&&e>9?f.push(s.getIndex(),0,0,0):f.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(ys.MatricesWeightsKind,p,!1),d.setVerticesData(ys.MatricesIndicesKind,f,!1),d.convertToFlatShadedMesh(),d}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(ys.PositionKind),i=this.mesh.getIndices(),s=this.mesh.getVerticesData(ys.MatricesWeightsKind),r=this.mesh.getVerticesData(ys.MatricesIndicesKind);if(!(t&&i&&s&&r))return null;const n=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new de(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let a=0;for(let l=0;l1e-5){de.FromArrayToRef(t,3*h,ge.Vector3[0]),n.minimizeInPlace(ge.Vector3[0]),o.maximizeInPlace(ge.Vector3[0]),a++;break}}}return a>1?{center:de.Center(n,o),radius:de.Distance(n,o)/2}:null}_buildSpheresAndSpurs(e=!0){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=this.utilityLayer?.utilityLayerScene,i=this.skeleton.bones,s=[],r=[],n=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let o=Number.NEGATIVE_INFINITY;const a=this.options.displayOptions||{};for(let n=0;n0)l.children.forEach((i=>{const s=new fe;i.getLocalMatrix().multiplyToRef(h,s);const n=new de;s.decompose(void 0,void 0,n);const u=de.Distance(c,n);u>o&&(o=u),e||r.push(this._createSpur(c,l,n,i,a,t))}));else{const i=this._getBoundingSphereForBone(l.getIndex());if(i&&(i.radius>o&&(o=i.radius),!e)){let e;const s=l.getParent();s?(this._getAbsoluteBindPoseToRef(s,h),h.decompose(void 0,void 0,ge.Vector3[0]),e=c.subtract(ge.Vector3[0]).normalize().scale(i.radius).add(c)):e=i.center.subtract(c).normalize().scale(i.radius).add(c),r.push(this._createSpur(c,l,e,null,a,t))}}const u=Eu("skeletonViewer",{segments:6,diameter:a.sphereBaseSize||.2,updatable:!0},t),d=u.getTotalVertices(),_=[],p=[];for(let e=0;e{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)})),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach((e=>{e.setEnabled(!1)})),this._visible=!1}update(){if(!this._visible)return;if(this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,ge.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,void 0!==this._light.shadowMinZ?this._light.shadowMinZ:this._camera.minZ),ge.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,void 0!==this._light.shadowMaxZ?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();ge.Vector3[2].copyFromFloats(ge.Vector3[1].x,ge.Vector3[1].y,ge.Vector3[0].z),ge.Vector3[3].copyFromFloats(ge.Vector3[1].x,ge.Vector3[0].y,ge.Vector3[0].z),ge.Vector3[4].copyFromFloats(ge.Vector3[0].x,ge.Vector3[0].y,ge.Vector3[0].z),ge.Vector3[5].copyFromFloats(ge.Vector3[0].x,ge.Vector3[1].y,ge.Vector3[0].z),de.TransformCoordinatesToRef(ge.Vector3[2],e,ge.Vector3[2]),de.TransformCoordinatesToRef(ge.Vector3[3],e,ge.Vector3[3]),de.TransformCoordinatesToRef(ge.Vector3[4],e,ge.Vector3[4]),de.TransformCoordinatesToRef(ge.Vector3[5],e,ge.Vector3[5]),ge.Vector3[6].copyFromFloats(ge.Vector3[1].x,ge.Vector3[1].y,ge.Vector3[1].z),ge.Vector3[7].copyFromFloats(ge.Vector3[1].x,ge.Vector3[0].y,ge.Vector3[1].z),ge.Vector3[8].copyFromFloats(ge.Vector3[0].x,ge.Vector3[0].y,ge.Vector3[1].z),ge.Vector3[9].copyFromFloats(ge.Vector3[0].x,ge.Vector3[1].y,ge.Vector3[1].z),de.TransformCoordinatesToRef(ge.Vector3[6],e,ge.Vector3[6]),de.TransformCoordinatesToRef(ge.Vector3[7],e,ge.Vector3[7]),de.TransformCoordinatesToRef(ge.Vector3[8],e,ge.Vector3[8]),de.TransformCoordinatesToRef(ge.Vector3[9],e,ge.Vector3[9]),Zu("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),Zu("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),Zu("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),Zu("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),Zu("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),Zu("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),ge.Vector3[2].toArray(this._nearPlaneVertices,0),ge.Vector3[3].toArray(this._nearPlaneVertices,3),ge.Vector3[4].toArray(this._nearPlaneVertices,6),ge.Vector3[5].toArray(this._nearPlaneVertices,9),this._lightHelperFrustumMeshes[6].geometry?.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),ge.Vector3[6].toArray(this._farPlaneVertices,0),ge.Vector3[7].toArray(this._farPlaneVertices,3),ge.Vector3[8].toArray(this._farPlaneVertices,6),ge.Vector3[9].toArray(this._farPlaneVertices,9),this._lightHelperFrustumMeshes[7].geometry?.updateVerticesDataDirectly("position",this._farPlaneVertices,0),ge.Vector3[2].toArray(this._rightPlaneVertices,0),ge.Vector3[6].toArray(this._rightPlaneVertices,3),ge.Vector3[7].toArray(this._rightPlaneVertices,6),ge.Vector3[3].toArray(this._rightPlaneVertices,9),this._lightHelperFrustumMeshes[8].geometry?.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),ge.Vector3[5].toArray(this._leftPlaneVertices,0),ge.Vector3[9].toArray(this._leftPlaneVertices,3),ge.Vector3[8].toArray(this._leftPlaneVertices,6),ge.Vector3[4].toArray(this._leftPlaneVertices,9),this._lightHelperFrustumMeshes[9].geometry?.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),ge.Vector3[2].toArray(this._topPlaneVertices,0),ge.Vector3[6].toArray(this._topPlaneVertices,3),ge.Vector3[9].toArray(this._topPlaneVertices,6),ge.Vector3[5].toArray(this._topPlaneVertices,9),this._lightHelperFrustumMeshes[10].geometry?.updateVerticesDataDirectly("position",this._topPlaneVertices,0),ge.Vector3[3].toArray(this._bottomPlaneVertices,0),ge.Vector3[7].toArray(this._bottomPlaneVertices,3),ge.Vector3[8].toArray(this._bottomPlaneVertices,6),ge.Vector3[4].toArray(this._bottomPlaneVertices,9),this._lightHelperFrustumMeshes[11].geometry?.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach((e=>{e.material?.dispose(),e.dispose()})),this._rootNode.dispose()}_createGeometry(){this._rootNode=new xn("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[ge.Vector3[0],ge.Vector3[1],ge.Vector3[2],ge.Vector3[3],ge.Vector3[4]];const e=Zu("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[ge.Vector3[5],ge.Vector3[6],ge.Vector3[7],ge.Vector3[8],ge.Vector3[9]];const t=Zu("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[ge.Vector3[10],ge.Vector3[11]];const i=Zu("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[ge.Vector3[12],ge.Vector3[0]];const s=Zu("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[ge.Vector3[1],ge.Vector3[2]];const r=Zu("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[ge.Vector3[3],ge.Vector3[4]];const n=Zu("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,s,r,n);const o=(e,t,i)=>{const s=new bo(e+"plane",this._scene),r=new yc(e+"PlaneMat",this._scene);s.material=r,s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,r.emissiveColor=t,r.alpha=this.transparency,r.backFaceCulling=!1,r.disableLighting=!0;const n=new cn;n.positions=i,n.indices=[0,1,2,0,2,3],n.applyToMesh(s,!0),this._lightHelperFrustumMeshes.push(s)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],o("near",new Ce(1,0,0),this._nearPlaneVertices),o("far",new Ce(.3,0,0),this._farPlaneVertices),o("right",new Ce(0,1,0),this._rightPlaneVertices),o("left",new Ce(0,.3,0),this._leftPlaneVertices),o("top",new Ce(0,0,1),this._topPlaneVertices),o("bottom",new Ce(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=ge.Vector3[2],this._nearLinesPoints[1]=ge.Vector3[3],this._nearLinesPoints[2]=ge.Vector3[4],this._nearLinesPoints[3]=ge.Vector3[5],this._nearLinesPoints[4]=ge.Vector3[2],this._farLinesPoints[0]=ge.Vector3[6],this._farLinesPoints[1]=ge.Vector3[7],this._farLinesPoints[2]=ge.Vector3[8],this._farLinesPoints[3]=ge.Vector3[9],this._farLinesPoints[4]=ge.Vector3[6],this._trLinesPoints[0]=ge.Vector3[2],this._trLinesPoints[1]=ge.Vector3[6],this._brLinesPoints[0]=ge.Vector3[3],this._brLinesPoints[1]=ge.Vector3[7],this._tlLinesPoints[0]=ge.Vector3[4],this._tlLinesPoints[1]=ge.Vector3[8],this._blLinesPoints[0]=ge.Vector3[5],this._blLinesPoints[1]=ge.Vector3[9]}_getInvertViewMatrix(){return fe.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),de.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}class Yd{}Yd.ALPHA_DISABLE=0,Yd.ALPHA_ADD=1,Yd.ALPHA_COMBINE=2,Yd.ALPHA_SUBTRACT=3,Yd.ALPHA_MULTIPLY=4,Yd.ALPHA_MAXIMIZED=5,Yd.ALPHA_ONEONE=6,Yd.ALPHA_PREMULTIPLIED=7,Yd.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Yd.ALPHA_INTERPOLATE=9,Yd.ALPHA_SCREENMODE=10,Yd.ALPHA_ONEONE_ONEONE=11,Yd.ALPHA_ALPHATOCOLOR=12,Yd.ALPHA_REVERSEONEMINUS=13,Yd.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Yd.ALPHA_ONEONE_ONEZERO=15,Yd.ALPHA_EXCLUSION=16,Yd.ALPHA_LAYER_ACCUMULATE=17,Yd.ALPHA_EQUATION_ADD=0,Yd.ALPHA_EQUATION_SUBSTRACT=1,Yd.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Yd.ALPHA_EQUATION_MAX=3,Yd.ALPHA_EQUATION_MIN=4,Yd.ALPHA_EQUATION_DARKEN=5,Yd.DELAYLOADSTATE_NONE=0,Yd.DELAYLOADSTATE_LOADED=1,Yd.DELAYLOADSTATE_LOADING=2,Yd.DELAYLOADSTATE_NOTLOADED=4,Yd.NEVER=512,Yd.ALWAYS=519,Yd.LESS=513,Yd.EQUAL=514,Yd.LEQUAL=515,Yd.GREATER=516,Yd.GEQUAL=518,Yd.NOTEQUAL=517,Yd.KEEP=7680,Yd.ZERO=0,Yd.REPLACE=7681,Yd.INCR=7682,Yd.DECR=7683,Yd.INVERT=5386,Yd.INCR_WRAP=34055,Yd.DECR_WRAP=34056,Yd.TEXTURE_CLAMP_ADDRESSMODE=0,Yd.TEXTURE_WRAP_ADDRESSMODE=1,Yd.TEXTURE_MIRROR_ADDRESSMODE=2,Yd.TEXTURE_CREATIONFLAG_STORAGE=1,Yd.TEXTUREFORMAT_ALPHA=0,Yd.TEXTUREFORMAT_LUMINANCE=1,Yd.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Yd.TEXTUREFORMAT_RGB=4,Yd.TEXTUREFORMAT_RGBA=5,Yd.TEXTUREFORMAT_RED=6,Yd.TEXTUREFORMAT_R=6,Yd.TEXTUREFORMAT_RG=7,Yd.TEXTUREFORMAT_RED_INTEGER=8,Yd.TEXTUREFORMAT_R_INTEGER=8,Yd.TEXTUREFORMAT_RG_INTEGER=9,Yd.TEXTUREFORMAT_RGB_INTEGER=10,Yd.TEXTUREFORMAT_RGBA_INTEGER=11,Yd.TEXTUREFORMAT_BGRA=12,Yd.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Yd.TEXTUREFORMAT_DEPTH32_FLOAT=14,Yd.TEXTUREFORMAT_DEPTH16=15,Yd.TEXTUREFORMAT_DEPTH24=16,Yd.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Yd.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Yd.TEXTUREFORMAT_STENCIL8=19,Yd.TEXTUREFORMAT_UNDEFINED=4294967295,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Yd.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Yd.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Yd.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Yd.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Yd.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Yd.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Yd.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Yd.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Yd.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Yd.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Yd.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Yd.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Yd.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Yd.TEXTURETYPE_UNSIGNED_BYTE=0,Yd.TEXTURETYPE_UNSIGNED_INT=0,Yd.TEXTURETYPE_FLOAT=1,Yd.TEXTURETYPE_HALF_FLOAT=2,Yd.TEXTURETYPE_BYTE=3,Yd.TEXTURETYPE_SHORT=4,Yd.TEXTURETYPE_UNSIGNED_SHORT=5,Yd.TEXTURETYPE_INT=6,Yd.TEXTURETYPE_UNSIGNED_INTEGER=7,Yd.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Yd.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Yd.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Yd.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Yd.TEXTURETYPE_UNSIGNED_INT_24_8=12,Yd.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Yd.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Yd.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Yd.TEXTURETYPE_UNDEFINED=16,Yd.TEXTURE_2D=3553,Yd.TEXTURE_2D_ARRAY=35866,Yd.TEXTURE_CUBE_MAP=34067,Yd.TEXTURE_CUBE_MAP_ARRAY=3735928559,Yd.TEXTURE_3D=32879,Yd.TEXTURE_NEAREST_SAMPLINGMODE=1,Yd.TEXTURE_NEAREST_NEAREST=1,Yd.TEXTURE_BILINEAR_SAMPLINGMODE=2,Yd.TEXTURE_LINEAR_LINEAR=2,Yd.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Yd.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Yd.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Yd.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Yd.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Yd.TEXTURE_NEAREST_LINEAR=7,Yd.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Yd.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Yd.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Yd.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Yd.TEXTURE_LINEAR_NEAREST=12,Yd.TEXTURE_EXPLICIT_MODE=0,Yd.TEXTURE_SPHERICAL_MODE=1,Yd.TEXTURE_PLANAR_MODE=2,Yd.TEXTURE_CUBIC_MODE=3,Yd.TEXTURE_PROJECTION_MODE=4,Yd.TEXTURE_SKYBOX_MODE=5,Yd.TEXTURE_INVCUBIC_MODE=6,Yd.TEXTURE_EQUIRECTANGULAR_MODE=7,Yd.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Yd.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Yd.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Yd.TEXTURE_FILTERING_QUALITY_HIGH=64,Yd.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Yd.TEXTURE_FILTERING_QUALITY_LOW=8,Yd.SCALEMODE_FLOOR=1,Yd.SCALEMODE_NEAREST=2,Yd.SCALEMODE_CEILING=3,Yd.MATERIAL_TextureDirtyFlag=1,Yd.MATERIAL_LightDirtyFlag=2,Yd.MATERIAL_FresnelDirtyFlag=4,Yd.MATERIAL_AttributesDirtyFlag=8,Yd.MATERIAL_MiscDirtyFlag=16,Yd.MATERIAL_PrePassDirtyFlag=32,Yd.MATERIAL_AllDirtyFlag=63,Yd.MATERIAL_TriangleFillMode=0,Yd.MATERIAL_WireFrameFillMode=1,Yd.MATERIAL_PointFillMode=2,Yd.MATERIAL_PointListDrawMode=3,Yd.MATERIAL_LineListDrawMode=4,Yd.MATERIAL_LineLoopDrawMode=5,Yd.MATERIAL_LineStripDrawMode=6,Yd.MATERIAL_TriangleStripDrawMode=7,Yd.MATERIAL_TriangleFanDrawMode=8,Yd.MATERIAL_ClockWiseSideOrientation=0,Yd.MATERIAL_CounterClockWiseSideOrientation=1,Yd.ACTION_NothingTrigger=0,Yd.ACTION_OnPickTrigger=1,Yd.ACTION_OnLeftPickTrigger=2,Yd.ACTION_OnRightPickTrigger=3,Yd.ACTION_OnCenterPickTrigger=4,Yd.ACTION_OnPickDownTrigger=5,Yd.ACTION_OnDoublePickTrigger=6,Yd.ACTION_OnPickUpTrigger=7,Yd.ACTION_OnPickOutTrigger=16,Yd.ACTION_OnLongPressTrigger=8,Yd.ACTION_OnPointerOverTrigger=9,Yd.ACTION_OnPointerOutTrigger=10,Yd.ACTION_OnEveryFrameTrigger=11,Yd.ACTION_OnIntersectionEnterTrigger=12,Yd.ACTION_OnIntersectionExitTrigger=13,Yd.ACTION_OnKeyDownTrigger=14,Yd.ACTION_OnKeyUpTrigger=15,Yd.PARTICLES_BILLBOARDMODE_Y=2,Yd.PARTICLES_BILLBOARDMODE_ALL=7,Yd.PARTICLES_BILLBOARDMODE_STRETCHED=8,Yd.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Yd.MESHES_CULLINGSTRATEGY_STANDARD=0,Yd.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Yd.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Yd.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Yd.SCENELOADER_NO_LOGGING=0,Yd.SCENELOADER_MINIMAL_LOGGING=1,Yd.SCENELOADER_SUMMARY_LOGGING=2,Yd.SCENELOADER_DETAILED_LOGGING=3,Yd.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Yd.PREPASS_POSITION_TEXTURE_TYPE=1,Yd.PREPASS_VELOCITY_TEXTURE_TYPE=2,Yd.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Yd.PREPASS_COLOR_TEXTURE_TYPE=4,Yd.PREPASS_DEPTH_TEXTURE_TYPE=5,Yd.PREPASS_NORMAL_TEXTURE_TYPE=6,Yd.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Yd.BUFFER_CREATIONFLAG_READ=1,Yd.BUFFER_CREATIONFLAG_WRITE=2,Yd.BUFFER_CREATIONFLAG_READWRITE=3,Yd.BUFFER_CREATIONFLAG_UNIFORM=4,Yd.BUFFER_CREATIONFLAG_VERTEX=8,Yd.BUFFER_CREATIONFLAG_INDEX=16,Yd.BUFFER_CREATIONFLAG_STORAGE=32,Yd.RENDERPASS_MAIN=0,Yd.INPUT_ALT_KEY=18,Yd.INPUT_CTRL_KEY=17,Yd.INPUT_META_KEY1=91,Yd.INPUT_META_KEY2=92,Yd.INPUT_META_KEY3=93,Yd.INPUT_SHIFT_KEY=16,Yd.SNAPSHOTRENDERING_STANDARD=0,Yd.SNAPSHOTRENDERING_FAST=1,Yd.PERSPECTIVE_CAMERA=0,Yd.ORTHOGRAPHIC_CAMERA=1,Yd.FOVMODE_VERTICAL_FIXED=0,Yd.FOVMODE_HORIZONTAL_FIXED=1,Yd.RIG_MODE_NONE=0,Yd.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Yd.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Yd.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Yd.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Yd.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Yd.RIG_MODE_VR=20,Yd.RIG_MODE_CUSTOM=22,Yd.MAX_SUPPORTED_UV_SETS=6,Yd.GL_ALPHA_EQUATION_ADD=32774,Yd.GL_ALPHA_EQUATION_MIN=32775,Yd.GL_ALPHA_EQUATION_MAX=32776,Yd.GL_ALPHA_EQUATION_SUBTRACT=32778,Yd.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Yd.GL_ALPHA_FUNCTION_SRC=768,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Yd.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Yd.GL_ALPHA_FUNCTION_DST_ALPHA=772,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Yd.GL_ALPHA_FUNCTION_DST_COLOR=774,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Yd.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Yd.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Yd.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Yd.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Yd.SnippetUrl="https://snippet.babylonjs.com",Yd.FOGMODE_NONE=0,Yd.FOGMODE_EXP=1,Yd.FOGMODE_EXP2=2,Yd.FOGMODE_LINEAR=3,Yd.BYTE=5120,Yd.UNSIGNED_BYTE=5121,Yd.SHORT=5122,Yd.UNSIGNED_SHORT=5123,Yd.INT=5124,Yd.UNSIGNED_INT=5125,Yd.FLOAT=5126,Yd.PositionKind="position",Yd.NormalKind="normal",Yd.TangentKind="tangent",Yd.UVKind="uv",Yd.UV2Kind="uv2",Yd.UV3Kind="uv3",Yd.UV4Kind="uv4",Yd.UV5Kind="uv5",Yd.UV6Kind="uv6",Yd.ColorKind="color",Yd.ColorInstanceKind="instanceColor",Yd.MatricesIndicesKind="matricesIndices",Yd.MatricesWeightsKind="matricesWeights",Yd.MatricesIndicesExtraKind="matricesIndicesExtra",Yd.MatricesWeightsExtraKind="matricesWeightsExtra";class Qd{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class jd extends gn{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new Qd){super(null),gn.Instances.push(this),void 0===e.deterministicLockstep&&(e.deterministicLockstep=!1),void 0!==e.timeStep&&(this._timeStep=e.timeStep),void 0===e.lockstepMaxSteps&&(e.lockstepMaxSteps=4),this._options=e,ie.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},we.Log(`Babylon.js v${gn.Version} - Null engine`);const t="undefined"!=typeof self?self:void 0!==i.g?i.g:window;"undefined"==typeof URL&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(t.Blob=function(){})}createVertexBuffer(e){const t=new Oi;return t.references=1,t}createIndexBuffer(e){const t=new Oi;return t.references=1,t}clear(e,t,i,s=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,s,r){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=null!==e&&Fi.IsWrapper(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,s=!1,r,n,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,s){return!0}setBool(e,t){return!0}setFloat4(e,t,i,s,r){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=0!==e,t||this.setDepthWrite(0===e),this._alphaMode=e)}bindBuffers(e,t,i){}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}draw(e,t,i,s){}drawElementsType(e,t,i,s){}drawArraysType(e,t,i,s){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u){const d=new Pi(this,Ai.Url),_=String(e);return d.url=_,d.generateMipMaps=!t,d.samplingMode=r,d.invertY=i,d.baseWidth=this._options.textureSize,d.baseHeight=this._options.textureSize,d.width=this._options.textureSize,d.height=this._options.textureSize,h&&(d.format=h),d.isReady=!0,n&&setTimeout((()=>{n(d)})),this._internalTexturesCache.push(d),d}_createHardwareRenderTargetWrapper(e,t,i){const s=new Ka(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.type=void 0===t.type?0:t.type,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.type=0,s.samplingMode=3);const r=new Pi(this,Ai.RenderTarget),n=e.width||e,o=e.height||e;return i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,r.baseWidth=n,r.baseHeight=o,r.width=n,r.height=o,r.isReady=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1),i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer;const r=new Pi(this,Ai.RenderTarget);return r.baseWidth=e,r.baseHeight=e,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new Pi(this,Ai.Raw);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),u}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r,e.type=n,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,s,r){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!r&&this.setViewport(this._cachedViewport,i,s)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new Oi;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,s=!1,r){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,s){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,s=0){}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){}_uploadImageToTexture(e,t,i=0,s=0){}}ki.prototype._debugPushGroup=function(e,t){},ki.prototype._debugPopGroup=function(e){},ki.prototype._debugInsertMarker=function(e,t){},ki.prototype._debugFlushPendingCommands=function(){};class Kd{constructor(){this._timeElapsedQueryEnded=!1}}class $d{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Sn.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Sn.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}gn.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},gn.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},gn.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},gn.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},gn.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},gn.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},gn.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},gn.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},gn.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},gn.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},gn.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new Kd;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery),this._currentNonTimestampToken=i}return i},gn.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const s=this._gl.getParameter(i.GPU_DISJOINT_EXT);let r=!1;if(e._endTimeQuery?r=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(r=this._getTimeQueryAvailability(e._timeElapsedQuery)),r&&!s){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},gn.prototype._captureGPUFrameTime=!1,gn.prototype._gpuFrameTime=new tr,gn.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},gn.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add((()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},gn.prototype._getGlAlgorithmType=function(e){return e===Sn.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(Sn.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Sn.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new $d),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Sn.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),Sn.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===Sn.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==Sn.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Sn.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const s=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(s.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};var qd=!0;gn.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},gn.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},gn.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},gn.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},gn.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},gn.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},gn.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},ki.prototype.createExternalTexture=function(e){return null},ki.prototype.setExternalTexture=function(e,t){throw new Error("setExternalTexture: This engine does not support external textures!")},ki.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const s=this._getInternalFormat(e.format),r=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},ki.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},ki.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},ki.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let s=0;s1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],s.readBuffer(r[t]),s.drawBuffers(r),s.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,s.COLOR_BUFFER_BIT,s.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];s.drawBuffers(r)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(a=t.depthTextureFormat)),g.label=t?.label??"MultiRenderTargetWrapper";const v=this._gl,x=v.createFramebuffer();this._bindUnboundFramebuffer(x);const b=e.width||e,T=e.height||e,y=[],S=[],C=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),E=this._setupFramebufferDepthAttachments(!C&&n,!o&&r,b,T);g._framebuffer=x,g._depthStencilBuffer=E,g._generateDepthBuffer=!o&&r,g._generateStencilBuffer=!C&&n,g._attachments=S;for(let e=0;e1||this.isWebGPU);const p=this.webGLVersion>1,f=v[p?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(S.push(f),-1===o)continue;const g=new Pi(this,Ai.MultiRenderTarget);y[e]=g,v.activeTexture(v["TEXTURE"+e]),v.bindTexture(o,g._hardwareTexture.underlyingResource),v.texParameteri(o,v.TEXTURE_MAG_FILTER,l.mag),v.texParameteri(o,v.TEXTURE_MIN_FILTER,l.min),v.texParameteri(o,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(o,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE);const x=this._getRGBABufferInternalSizedFormat(i,n,r),C=this._getInternalFormat(n),E=this._getWebGLTextureType(i);if(!p||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,x,b,T,0,C,E,null);g.isCube=!0}else v.texImage2D(v.TEXTURE_2D,0,x,b,T,0,C,E,null);else 35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=a,v.texImage3D(o,0,x,b,T,a,0,C,E,null);s&&v.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=b,g.baseHeight=T,g.width=b,g.height=T,g.isReady=!0,g.samples=1,g.generateMipMaps=s,g.samplingMode=t,g.type=i,g._useSRGBBuffer=r,g.format=n,this._internalTexturesCache.push(g)}if(o&&this._caps.depthTextureExtension){const e=new Pi(this,Ai.Depth);let t=5,i=v.DEPTH_COMPONENT16,r=v.DEPTH_COMPONENT,n=v.UNSIGNED_SHORT,o=v.DEPTH_ATTACHMENT;this.webGLVersion<2?i=v.DEPTH_COMPONENT:14===a?(t=1,n=v.FLOAT,i=v.DEPTH_COMPONENT32F):18===a?(t=0,n=v.FLOAT_32_UNSIGNED_INT_24_8_REV,i=v.DEPTH32F_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT):16===a?(t=0,n=v.UNSIGNED_INT,i=v.DEPTH_COMPONENT24,o=v.DEPTH_ATTACHMENT):13!==a&&17!==a||(t=12,n=v.UNSIGNED_INT_24_8,i=v.DEPTH24_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT),v.activeTexture(v.TEXTURE0),v.bindTexture(v.TEXTURE_2D,e._hardwareTexture.underlyingResource),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MAG_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MIN_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),v.texImage2D(v.TEXTURE_2D,0,i,b,T,0,r,n,null),v.framebufferTexture2D(v.FRAMEBUFFER,o,v.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=b,e.baseHeight=T,e.width=b,e.height=T,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=a,e.type=t,y[l]=e,this._internalTexturesCache.push(e)}return g.setTextures(y),i&&v.drawBuffers(S),this._bindUnboundFramebuffer(null),g.setLayerAndFaceIndices(f,p),this.resetTextureCache(),g},ki.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const s=e._attachments.length;if(0===s)return 1;const r=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const n=!!e._depthStencilBuffer;if(n&&(r.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(r.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof r.renderbufferStorageMultisample){const n=r.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(s.width,s.height,t,-1,this._getRGBABufferInternalSizedFormat(s.type,s.format,s._useSRGBBuffer),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),s.samples=t,o.push(a)}i&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},ki.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Pi(this,Ai.DepthStencil);if(i.isCube=!0,1===this.webGLVersion)return we.Error("Depth cube texture is not supported by WebGL 1."),i;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction);for(let t=0;t<6;t++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},ki.prototype._partialLoadFile=function(e,t,i,s,r=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&s(i)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},ki.prototype._cascadeLoadFiles=function(e,t,i,s=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,r,t,s)},ki.prototype._cascadeLoadImgs=function(e,t,i,s,r=null,n){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(s[a],a,o,e,t,i,r,n)},ki.prototype._partialLoadImg=function(e,t,i,s,r,n,o=null,a){const l=ns();Qi(e,(e=>{i[t]=e,i._internalCount++,s&&s.removePendingData(l),6===i._internalCount&&n&&n(r,i)}),((e,t)=>{s&&s.removePendingData(l),o&&o(e,t)}),s?s.offlineProvider:null,a),s&&s.addPendingData(l)},ki.prototype._setCubeMapTextureParams=function(e,t,i){const s=this._gl;s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)},ki.prototype.createCubeTextureBase=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=null,_=null,p=!1){const f=u||new Pi(this,Ai.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!s,f._lodGenerationScale=h,f._lodGenerationOffset=c,f._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!s),f!==u&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=a,f._files=i);const m=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));const g=e.split("?")[0],v=g.lastIndexOf("."),x=a||(v>-1?g.substring(v).toLowerCase():"");let b=null;for(const e of ki._TextureLoaders)if(e.canLoad(x)){b=e;break}const T=(u,g)=>{e===m?n&&u&&n(u.status+" "+u.statusText,g):(we.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!s,r,n,o,a,l,h,c,f,d,_,p))};if(b){const s=e=>{d&&d(f,e),b.loadCubeData(e,f,l,r,n)};i&&6===i.length?b.supportCascades?this._cascadeLoadFiles(t,(e=>s(e.map((e=>new Uint8Array(e))))),i,n):n?n("Textures type does not support cascades."):we.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>s(new Uint8Array(e))),void 0,void 0,!0,T)}else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,f,((e,t)=>{_&&_(e,t)}),i,n)}return this._internalTexturesCache.push(f),f},ki.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,_=!1){const p=this._gl;return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,(e=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?ki.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=i,a=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let h=o?this._getInternalFormat(o):p.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),s=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+s}Object.defineProperty(gn.prototype,"onBeforeViewRenderObservable",{get:function(){return Jd}}),Object.defineProperty(gn.prototype,"onAfterViewRenderObservable",{get:function(){return e_}}),Object.defineProperty(gn.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){this._inputElement!==e&&(this._inputElement=e,this._onEngineViewChanged?.())}}),gn.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},gn.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const s=this.getRenderingCanvas();s&&(e.width=s.width,e.height=s.height);const r={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(r),t&&!Array.isArray(t)&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),r},gn.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},gn.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const s=this.getRenderingCanvas();Jd.notifyObservers(e);const r=e.camera;let n=null,o=null,a=null;if(r&&(a=Array.isArray(r)?r[0].getScene():r.getScene(),n=a.activeCamera,o=a.activeCameras,this.activeView=e,Array.isArray(r)?a.activeCameras=r:(a.activeCamera=r,a.activeCameras=null)),e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),r=e!==t.width||s.width!==t.width||i!==t.height||s.height!==t.height;t.clientWidth&&t.clientHeight&&r&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!s.width||!s.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,s.width,s.height),i.drawImage(s,0,0),a&&(a.activeCameras=o,a.activeCamera=n),e_.notifyObservers(e),0))},gn.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},ki.prototype.createStorageBuffer=function(e,t){throw new Error("createStorageBuffer: Unsupported method in this engine!")},ki.prototype.updateStorageBuffer=function(e,t,i,s){},ki.prototype.readFromStorageBuffer=function(e,t,i,s){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")},ki.prototype.setStorageBuffer=function(e,t){throw new Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(gn.prototype,"texturesSupported",{get:function(){const e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(gn.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),gn.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},gn.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,s=t.length;i{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}i_.DEFAULT_BUFFER_SIZE=65536;const s_=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],r_=[()=>1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],n_=(e,t)=>s_[e]*r_[e](t),o_=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class a_{constructor(){this.preScaled=!1,this.l00=de.Zero(),this.l1_1=de.Zero(),this.l10=de.Zero(),this.l11=de.Zero(),this.l2_2=de.Zero(),this.l2_1=de.Zero(),this.l20=de.Zero(),this.l21=de.Zero(),this.l22=de.Zero()}addLight(e,t,i){ge.Vector3[0].set(t.r,t.g,t.b);const s=ge.Vector3[0],r=ge.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(n_(0,e),ge.Vector3[2]),this.l00.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(1,e),ge.Vector3[2]),this.l1_1.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(2,e),ge.Vector3[2]),this.l10.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(3,e),ge.Vector3[2]),this.l11.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(4,e),ge.Vector3[2]),this.l2_2.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(5,e),ge.Vector3[2]),this.l2_1.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(6,e),ge.Vector3[2]),this.l20.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(7,e),ge.Vector3[2]),this.l21.addInPlace(ge.Vector3[2]),r.scaleToRef(n_(8,e),ge.Vector3[2]),this.l22.addInPlace(ge.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(o_[0]),this.l1_1.scaleInPlace(o_[1]),this.l10.scaleInPlace(o_[2]),this.l11.scaleInPlace(o_[3]),this.l2_2.scaleInPlace(o_[4]),this.l2_1.scaleInPlace(o_[5]),this.l20.scaleInPlace(o_[6]),this.l21.scaleInPlace(o_[7]),this.l22.scaleInPlace(o_[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(s_[0]),this.l1_1.scaleInPlace(s_[1]),this.l10.scaleInPlace(s_[2]),this.l11.scaleInPlace(s_[3]),this.l2_2.scaleInPlace(s_[4]),this.l2_1.scaleInPlace(s_[5]),this.l20.scaleInPlace(s_[6]),this.l21.scaleInPlace(s_[7]),this.l22.scaleInPlace(s_[8])}updateFromArray(e){return de.FromArrayToRef(e[0],0,this.l00),de.FromArrayToRef(e[1],0,this.l1_1),de.FromArrayToRef(e[2],0,this.l10),de.FromArrayToRef(e[3],0,this.l11),de.FromArrayToRef(e[4],0,this.l2_2),de.FromArrayToRef(e[5],0,this.l2_1),de.FromArrayToRef(e[6],0,this.l20),de.FromArrayToRef(e[7],0,this.l21),de.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return de.FromFloatsToRef(e[0],e[1],e[2],this.l00),de.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),de.FromFloatsToRef(e[6],e[7],e[8],this.l10),de.FromFloatsToRef(e[9],e[10],e[11],this.l11),de.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),de.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),de.FromFloatsToRef(e[18],e[19],e[20],this.l20),de.FromFloatsToRef(e[21],e[22],e[23],this.l21),de.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new a_).updateFromArray(e)}static FromPolynomial(e){const t=new a_;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class l_{constructor(){this.x=de.Zero(),this.y=de.Zero(),this.z=de.Zero(),this.xx=de.Zero(),this.yy=de.Zero(),this.zz=de.Zero(),this.xy=de.Zero(),this.yz=de.Zero(),this.zx=de.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=a_.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){ge.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=ge.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),ge.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),ge.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(ge.Vector3[0]).addInPlace(ge.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(ge.Vector3[0]).subtractInPlace(ge.Vector3[1]),this.zz.copyFrom(e.l00),ge.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(ge.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return(new l_).updateFromHarmonics(e)}static FromArray(e){const t=new l_;return de.FromArrayToRef(e[0],0,t.x),de.FromArrayToRef(e[1],0,t.y),de.FromArrayToRef(e[2],0,t.z),de.FromArrayToRef(e[3],0,t.xx),de.FromArrayToRef(e[4],0,t.yy),de.FromArrayToRef(e[5],0,t.zz),de.FromArrayToRef(e[6],0,t.yz),de.FromArrayToRef(e[7],0,t.zx),de.FromArrayToRef(e[8],0,t.xy),t}}function h_(e,t,i,s=!0){const r=e.getScene(),n=r.getEngine(),o=new pl("resized"+e.name,{width:t,height:i},r,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);o.wrapU=e.wrapU,o.wrapV=e.wrapV,o.uOffset=e.uOffset,o.vOffset=e.vOffset,o.uScale=e.uScale,o.vScale=e.vScale,o.uAng=e.uAng,o.vAng=e.vAng,o.wAng=e.wAng,o.coordinatesIndex=e.coordinatesIndex,o.level=e.level,o.anisotropicFilteringLevel=e.anisotropicFilteringLevel,o._texture.isReady=!1,e.wrapU=Vo.CLAMP_ADDRESSMODE,e.wrapV=Vo.CLAMP_ADDRESSMODE;const a=new Nh("pass",1,null,s?Vo.BILINEAR_SAMPLINGMODE:Vo.NEAREST_SAMPLINGMODE,n,!1,0);return a.externalTextureSamplerBinding=!0,a.getEffect().executeWhenCompiled((()=>{a.onApply=function(t){t.setTexture("textureSampler",e)};const t=o.renderTarget;t&&(r.postProcessManager.directRender([a],t),n.unBindFramebuffer(t),o.disposeFramebufferObjects(),a.dispose(),o.getInternalTexture().isReady=!0)})),o}function c_(e,t,i,s,r,n,o,a){const l=t.getEngine();return t.isReady=!1,r=r??t.samplingMode,s=s??t.type,n=n??t.format,o=o??t.width,a=a??t.height,-1===s&&(s=0),new Promise((h=>{const c=new qa("postprocess",e,null,null,1,null,r,l,!1,void 0,s,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:o,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:s,format:n});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=s,t.format=5,t.isReady=!0,h(t)}))}))}let u_,d_;function __(e){u_||(u_=new Float32Array(1),d_=new Int32Array(u_.buffer)),u_[0]=e;const t=d_[0];let i=t>>16&32768,s=t>>12&2047;const r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=(255==r?0:1)&&8388607&t,i):r<113?(s|=2048,i|=(s>>114-r)+(s>>113-r&1),i):(i|=r-112<<10|s>>1,i+=1&s,i)}function p_(e){const t=(32768&e)>>15,i=(31744&e)>>10,s=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==i?s?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+s/Math.pow(2,10))}bi.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";const f_=async(e,t,i,s,r)=>{const n=e.getScene(),o=n.getEngine();let a;if(e.isCube){const e=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new qa("lodCube","lodCube",["lod","gamma"],null,1,null,Vo.NEAREST_NEAREST_MIPNEAREST,o,!1,e[s])}else a=new qa("lod","lod",["lod","gamma"],null,1,null,Vo.NEAREST_NEAREST_MIPNEAREST,o);await new Promise((e=>{a.getEffect().executeWhenCompiled((()=>{e(0)}))}));const l=new pl("temp",{width:t,height:i},n,!1);a.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",r),t.setBool("gamma",e.gammaSpace)};const h=e.getInternalTexture();try{if(l.renderTarget&&h){const s=h.samplingMode;0!==r?e.updateSamplingMode(Vo.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(Vo.NEAREST_NEAREST),n.postProcessManager.directRender([a],l.renderTarget,!0),e.updateSamplingMode(s);const c=await o.readPixels(0,0,t,i),u=new Uint8Array(c.buffer,0,c.byteLength);return o.unBindFramebuffer(l.renderTarget),u}throw Error("Render to texture failed.")}finally{l.dispose(),a.dispose()}};async function m_(e,t,i,s=0,r=0){return!e.isReady()&&e._texture&&await new Promise(((t,i)=>{null!==e._texture?e._texture.onLoadedObservable.addOnce((()=>{t(0)})):i(0)})),await f_(e,t,i,s,r)}const g_={CreateResizedCopy:h_,ApplyPostProcess:c_,ToHalfFloat:__,FromHalfFloat:p_,GetTextureDataAsync:m_};class v_{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const s=new qa("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);s.externalTextureSamplerBinding=!0;const r=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});s.getEffect().executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],r,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),r._swapAndDie(t),t.isReady=!0}))};n&&(r?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return c_("rgbdEncode",e,t,i,1,5)}}class x_{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class b_{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),a=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace;let h=0;return 1!=e.textureType&&2!=e.textureType||(h=1),new Promise((e=>{Promise.all([s,i,r,n,o,a]).then((([i,s,r,n,o,a])=>{const c={size:t,right:s,left:i,up:r,down:n,front:o,back:a,format:5,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(c))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new a_;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let a=0;a<6;a++){const l=this._FileFaces[a],h=e[l.name];let c=o;const u=5===e.format?4:3;for(let a=0;ag){const t=g/e;p*=t,f*=t,m*=t}}else p=xe.Clamp(p,0,g),f=xe.Clamp(f,0,g),m=xe.Clamp(m,0,g);const v=new Ce(p,f,m);t.addLight(o,v,_),i+=_,d+=s}c+=r}}const a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),l_.FromHarmonics(t)}}b_._FileFaces=[new x_("right",new de(1,0,0),new de(0,0,-1),new de(0,-1,0)),new x_("left",new de(-1,0,0),new de(0,0,1),new de(0,-1,0)),new x_("up",new de(0,1,0),new de(1,0,0),new de(0,0,1)),new x_("down",new de(0,-1,0),new de(1,0,0),new de(0,0,-1)),new x_("front",new de(0,0,1),new de(1,0,0),new de(0,-1,0)),new x_("back",new de(0,0,-1),new de(-1,0,0),new de(0,-1,0))],b_.MAX_HDRI_VALUE=4096,b_.PRESERVE_CLAMPED_COLORS=!1,No.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(No.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=b_.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});bi.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";const T_="image/png",y_=2,S_=[134,22,135,150,246,214,150,54];function C_(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;ey_)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${y_}".`);return 2===e.version?e:e={...e,version:2,imageType:T_}}async function A_(e,t={}){const i=e.getInternalTexture();if(!i)return Promise.reject("The cube texture is invalid.");const s=t.imageType??T_,r=i.getEngine();if(2!==e.textureType&&1!==e.textureType&&0!==e.textureType&&0!==e.textureType&&7!==e.textureType&&-1!==e.textureType)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let n=1;if(!r.getCaps().textureFloatRender&&(n=2,!r.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");e.sphericalPolynomial;const o=e.getInternalTexture()?._sphericalPolynomialPromise,a=i.width,l=new dr(r),h={};r.flushFramebuffer();const c=xe.ILog2(i.width);for(let i=0;i<=c;i++){const o=Math.pow(2,c-i);for(let a=0;a<6;a++){let c=await e.readPixels(a,i,void 0,!1);if(c&&c.byteLength===c.length){const e=new Float32Array(4*c.byteLength);for(let t=0;t{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);s.getEffect().executeWhenCompiled((()=>{s.externalTextureSamplerBinding=!0,s.onApply=s=>{s._bindTexture("textureSampler",i),s.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([s],h,!0,n,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(r),u())}))}else{if(t._uploadImageToTexture(c,e,n,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,n,0)}u()}}))}function O_(e,t,i=T_){if(!hs.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const s=xe.ILog2(e.width)+1,r=e.getEngine();let n=!1,o=!1,a=null,l=null,h=null;const c=r.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(3,e),c.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(n=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,o=!0,h={}),n)a=new qa("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=r.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,o){const t=3,i=e._lodGenerationScale,n=e._lodGenerationOffset;for(let o=0;oM_(t,r,n,a,p,c,s,o,h,l,e)));else{const t=new Image;t.src=p,f=new Promise(((i,u)=>{t.onload=()=>{M_(t,r,n,a,p,c,s,o,h,l,e).then((()=>i())).catch((e=>{u(e)}))},t.onerror=e=>{u(e)}}))}u.push(f)}if(t.length{l&&(r._releaseTexture(e),l._swapAndDie(e)),a&&a.dispose(),o&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function D_(e,t){const i=(t=E_(t)).irradiance;if(!i)return;const s=new l_;de.FromArrayToRef(i.x,0,s.x),de.FromArrayToRef(i.y,0,s.y),de.FromArrayToRef(i.z,0,s.z),de.FromArrayToRef(i.xx,0,s.xx),de.FromArrayToRef(i.yy,0,s.yy),de.FromArrayToRef(i.zz,0,s.zz),de.FromArrayToRef(i.yz,0,s.yz),de.FromArrayToRef(i.zx,0,s.zx),de.FromArrayToRef(i.xy,0,s.xy),e._sphericalPolynomial=s}function w_(e,t,i,s,r){const n=O_(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:n,isReady:!0,isAsync:!0}),e._source=Ai.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=s,e._lodGenerationOffset=r,e._sphericalPolynomial=i,O_(e,t).then((()=>(e.isReady=!0,e)))}const N_={GetEnvInfo:C_,CreateEnvTextureAsync:A_,CreateImageDataArrayBufferViews:R_,UploadEnvLevelsAsync:I_,UploadLevelsAsync:O_,UploadEnvSpherical:D_};function F_(e,t,i,s){let r=s,n=0,o="";for(;r=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function k_(e){let t=0,i="",s=!1;const r=[];for(;t=0&&e.charAt(t)!==i&&(!s||e.charAt(t)!==s);)t--;return t}class U_{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&we.Log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&we.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&d.push(t.substring(i+1))}"void"!==r&&d.push("return"),this._functionDescr.push({name:n,type:r,parameters:d,body:c,callIndex:0}),e=h+1;const _=t>0?this._sourceCode.substring(0,t):"",p=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&we.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o{const t=[];let i=0,s=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=r[0];return L_(e.charAt(a-1))||L_(e.charAt(a+n))?t[s]:o}))}return e}}U_._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class G_{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t){this.isCompiled=!1,this._valueCache={},this._engine=e,this.isAsync=t}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t})),a.push(...l.getAttributes(this,o))}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class z_ extends Ka{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class W_{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function H_(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new Qt(`Unsupported texture format or type: format ${e}, type ${t}.`,Yt.UnsupportedTextureError)}function X_(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${e}.`)}}function Y_(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}function Q_(e){switch(e){case ys.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case ys.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case ys.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case ys.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case ys.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}const j_=new X;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&j_.notifyObservers(e)}})}function K_(){return new Promise((e=>{"undefined"==typeof _native?j_.addOnce((t=>e(t))):e(_native)}))}async function $_(e,t){(await K_())[e]=t}class q_ extends Oi{}class Z_{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=J_._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}class J_ extends gn{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new Z_(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==J_.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${J_.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback((()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()})),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},hs.Log("Babylon Native (v"+gn.Version+") launched"),hs.LoadScript=function(e,t,i,s){hs.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,s){return Array.isArray(s)?i.push.apply(i,e.call(s,t-1)):i.push(s),i}),[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new Mi,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new i_}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=s,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,s=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const s=this._normalizeIndexData(e),r=new q_;return r.references=1,r.is32Bits=4===s.BYTES_PER_ELEMENT,s.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,r.is32Bits,t??!1)),r}createVertexBuffer(e,t,i){const s=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new q_;return r.references=1,s.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,t??!1)),r}_recordVertexArrayObject(e,t,i,s,r){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let i=0;i=0){const s=n[i];let a=null;if(r&&(a=r[s]),a||(a=t[s]),a){const t=a.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.byteOffset,a.byteStride,a.getSize(),Q_(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e;return this._engine.getAttributes(i.program,t)}drawElementsType(e,t,i,s){this._drawCalls.addCount(1,!1),s&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,s){this._drawCalls.addCount(1,!1),s&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){const e=!(!this._caps.parallelShaderCompile||!this._engine.createProgramAsync);return new G_(this,e)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,s,r,n,o,a){s?this.createRawShaderProgram():this.createShaderProgram(e,t,i,a)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(i.isAsync)if(i.onCompiled){const e=i.onCompiled;i.onCompiled=()=>{e(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new U_(t);n.processCode(),t=n.code;const o=new U_(i);o.processCode(),i=o.code,t=ki._ConcatenateShader(t,s),i=ki._ConcatenateShader(i,s);const a=()=>{r.isCompiled=!0,r.onCompiled?.(),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)r.program=this._engine.createProgramAsync(t,i,a,(e=>{r.compilationError=e}));else try{r.program=this._engine.createProgram(t,i),a()}catch(e){const t=e?.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}return r.program}inlineShaderCode(e){const t=new U_(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,s,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,s=!1,r){if(void 0===s&&(s=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),s=e._hardwareTexture.underlyingResource;this._engine.copyTexture(s,i),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new Pi(this,Ai.Raw);if(u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=X_(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,s,r,n,o,a,l=null,h=0){const c=new Pi(this,Ai.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=s,c.width=t,c.height=i,c.depth=s,c.format=r,c.type=h,c.generateMipMaps=n,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,s,H_(r,h),n,o);const u=X_(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const s=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(s,t,e.width,e.height,H_(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p=!1){const f="data:"===(e=e||"").substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new Pi(this,Ai.Url),v=e;!this._transformTextureUrl||m||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():"");let T=null;for(const e of gn._TextureLoaders)if(e.canLoad(b)){T=e;break}s&&s.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=r,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(g._buffer=a);let y=null;n&&!l&&(y=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);const S=(i,l)=>{s&&s.removePendingData(g),e===v?(y&&g.onLoadedObservable.remove(y),se.UseFallbackTexture&&this.createTexture(se.FallbackTexture,t,g.invertY,s,r,null,o,a,g),o&&o((i||"Unknown error")+(se.UseFallbackTexture?" - Fallback texture was used":""),l)):(we.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,s,r,n,o,a,g,h,c,u,d))};if(T)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const n=e=>{if(!g._hardwareTexture)return void(s&&s.removePendingData(g));const n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,(()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;const e=X_(r);this._setTextureSampling(n,e),s&&s.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(f&&a)if(a instanceof ArrayBuffer)n(new Uint8Array(a));else if(ArrayBuffer.isView(a))n(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");n(new Uint8Array(hs.DecodeBase64(a)))}else m?n(new Uint8Array(hs.DecodeBase64(e))):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{S("Unable to load "+(e&&e.responseURL,t))}))}return g}wrapNativeTexture(e,t=!1,i=3){const s=new W_(e,this._engine),r=new Pi(this,Ai.Unknown,!0);return r._hardwareTexture=s,r.baseWidth=this._engine.getTextureWidth(e),r.baseHeight=this._engine.getTextureHeight(e),r.width=r.baseWidth,r.height=r.baseHeight,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const s=t.generateStencil||!1,r=t.samples||1,n=i,o=new Pi(this,Ai.DepthStencil),a=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,a,l,s,!0,r);return n._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise(((t,i)=>{const s=this.createCanvasImage();s.onload=()=>{try{const e=this._engine.createImageBitmap(s);t(e)}catch(e){i(`Error loading image ${s.src} with exception: ${e}`)}},s.onerror=e=>{i(`Error loading image ${s.src} with exception: ${e}`)},s.src=e}))}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,_=!1){const p=u||new Pi(this,Ai.Cube);p.isCube=!0,p.url=e,p.generateMipMaps=!s,p._lodGenerationScale=h,p._lodGenerationOffset=c,p._useSRGBBuffer=this._getUseSRGBBuffer(_,!!s),this._doNotHandleContextLost||(p._extension=a,p._files=i);const f=e.lastIndexOf(".");if(".env"===(a||(f>-1?e.substring(f).toLowerCase():""))){const t=e=>{const t=C_(e);p.width=t.width,p.height=t.width,D_(p,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");p._lodGenerationScale=i.lodGenerationScale;const s=R_(e,t);p.format=5,p.type=0,p.generateMipMaps=!0,p.getEngine().updateTextureSamplingMode(Vo.TRILINEAR_SAMPLINGMODE,p),p._isRGBD=!0,p.invertY=!0,this._engine.loadCubeTextureWithMips(p._hardwareTexture.underlyingResource,s,!1,p._useSRGBBuffer,(()=>{p.isReady=!0,r&&r()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>{t(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>this._loadFileAsync(e,void 0,!0).then((e=>new Uint8Array(e,0,e.byteLength)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(p._hardwareTexture.underlyingResource,e,!s,!0,p._useSRGBBuffer,t,i)})))).then((()=>{p.isReady=!0,r&&r()}),(e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(p),p}_createHardwareTexture(){return new W_(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new z_(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=Ai.Unknown){let r,n=!1,o=0,a=3,l=5,h=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=void 0===t.type?0:t.type,a=void 0===t.samplingMode?3:t.samplingMode,l=void 0===t.format?5:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,r=t.label):n=!!t,h=this._getUseSRGBBuffer(h,!n),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,we.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new Pi(this,s),d=e.width??e,_=e.height??e,p=e.layers||0;if(0!==p)throw new Error("Texture layers are not supported in Babylon Native");const f=u._hardwareTexture.underlyingResource,m=H_(l,o);return this._engine.initializeTexture(f,d,_,n,m,!0,h,c),this._setTextureSampling(f,X_(a)),u._useSRGBBuffer=h,u.baseWidth=d,u.baseHeight=_,u.width=d,u.height=_,u.depth=p,u.isReady=!0,u.samples=c,u.generateMipMaps=n,u.samplingMode=a,u.type=o,u.format=l,u.label=r,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s,r=!0,n=!1,o=!1,a=1;void 0!==t&&"object"==typeof t&&(r=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,o=!!t.noColorAttachment,s=t.colorAttachment,a=t.samples??1);const l=s||(o?null:this._createInternalTexture(e,t,!0,Ai.RenderTarget)),h=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,c,n,r,a);return i._framebuffer=u,i._generateDepthBuffer=r,i._generateStencilBuffer=n,i._samples=a,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return we.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=X_(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const s=e,r=this._normalizeIndexData(t);s.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,s){const r=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,s??n.byteLength);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;return n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,Y_(t.wrapU),Y_(t.wrapV),Y_(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(r,n._hardwareTexture.underlyingResource),0))}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,s,r,n,o,a,l,h){if(void 0!==s&&-1!==s)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture(e._hardwareTexture?.underlyingResource,r??0,l??0,h??0,t,i,n?.buffer??null,n?.byteOffset??0,n?.byteLength??0).then((e=>(n||(n=new Uint8Array(e)),n)))}}J_.PROTOCOL_VERSION=8,J_._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new ep:new i_};class ep extends i_{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var tp,ip,sp,rp,np,op,ap,lp,hp,cp,up,dp,_p,pp,fp,mp,gp,vp,xp,bp,Tp,yp,Sp,Cp,Ep,Ap,Pp,Rp,Ip,Mp,Op,Dp,wp,Np,Fp,Bp,Lp,kp,Vp,Up;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(tp||(tp={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(ip||(ip={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(sp||(sp={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(rp||(rp={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(np||(np={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(op||(op={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(ap||(ap={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(lp||(lp={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(hp||(hp={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(cp||(cp={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(up||(up={})),function(e){e.Nearest="nearest",e.Linear="linear"}(dp||(dp={})),function(e){e.Nearest="nearest",e.Linear="linear"}(_p||(_p={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(pp||(pp={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(fp||(fp={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(mp||(mp={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(gp||(gp={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(vp||(vp={})),function(e){e.WriteOnly="write-only",e.ReadOnly="read-only",e.ReadWrite="read-write"}(xp||(xp={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(bp||(bp={})),function(e){e.Validation="validation",e.Internal="internal"}(Tp||(Tp={})),function(e){e.Auto="auto"}(yp||(yp={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(Sp||(Sp={})),function(e){e.CCW="ccw",e.CW="cw"}(Cp||(Cp={})),function(e){e.None="none",e.Front="front",e.Back="back"}(Ep||(Ep={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(Ap||(Ap={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(Pp||(Pp={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(Rp||(Rp={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Ip||(Ip={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Mp||(Mp={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(Op||(Op={})),function(e){e.Vertex="vertex",e.Instance="instance"}(Dp||(Dp={})),function(e){e.Beginning="beginning",e.End="end"}(wp||(wp={})),function(e){e.Beginning="beginning",e.End="end"}(Np||(Np={})),function(e){e.Load="load",e.Clear="clear"}(Fp||(Fp={})),function(e){e.Store="store",e.Discard="discard"}(Bp||(Bp={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(Lp||(Lp={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(kp||(kp={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(Vp||(Vp={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(Up||(Up={}));class Gp{constructor(){this.shaderLanguage=ui.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let t=0;t=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new bs(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Gp.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,s,r)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,s,r)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,s,r)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const Wp={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Hp{static get KnownUBOs(){return Hp._SimplifiedKnownBindings?Hp._SimplifiedKnownUBOs:Hp._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Hp.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;-1!==s.groupIndex&&(void 0===t[s.groupIndex]?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(Wp[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(Wp[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Hp._SimplifiedKnownBindings=!0,Hp._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},Hp._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class Xp extends Gp{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=ui.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const t=e.substring(r+1,n);s=+t,isNaN(s)&&(s=+i[t.trim()]),e=e.substr(0,r)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\nuniform ${Gp.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,s=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const r=s[1]??"",n=s[2],o=s[3];let a;t?(a=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[a]="",void 0===a&&we.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(a=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=a,this._missingVaryings[a]=`layout(location = ${a}) ${r} in ${n} ${o};`),e=e.replace(s[0],void 0===a?"":`layout(location = ${a}) ${r} ${t?"in":"out"} ${n} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const s=i[1],r=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const t=o<0?-1===o?"int":"ivec"+-o:1===o?"uint":"uvec"+o,a=`_int_${r}_`;e=e.replace(i[0],`layout(location = ${n}) in ${t} ${a}; ${s} ${r} = ${s}(${a});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${s} ${r};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],n=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[n,r,s]=this._getArraySize(n,r,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:vp.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const a=Gp._SamplerTypeByWebGLSamplerType[r]??"sampler",l=!!Gp._IsComparisonSamplerByWebGPUSamplerType[a],h=l?gp.Comparison:gp.Filtering,c=n+Gp.AutoSamplerSuffix;let u=this._webgpuProcessingContext.availableSamplers[c];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const d="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";d&&(r=r.substr(1));const _=l?vp.Depth:"u"===d?vp.Uint:"i"===d?vp.Sint:vp.Float;o.sampleType=_;const p=s>0,f=u.binding.groupIndex,m=u.binding.bindingIndex,g=Gp._SamplerFunctionByWebGLSamplerType[r],v=Gp._TextureTypeByWebGLSamplerType[r],x=Gp._GpuTextureViewDimensionByWebGPUTextureType[v];if(p){const t=[];t.push(`layout(set = ${f}, binding = ${m}) uniform ${d}${a} ${c};`),e="\n";for(let i=0;i0?"\n":""}#define ${n}${i} ${d}${g}(${n}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else s=1,e=`layout(set = ${f}, binding = ${m}) uniform ${a} ${c};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${d}${v} ${n}Texture;\n #define ${n} ${d}${g}(${n}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[c]=u,this._addSamplerBindingDescription(c,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",s=t?"vec4 glFragCoord_;\n":"",r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",s),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",r.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;null!==s;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}bi.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n";bi.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";bi.IncludesShadersStoreWGSL.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";bi.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";bi.IncludesShadersStoreWGSL.clipPlaneVertex="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";bi.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";bi.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n";bi.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i<$NUM_MORPH_INFLUENCERS$; i=i+1) {if (i>=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}\n#endif\n#endif\n";bi.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n";const Yp={texture_1d:lp.E1d,texture_2d:lp.E2d,texture_2d_array:lp.E2dArray,texture_3d:lp.E3d,texture_cube:lp.Cube,texture_cube_array:lp.CubeArray,texture_multisampled_2d:lp.E2d,texture_depth_2d:lp.E2d,texture_depth_2d_array:lp.E2dArray,texture_depth_cube:lp.Cube,texture_depth_cube_array:lp.CubeArray,texture_depth_multisampled_2d:lp.E2d,texture_storage_1d:lp.E1d,texture_storage_2d:lp.E2d,texture_storage_2d_array:lp.E2dArray,texture_storage_3d:lp.E3d,texture_external:null};class Qp extends Gp{constructor(){super(...arguments),this.shaderLanguage=ui.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let e=r;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const n=t.substring(e+1,r);for(s=+n,isNaN(s)&&(s=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${Gp.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${Gp.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+k_(e)}varyingCheck(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const s=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==s){const r=s[1]??"perspective",n=s[2]??"center",o=s[4],a=s[3],l="flat"===r?`@interpolate(${r})`:`@interpolate(${r}, ${n})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[a],void 0===h&&we.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=h,this._varyingsWGSL.push(` @location(${h}) ${l} ${a} : ${o},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const s=i[2],r=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const e=o<0?-1===o?"i32":"vec"+-o+"":1===o?"u32":"vec"+o+"",t=`_int_${r}_`;this._attributesInputWGSL.push(`@location(${n}) ${t} : ${e},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = ${s}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${r} : ${s},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = vertexInputs_.${r};`);e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(null!==s){const t=s[2],r=s[1];this._addUniformToLeftOverUBO(r,t,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(null!==s){const r=s[1],n=s[2],o=!!s[3],a=s[4],l=a.indexOf("storage")>0,h=s[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(r,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[r];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:vp.Float},u=u||1;for(let e=0;e0,p=Yp[a],f=_?vp.Depth:"u32"===h?vp.Uint:"i32"===h?vp.Sint:vp.Float;if(d.sampleType=f,void 0===p)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i2?t[2]:""}return e.replace(/\$(\w+)\$/g,((e,t)=>i[t]??t))}finalizeShaders(e,t){const i=t.indexOf("fragmentInputs.position")>=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const s=this._buildLeftOverUBO();t=s+t,e=(e=s+e).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(r+=this._attributesInputWGSL.join("\n")),r+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(r+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",r+=this._attributesWGSL.join("\n"),r+="\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=r+n+e;let o=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n"),e=this._injectStartingAndEndingCode(e,"fn main",o," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let a="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(a+=this._varyingsWGSL.join("\n")),a+="\n};\nvar fragmentInputs : FragmentInputs;\n";let l="struct FragmentOutputs {\n @location(0) color : vec4,\n",h=!1,c=0;for(;!(h||(c=t.indexOf("fragmentOutputs.fragDepth",c),c<0));){const e=c;for(h=!0;c>1&&"\n"!==t.charAt(c);){if("/"===t.charAt(c)&&"/"===t.charAt(c-1)){h=!1;break}c--}c=e+25}h&&(l+=" @builtin(frag_depth) fragDepth: f32,\n"),l+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=a+l+t;const u=" fragmentInputs = input;\n "+i;return t=this._injectStartingAndEndingCode(t,"fn main",u," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const r=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=Gp.UniformSizes[r];if(t.length>0)if(n<=2){const n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} {\n @size(16)\n el: ${r},\n }`,this._stridedUniformArrays.push(t.name),s+=` @align(16) ${t.name} : array<${n}, ${t.length}>,\n`}else s+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else s+=` ${t.name} : ${t.type},\n`}return s+="};\n",s=`${i}\n${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[2],o=r.indexOf(Gp.AutoSamplerSuffix)===r.length-Gp.AutoSamplerSuffix.length?r.substring(0,r.indexOf(Gp.AutoSamplerSuffix)):null,a="sampler_comparison"===n?gp.Comparison:gp.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[r];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[r]=l),this._addSamplerBindingDescription(r,l,t);const h=e.substring(0,s.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(s.index);e=h+c+u,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[3];let o=s[4];const a=s[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===r?Hp.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[o]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===n?mp.Storage:"storage"===r?mp.ReadOnlyStorage:mp.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,s.index),d=`@group(${h}) @binding(${c}) `,_=e.substring(s.index);e=u+d+_,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class jp{static ComputeNumMipmapLevels(e,t){return xe.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case cp.R8Unorm:case cp.R8Snorm:case cp.R8Uint:case cp.R8Sint:case cp.RG8Unorm:case cp.RG8Snorm:case cp.RG8Uint:case cp.RG8Sint:case cp.RGBA8Unorm:case cp.RGBA8UnormSRGB:case cp.RGBA8Snorm:case cp.RGBA8Uint:case cp.RGBA8Sint:case cp.BGRA8Unorm:case cp.BGRA8UnormSRGB:case cp.RGB10A2UINT:case cp.RGB10A2Unorm:case cp.RGB9E5UFloat:case cp.RG11B10UFloat:case cp.BC7RGBAUnorm:case cp.BC7RGBAUnormSRGB:case cp.BC6HRGBUFloat:case cp.BC6HRGBFloat:case cp.BC5RGUnorm:case cp.BC5RGSnorm:case cp.BC3RGBAUnorm:case cp.BC3RGBAUnormSRGB:case cp.BC2RGBAUnorm:case cp.BC2RGBAUnormSRGB:case cp.BC4RUnorm:case cp.BC4RSnorm:case cp.BC1RGBAUnorm:case cp.BC1RGBAUnormSRGB:case cp.ETC2RGB8Unorm:case cp.ETC2RGB8UnormSRGB:case cp.ETC2RGB8A1Unorm:case cp.ETC2RGB8A1UnormSRGB:case cp.ETC2RGBA8Unorm:case cp.ETC2RGBA8UnormSRGB:case cp.EACR11Unorm:case cp.EACR11Snorm:case cp.EACRG11Unorm:case cp.EACRG11Snorm:case cp.ASTC4x4Unorm:case cp.ASTC4x4UnormSRGB:case cp.ASTC5x4Unorm:case cp.ASTC5x4UnormSRGB:case cp.ASTC5x5Unorm:case cp.ASTC5x5UnormSRGB:case cp.ASTC6x5Unorm:case cp.ASTC6x5UnormSRGB:case cp.ASTC6x6Unorm:case cp.ASTC6x6UnormSRGB:case cp.ASTC8x5Unorm:case cp.ASTC8x5UnormSRGB:case cp.ASTC8x6Unorm:case cp.ASTC8x6UnormSRGB:case cp.ASTC8x8Unorm:case cp.ASTC8x8UnormSRGB:case cp.ASTC10x5Unorm:case cp.ASTC10x5UnormSRGB:case cp.ASTC10x6Unorm:case cp.ASTC10x6UnormSRGB:case cp.ASTC10x8Unorm:case cp.ASTC10x8UnormSRGB:case cp.ASTC10x10Unorm:case cp.ASTC10x10UnormSRGB:case cp.ASTC12x10Unorm:case cp.ASTC12x10UnormSRGB:case cp.ASTC12x12Unorm:case cp.ASTC12x12UnormSRGB:case cp.Stencil8:return 0;case cp.R16Uint:case cp.R16Sint:case cp.RG16Uint:case cp.RG16Sint:case cp.RGBA16Uint:case cp.RGBA16Sint:case cp.Depth16Unorm:return 5;case cp.R16Float:case cp.RG16Float:case cp.RGBA16Float:return 2;case cp.R32Uint:case cp.R32Sint:case cp.RG32Uint:case cp.RG32Sint:case cp.RGBA32Uint:case cp.RGBA32Sint:return 7;case cp.R32Float:case cp.RG32Float:case cp.RGBA32Float:case cp.Depth32Float:case cp.Depth32FloatStencil8:case cp.Depth24Plus:case cp.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case cp.R8Unorm:case cp.R8Snorm:case cp.R8Uint:case cp.R8Sint:return{width:1,height:1,length:1};case cp.R16Uint:case cp.R16Sint:case cp.R16Float:case cp.RG8Unorm:case cp.RG8Snorm:case cp.RG8Uint:case cp.RG8Sint:return{width:1,height:1,length:2};case cp.R32Uint:case cp.R32Sint:case cp.R32Float:case cp.RG16Uint:case cp.RG16Sint:case cp.RG16Float:case cp.RGBA8Unorm:case cp.RGBA8UnormSRGB:case cp.RGBA8Snorm:case cp.RGBA8Uint:case cp.RGBA8Sint:case cp.BGRA8Unorm:case cp.BGRA8UnormSRGB:case cp.RGB9E5UFloat:case cp.RGB10A2UINT:case cp.RGB10A2Unorm:case cp.RG11B10UFloat:return{width:1,height:1,length:4};case cp.RG32Uint:case cp.RG32Sint:case cp.RG32Float:case cp.RGBA16Uint:case cp.RGBA16Sint:case cp.RGBA16Float:return{width:1,height:1,length:8};case cp.RGBA32Uint:case cp.RGBA32Sint:case cp.RGBA32Float:return{width:1,height:1,length:16};case cp.Stencil8:throw"No fixed size for Stencil8 format!";case cp.Depth16Unorm:return{width:1,height:1,length:2};case cp.Depth24Plus:throw"No fixed size for Depth24Plus format!";case cp.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case cp.Depth32Float:return{width:1,height:1,length:4};case cp.Depth32FloatStencil8:return{width:1,height:1,length:5};case cp.BC7RGBAUnorm:case cp.BC7RGBAUnormSRGB:case cp.BC6HRGBUFloat:case cp.BC6HRGBFloat:case cp.BC5RGUnorm:case cp.BC5RGSnorm:case cp.BC3RGBAUnorm:case cp.BC3RGBAUnormSRGB:case cp.BC2RGBAUnorm:case cp.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case cp.BC4RUnorm:case cp.BC4RSnorm:case cp.BC1RGBAUnorm:case cp.BC1RGBAUnormSRGB:case cp.ETC2RGB8Unorm:case cp.ETC2RGB8UnormSRGB:case cp.ETC2RGB8A1Unorm:case cp.ETC2RGB8A1UnormSRGB:case cp.EACR11Unorm:case cp.EACR11Snorm:return{width:4,height:4,length:8};case cp.ETC2RGBA8Unorm:case cp.ETC2RGBA8UnormSRGB:case cp.EACRG11Unorm:case cp.EACRG11Snorm:case cp.ASTC4x4Unorm:case cp.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case cp.ASTC5x4Unorm:case cp.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case cp.ASTC5x5Unorm:case cp.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case cp.ASTC6x5Unorm:case cp.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case cp.ASTC6x6Unorm:case cp.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case cp.ASTC8x5Unorm:case cp.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case cp.ASTC8x6Unorm:case cp.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case cp.ASTC8x8Unorm:case cp.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case cp.ASTC10x5Unorm:case cp.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case cp.ASTC10x6Unorm:case cp.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case cp.ASTC10x8Unorm:case cp.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case cp.ASTC10x10Unorm:case cp.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case cp.ASTC12x10Unorm:case cp.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case cp.ASTC12x12Unorm:case cp.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case cp.BC7RGBAUnormSRGB:case cp.BC7RGBAUnorm:case cp.BC6HRGBFloat:case cp.BC6HRGBUFloat:case cp.BC5RGSnorm:case cp.BC5RGUnorm:case cp.BC4RSnorm:case cp.BC4RUnorm:case cp.BC3RGBAUnormSRGB:case cp.BC3RGBAUnorm:case cp.BC2RGBAUnormSRGB:case cp.BC2RGBAUnorm:case cp.BC1RGBAUnormSRGB:case cp.BC1RGBAUnorm:case cp.ETC2RGB8Unorm:case cp.ETC2RGB8UnormSRGB:case cp.ETC2RGB8A1Unorm:case cp.ETC2RGB8A1UnormSRGB:case cp.ETC2RGBA8Unorm:case cp.ETC2RGBA8UnormSRGB:case cp.EACR11Unorm:case cp.EACR11Snorm:case cp.EACRG11Unorm:case cp.EACRG11Snorm:case cp.ASTC4x4Unorm:case cp.ASTC4x4UnormSRGB:case cp.ASTC5x4Unorm:case cp.ASTC5x4UnormSRGB:case cp.ASTC5x5Unorm:case cp.ASTC5x5UnormSRGB:case cp.ASTC6x5Unorm:case cp.ASTC6x5UnormSRGB:case cp.ASTC6x6Unorm:case cp.ASTC6x6UnormSRGB:case cp.ASTC8x5Unorm:case cp.ASTC8x5UnormSRGB:case cp.ASTC8x6Unorm:case cp.ASTC8x6UnormSRGB:case cp.ASTC8x8Unorm:case cp.ASTC8x8UnormSRGB:case cp.ASTC10x5Unorm:case cp.ASTC10x5UnormSRGB:case cp.ASTC10x6Unorm:case cp.ASTC10x6UnormSRGB:case cp.ASTC10x8Unorm:case cp.ASTC10x8UnormSRGB:case cp.ASTC10x10Unorm:case cp.ASTC10x10UnormSRGB:case cp.ASTC12x10Unorm:case cp.ASTC12x10UnormSRGB:case cp.ASTC12x12Unorm:case cp.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return cp.Depth16Unorm;case 16:return cp.Depth24Plus;case 13:return cp.Depth24PlusStencil8;case 14:return cp.Depth32Float;case 18:return cp.Depth32FloatStencil8;case 19:return cp.Stencil8;case 36492:return i?cp.BC7RGBAUnormSRGB:cp.BC7RGBAUnorm;case 36495:return cp.BC6HRGBUFloat;case 36494:return cp.BC6HRGBFloat;case 33779:return i?cp.BC3RGBAUnormSRGB:cp.BC3RGBAUnorm;case 33778:return i?cp.BC2RGBAUnormSRGB:cp.BC2RGBAUnorm;case 33777:case 33776:return i?cp.BC1RGBAUnormSRGB:cp.BC1RGBAUnorm;case 37808:return i?cp.ASTC4x4UnormSRGB:cp.ASTC4x4Unorm;case 36196:case 37492:return i?cp.ETC2RGB8UnormSRGB:cp.ETC2RGB8Unorm;case 37496:return i?cp.ETC2RGBA8UnormSRGB:cp.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return cp.R8Snorm;case 7:return cp.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return cp.R8Sint;case 9:return cp.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return cp.RGBA8Sint;default:return cp.RGBA8Snorm}case 0:switch(t){case 6:return cp.R8Unorm;case 7:return cp.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?cp.RGBA8UnormSRGB:cp.RGBA8Unorm;case 12:return i?cp.BGRA8UnormSRGB:cp.BGRA8Unorm;case 8:return cp.R8Uint;case 9:return cp.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return cp.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return cp.RGBA8Unorm}case 4:switch(t){case 8:return cp.R16Sint;case 9:return cp.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cp.RGBA16Sint}case 5:switch(t){case 8:return cp.R16Uint;case 9:return cp.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cp.RGBA16Uint}case 6:switch(t){case 8:return cp.R32Sint;case 9:return cp.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cp.RGBA32Sint}case 7:switch(t){case 8:return cp.R32Uint;case 9:return cp.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return cp.RGBA32Uint}case 1:switch(t){case 6:return cp.R32Float;case 7:return cp.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return cp.RGBA32Float}case 2:switch(t){case 6:return cp.R16Float;case 7:return cp.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return cp.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return cp.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return cp.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return cp.RGB10A2Unorm;case 11:return cp.RGB10A2UINT}}return i?cp.RGBA8UnormSRGB:cp.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case cp.R8Unorm:case cp.R8Snorm:case cp.R8Uint:case cp.R8Sint:case cp.BC4RUnorm:case cp.BC4RSnorm:case cp.R16Uint:case cp.R16Sint:case cp.Depth16Unorm:case cp.R16Float:case cp.R32Uint:case cp.R32Sint:case cp.R32Float:case cp.Depth32Float:case cp.Stencil8:case cp.Depth24Plus:case cp.EACR11Unorm:case cp.EACR11Snorm:return 1;case cp.RG8Unorm:case cp.RG8Snorm:case cp.RG8Uint:case cp.RG8Sint:case cp.Depth32FloatStencil8:case cp.BC5RGUnorm:case cp.BC5RGSnorm:case cp.RG16Uint:case cp.RG16Sint:case cp.RG16Float:case cp.RG32Uint:case cp.RG32Sint:case cp.RG32Float:case cp.Depth24PlusStencil8:case cp.EACRG11Unorm:case cp.EACRG11Snorm:return 2;case cp.RGB9E5UFloat:case cp.RG11B10UFloat:case cp.BC6HRGBUFloat:case cp.BC6HRGBFloat:case cp.ETC2RGB8Unorm:case cp.ETC2RGB8UnormSRGB:return 3;case cp.RGBA8Unorm:case cp.RGBA8UnormSRGB:case cp.RGBA8Snorm:case cp.RGBA8Uint:case cp.RGBA8Sint:case cp.BGRA8Unorm:case cp.BGRA8UnormSRGB:case cp.RGB10A2UINT:case cp.RGB10A2Unorm:case cp.BC7RGBAUnorm:case cp.BC7RGBAUnormSRGB:case cp.BC3RGBAUnorm:case cp.BC3RGBAUnormSRGB:case cp.BC2RGBAUnorm:case cp.BC2RGBAUnormSRGB:case cp.BC1RGBAUnorm:case cp.BC1RGBAUnormSRGB:case cp.RGBA16Uint:case cp.RGBA16Sint:case cp.RGBA16Float:case cp.RGBA32Uint:case cp.RGBA32Sint:case cp.RGBA32Float:case cp.ETC2RGB8A1Unorm:case cp.ETC2RGB8A1UnormSRGB:case cp.ETC2RGBA8Unorm:case cp.ETC2RGBA8UnormSRGB:case cp.ASTC4x4Unorm:case cp.ASTC4x4UnormSRGB:case cp.ASTC5x4Unorm:case cp.ASTC5x4UnormSRGB:case cp.ASTC5x5Unorm:case cp.ASTC5x5UnormSRGB:case cp.ASTC6x5Unorm:case cp.ASTC6x5UnormSRGB:case cp.ASTC6x6Unorm:case cp.ASTC6x6UnormSRGB:case cp.ASTC8x5Unorm:case cp.ASTC8x5UnormSRGB:case cp.ASTC8x6Unorm:case cp.ASTC8x6UnormSRGB:case cp.ASTC8x8Unorm:case cp.ASTC8x8UnormSRGB:case cp.ASTC10x5Unorm:case cp.ASTC10x5UnormSRGB:case cp.ASTC10x6Unorm:case cp.ASTC10x6UnormSRGB:case cp.ASTC10x8Unorm:case cp.ASTC10x8UnormSRGB:case cp.ASTC10x10Unorm:case cp.ASTC10x10UnormSRGB:case cp.ASTC12x10Unorm:case cp.ASTC12x10UnormSRGB:case cp.ASTC12x12Unorm:case cp.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case cp.Stencil8:case cp.Depth32FloatStencil8:case cp.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case cp.Depth32FloatStencil8:case cp.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case cp.Depth16Unorm:return cp.Depth16Unorm;case cp.Depth24Plus:case cp.Depth24PlusStencil8:return cp.Depth24Plus;case cp.Depth32Float:case cp.Depth32FloatStencil8:return cp.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class Kp{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){return this._webgpuMSAATexture?.[e]??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=cp.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,r,n,o,a){let l=lp.E2d,h=1;s?(l=i?lp.CubeArray:lp.Cube,h=6*(a||1)):r?(l=lp.E3d,h=1):i&&(l=lp.E2dArray,h=a);const c=jp.GetDepthFormatOnly(this.format),u=jp.HasDepthAndStencilAspects(this.format)?hp.DepthOnly:hp.All;this.createView({label:`TextureView${r?"3D":s?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:c,dimension:l,mipLevelCount:t?xe.ILog2(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:u})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATexture(),this._copyInvertYTempTexture?.destroy(),this.reset()}}const $p="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",qp=$p;var Zp,Jp;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Zp||(Zp={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(Jp||(Jp={}));const ef=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:$p,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:qp,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],tf={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class sf{constructor(e,t,i,s,r,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=r,-1!==n.indexOf(ip.RG11B10UFloatRenderable)){const e=Object.keys(tf);tf[cp.RG11B10UFloat]=tf[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:dp.Linear}),this._videoSampler=t.createSampler({minFilter:dp.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,rp.Uniform|rp.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(cp.RGBA8Unorm),this._getVideoPipeline(cp.RGBA8Unorm)}_getPipeline(e,t=Zp.MipMap,i){const s=t===Zp.MipMap?1:t===Zp.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Zp.Clear?8:t===Zp.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n="#version 450\n";t!==Zp.InvertYPremultiplyAlpha&&t!==Zp.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[s];if(!o){let e=this._glslang.compileGLSL(n+ef[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+ef[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const r=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[s]=[r,a]}const a=this._device.createRenderPipeline({layout:yp.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Sp.TriangleStrip,stripIndexFormat:Mp.Uint16}});r=this._pipelines[e][s]=[a,a.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=Jp.DontInvertY){const i=t===Jp.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),s=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,s]}const r=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:yp.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Sp.TriangleStrip,stripIndexFormat:Mp.Uint16}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,r){const n=void 0===r,[o,a]=this._getVideoPipeline(i,s?Jp.InvertY:Jp.DontInvertY);n&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.(`copy video to texture - invertY=${s}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:lp.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:hp.All}),loadOp:Fp.Load,storeOp:Bp.Store}]},c=r.beginRenderPass(h),u={layout:a,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(u);c.setPipeline(o),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),r.popDebugGroup?.(),n&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,_,p){const f=0!==u,m=void 0===_,[g,v]=this._getPipeline(s,f?Zp.InvertYPremultiplyAlphaWithOfst:Zp.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});let x;if(o=Math.max(o,0),m&&(_=this._device.createCommandEncoder({})),_.pushDebugGroup?.(`internal process texture - invertY=${r} premultiplyAlpha=${n}`),jp.IsHardwareTexture(e)?(x=e.underlyingResource,r&&!n&&1===l&&0===o||(e=void 0)):(x=e,e=void 0),!x)return;f&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const b=e,T=b?._copyInvertYTempTexture??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,_,ap.CopySrc|ap.RenderAttachment|ap.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),y=b?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${r?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:T.createView({format:s,dimension:lp.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Fp.Load,storeOp:Bp.Store}]},S=_.beginRenderPass(y);let C=f?b?._copyInvertYBindGroupWithOfst:b?._copyInvertYBindGroup;if(!C){const e={layout:v,entries:[{binding:0,resource:x.createView({format:s,dimension:lp.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};f&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),C=this._device.createBindGroup(e)}S.setPipeline(g),S.setBindGroup(0,C),S.draw(4,1,0,0),S.end(),_.copyTextureToTexture({texture:T},{texture:x,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),b?(b._copyInvertYTempTexture=T,b._copyInvertYRenderPassDescr=y,f?b._copyInvertYBindGroupWithOfst=C:b._copyInvertYBindGroup=C):this._deferredReleaseTextures.push([T,null]),_.popDebugGroup?.(),m&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,s){const r=void 0===s,[n,o]=this._getPipeline(t,Zp.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.("internal copy texture with invertY");const a=s.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});a.setPipeline(n),a.setBindGroup(0,l),a.draw(4,1,0,0),a.end(),s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=cp.RGBA8Unorm,a=1,l,h=-1,c=0,u){a=jp.GetSample(a);const d=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:d},p=tf[o]?ap.RenderAttachment:0,f=jp.IsCompressedFormat(o),m=t?jp.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:ap.CopySrc|ap.CopyDst|ap.TextureBinding;c|=t&&!f?ap.CopySrc|p:0,f||n||(c|=p|ap.CopyDst);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${u?u+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:_,dimension:n?op.E3d:op.E2d,format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return jp.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(v,o,m,0,n,l)),v}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=cp.RGBA8Unorm,o=1,a,l=-1,h=0,c){o=jp.GetSample(o);const u=jp.IsImageBitmapArray(e)?e[0].width:e.width,d=jp.IsImageBitmapArray(e)?e[0].height:e.height,_=tf[n]?ap.RenderAttachment:0,p=jp.IsCompressedFormat(n),f=t?jp.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:ap.CopySrc|ap.CopyDst|ap.TextureBinding;h|=t&&!p?ap.CopySrc|_:0,p||(h|=_|ap.CopyDst);const g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:op.E2d,format:n,usage:m|h,sampleCount:o,mipLevelCount:f});return jp.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,a)),g}generateCubeMipmaps(e,t,i,s){const r=void 0===s;r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.(`create cube mipmaps - ${i} levels`);for(let r=0;r<6;++r)this.generateMipmaps(e,t,i,r,!1,s);s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r=!1,n){const o=void 0===n,[a,l]=this._getPipeline(t);let h;if(s=Math.max(s,0),o&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup?.(`create mipmaps for face #${s} - ${i} levels`),jp.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let e=1;eh;)this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,r-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=p_(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0,d=this._engine.uniqueId;return new Promise(((i,_)=>{e.mapAsync(np.Read,a,t).then((()=>{const d=e.getMappedRange(a,t);let _=l;if(c)_=null===_?mn(o,t,!0,d):mn(o,_.buffer,void 0,d);else if(null===_)switch(u){case 0:_=new Uint8Array(t),_.set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:_=new Float32Array(t/4),_.set(new Float32Array(d))}else switch(u){case 0:_=new Uint8Array(_.buffer),_.set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:_=new Float32Array(_.buffer),_.set(new Float32Array(d))}if(r!==n){1!==u||c||(r*=2,n*=2);const e=new Uint8Array(_.buffer);let t=r,i=0;for(let o=1;o{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):_(e)}))}))}releaseBuffer(e){return nf._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return of[e.samplingMode]+af[(e._comparisonFunction||514)-512+1]+lf[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=dp.Linear,s=dp.Linear,r=dp.Nearest,a||(n=o=0);break;case 3:case 3:i=dp.Linear,s=dp.Linear,a?r=dp.Linear:(r=dp.Nearest,n=o=0);break;case 8:i=dp.Nearest,s=dp.Nearest,a?r=dp.Linear:(r=dp.Nearest,n=o=0);break;case 4:i=dp.Nearest,s=dp.Nearest,r=dp.Nearest,a||(n=o=0);break;case 5:i=dp.Nearest,s=dp.Linear,r=dp.Nearest,a||(n=o=0);break;case 6:i=dp.Nearest,s=dp.Linear,a?r=dp.Linear:(r=dp.Nearest,n=o=0);break;case 7:i=dp.Nearest,s=dp.Linear,r=dp.Nearest,n=o=0;break;case 1:case 1:default:i=dp.Nearest,s=dp.Nearest,r=dp.Nearest,n=o=0;break;case 9:i=dp.Linear,s=dp.Nearest,r=dp.Nearest,a||(n=o=0);break;case 10:i=dp.Linear,s=dp.Nearest,a?r=dp.Linear:(r=dp.Nearest,n=o=0);break;case 2:case 2:i=dp.Linear,s=dp.Linear,r=dp.Nearest,n=o=0;break;case 12:i=dp.Linear,s=dp.Nearest,r=dp.Nearest,n=o=0}return t>1&&(0!==n||0!==o)&&r!==dp.Nearest?{magFilter:dp.Linear,minFilter:dp.Linear,mipmapFilter:dp.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return up.Repeat;case 0:return up.ClampToEdge;case 2:return up.MirrorRepeat}return up.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?hf.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return pp.Always;case 514:return pp.Equal;case 516:return pp.Greater;case 518:return pp.GreaterEqual;case 513:default:return pp.Less;case 515:return pp.LessEqual;case 512:return pp.Never;case 517:return pp.NotEqual}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(hf._GetSamplerDescriptor(e,s));t?i=0:0===i&&(i=hf.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(hf._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var cf;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(cf||(cf={}));const uf={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},df={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},_f={[ys.PositionKind]:!0,[ys.NormalKind]:!0,[ys.TangentKind]:!0,[ys.UVKind]:!0,[ys.UV2Kind]:!0,[ys.UV3Kind]:!0,[ys.UV4Kind]:!0,[ys.UV5Kind]:!0,[ys.UV6Kind]:!0,[ys.ColorKind]:!0,[ys.ColorInstanceKind]:!0,[ys.MatricesIndicesKind]:!0,[ys.MatricesWeightsKind]:!0,[ys.MatricesIndicesExtraKind]:!0,[ys.MatricesWeightsExtraKind]:!0};class pf{static _IsSignedType(e){switch(e){case ys.BYTE:case ys.SHORT:case ys.INT:case ys.FLOAT:return!0;case ys.UNSIGNED_BYTE:case ys.UNSIGNED_SHORT:case ys.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[cp.BGRA8Unorm],this.setColorFormat(cp.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(cp.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,s=0){if(i=jp.GetSample(i),this.disabled){const r=pf._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,r,i),pf.NumCacheMiss++,pf._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,pf.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return pf.NumCacheHitWithHash++,this._parameter.pipeline;const r=pf._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),pf.NumCacheMiss++,pf._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){pf.NumPipelineCreationLastFrame=pf._NumPipelineCreationCurrentFrame,pf._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,s,r,n,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(a??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[cf.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[cf.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=tf[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let s=0,r=0,n=0;for(let o=0;o=32&&(r=0,s++)}this._mrtFormats.length=n,this._mrtAttachments1===i[0]&&this._mrtAttachments2===i[1]||(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[cf.MRTAttachments1]=i[0],this._states[cf.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:tf[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:df[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:df[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:df[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[cf.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[cf.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=null===i?1:df[i],this._stencilFrontPassOp=null===s?2:df[s],this._stencilFrontFailOp=null===r?1:df[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return Sp.TriangleList;case 2:case 3:return Sp.PointList;case 1:case 4:return Sp.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Sp.LineStrip;case 7:return Sp.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return Rp.Add;case 32778:return Rp.Subtract;case 32779:return Rp.ReverseSubtract;case 32775:return Rp.Min;case 32776:return Rp.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return Pp.Zero;case 1:default:return Pp.One;case 768:return Pp.Src;case 769:return Pp.OneMinusSrc;case 770:return Pp.SrcAlpha;case 771:return Pp.OneMinusSrcAlpha;case 772:return Pp.DstAlpha;case 773:return Pp.OneMinusDstAlpha;case 774:return Pp.Dst;case 775:return Pp.OneMinusDst;case 776:return Pp.SrcAlphaSaturated;case 32769:case 32771:return Pp.Constant;case 32770:case 32772:return Pp.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return pp.Never;case 1:return pp.Less;case 2:return pp.Equal;case 3:return pp.LessEqual;case 4:return pp.Greater;case 5:return pp.NotEqual;case 6:return pp.GreaterEqual;case 7:return pp.Always}return pp.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Ip.Zero;case 1:return Ip.Keep;case 2:return Ip.Replace;case 3:return Ip.IncrementClamp;case 4:return Ip.DecrementClamp;case 5:return Ip.Invert;case 6:return Ip.IncrementWrap;case 7:return Ip.DecrementWrap}return Ip.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case ys.BYTE:switch(s){case 1:case 2:return i?Op.Snorm8x2:Op.Sint8x2;case 3:case 4:return i?Op.Snorm8x4:Op.Sint8x4}break;case ys.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?Op.Unorm8x2:Op.Uint8x2;case 3:case 4:return i?Op.Unorm8x4:Op.Uint8x4}break;case ys.SHORT:switch(s){case 1:case 2:return i?Op.Snorm16x2:Op.Sint16x2;case 3:case 4:return i?Op.Snorm16x4:Op.Sint16x4}break;case ys.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?Op.Unorm16x2:Op.Uint16x2;case 3:case 4:return i?Op.Unorm16x4:Op.Uint16x4}break;case ys.INT:switch(s){case 1:return Op.Sint32;case 2:return Op.Sint32x2;case 3:return Op.Sint32x3;case 4:return Op.Sint32x4}break;case ys.UNSIGNED_INT:switch(s){case 1:return Op.Uint32;case 2:return Op.Uint32x2;case 3:return Op.Uint32x3;case 4:return Op.Uint32x4}break;case ys.FLOAT:switch(s){case 1:return Op.Float32;case 2:return Op.Float32x2;case 3:return Op.Float32x3;case 4:return Op.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:pf._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:pf._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:pf._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:pf._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:pf._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:pf._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[cf.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[cf.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:uf[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:uf[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:uf[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:uf[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[cf.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[cf.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,cf.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let i=cf.VertexState;const s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,n=s.shaderProcessingContext.attributeLocationsFromEffect;let o,a=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class bf{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=bf._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?hf.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){let i=this.textures[e],s=-1;i?s=i.texture?.uniqueId??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,i.isExternalTexture=xf.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const r=s!==(t?.uniqueId??-1);r&&this.updateId++,this.isDirty||(this.isDirty=r)}}bf._Counter=0;class Tf{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,rp.CopyDst|rp.Indirect|rp.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=Tf._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){this._isDirty||(this._isDirty=t?.uniqueId!==this.buffers[e]?.uniqueId),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}Tf._Counter=0;class yf{constructor(){this.values={}}}class Sf{static get Statistics(){return{totalCreated:Sf.NumBindGroupsCreatedTotal,lastFrameCreated:Sf.NumBindGroupsCreatedLastFrame,lookupLastFrame:Sf.NumBindGroupsLookupLastFrame,noLookupLastFrame:Sf.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Sf._Cache=new yf,Sf.NumBindGroupsCreatedTotal=0,Sf.NumBindGroupsCreatedLastFrame=0,Sf.NumBindGroupsLookupLastFrame=0,Sf.NumBindGroupsNoLookupLastFrame=0,Sf._NumBindGroupsCreatedCurrentFrame=0,Sf._NumBindGroupsLookupCurrentFrame=0,Sf._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Sf.NumBindGroupsCreatedLastFrame=Sf._NumBindGroupsCreatedCurrentFrame,Sf.NumBindGroupsLookupLastFrame=Sf._NumBindGroupsLookupCurrentFrame,Sf.NumBindGroupsNoLookupLastFrame=Sf._NumBindGroupsNoLookupCurrentFrame,Sf._NumBindGroupsCreatedCurrentFrame=0,Sf._NumBindGroupsLookupCurrentFrame=0,Sf._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){let s,r=Sf._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return Sf._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=t.buffers[i]?.uniqueId??0;let s=r.values[e];s||(s=new yf,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.samplerNames){const e=i.samplers[t]?.hashCode??0;let s=r.values[e];s||(s=new yf,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.textureNames){const e=i.textures[t]?.texture?.uniqueId??0;let s=r.values[e];s||(s=new yf,r.values[e]=s),r=s}s=r.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,Sf._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,n||(r.bindGroups=s),Sf.NumBindGroupsCreatedTotal++,Sf._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else we.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){we.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){we.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=n.storageTexture?t.viewForWriting:t.view}else we.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){we.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){we.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._device.importExternalTexture({source:t})}else we.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;a[s].resource.buffer=t,a[s].resource.size=e.capacity}else we.Error(`Can't find buffer "${l}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const l=o[r];s[r]=this._device.createBindGroup({layout:l,entries:a})}return s}}Sf.NumBindGroupsCreatedTotal=0,Sf.NumBindGroupsCreatedLastFrame=0,Sf.NumBindGroupsLookupLastFrame=0,Sf.NumBindGroupsNoLookupLastFrame=0,Sf._Cache=new yf,Sf._NumBindGroupsCreatedCurrentFrame=0,Sf._NumBindGroupsLookupCurrentFrame=0,Sf._NumBindGroupsNoLookupCurrentFrame=0;bi.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";bi.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";class Cf{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new mf(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,ui.WGSL)}clear(e,t,i,s,r=1){let n,o,a=null;const l=!!this._engine._currentRenderTarget;if(e)n=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+h*2**37,o=this._keyTemp.join("_"),a=this._bundleCache[o],a)return a;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:jp.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&jp.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),c=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),c.uniformBuffer.update();const u=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=c.uniformBuffer.getBuffer(),_=d.uniqueId+"-"+u.uniqueId;let p=this._bindGroups[_];if(!p){const e=c.bindGroupLayouts[0];p=this._bindGroups[_]=[],p.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${_}`,layout:e[0],entries:[]})),Hp._SimplifiedKnownBindings||p.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${_}`,layout:e[1],entries:[]})),p.push(this._device.createBindGroup({label:`clearQuadBindGroup${Hp._SimplifiedKnownBindings?1:2}-${_}`,layout:e[Hp._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:u.underlyingResource,size:u.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}n.setPipeline(h);for(let e=0;e{const e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw e}))}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(np.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(np.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then((e=>{t._addDuration(i,null!==e&&e>0?e:0)}))}dispose(){this._measureDuration?.dispose()}}class Ff{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new wf(e,s,Lp.Timestamp,t,i,!0,r)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class Bf{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,r=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=r,this._allocateNewIndices(s)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e})))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose),1e3)}dispose(){this._querySet?.dispose(),this._availableIndices.length=0}}class Lf{async initTwgsl(e){if(!Lf._Twgsl)return e=e||{},(e={...Lf._TWgslDefaultOptions,...e}).twgsl?(Lf._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await hs.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Lf._Twgsl=await self.twgsl(hs.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Lf._Twgsl.convertSpirV2WGSL(e,Lf.DisableUniformityAnalysis||t);return Lf.ShowWGSLShaderCode&&(we.Log(i),we.Log("***********************************************")),Lf.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}Lf._TWgslDefaultOptions={jsPath:`${hs._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${hs._DefaultCdnUrl}/twgsl/twgsl.wasm`},Lf.ShowWGSLShaderCode=!1,Lf.DisableUniformityAnalysis=!1,Lf._Twgsl=null;class kf{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}bi.ShadersStoreWGSL.postprocessVertexShader="attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";const Vf={label:"TextureView_SwapChain_ResolveTarget",dimension:op.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Uf={label:"TextureView_SwapChain",dimension:op.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Gf="/* disable_uniformity_analysis */",zf=new Ee;class Wf extends gn{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then((e=>!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return we.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new iu:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Wf(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){super(null,t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,we.Log(`Babylon.js v${gn.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new Xp,this._shaderProcessorWGSL=new Qp):we.Error("WebGPU is not supported by your browser.")}initAsync(e,t){return this.uniqueId=Wf._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??this._options?.glslangOptions).then((e=>(this._glslang=e,this._tintWASM=Wf.UseTWGSL?new Lf:null,this._tintWASM?this._tintWASM.initTwgsl(t??this._options?.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options))):navigator.gpu.requestAdapter(this._options)))).then((e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const t=this._options.deviceDescriptor??{},i=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(i){const e=i,s=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&s.push(t);t.requiredFeatures=s}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",(e=>{++t{this._isDisposed||(this._contextWasLost=!0,we.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost((async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,s=this.disableCacheRenderPipelines,r=this.disableCacheBindGroups,n=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=s,this.disableCacheBindGroups=r,this.enableGPUTimingMeasurements=n,this._currentRenderPass=null})))}))})).then((()=>{this._bufferManager=new nf(this,this._device),this._textureHelper=new sf(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new hf(this._device),this._cacheBindGroups=new Sf(this._device,this._cacheSampler,this),this._timestampQuery=new Nf(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Bf(this,this._device,this._bufferManager):void 0,this._bundleList=new Df(this._device),this._snapshotRendering=new kf(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),rp.Uniform|rp.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),rp.Uniform|rp.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,we.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new ys(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new mf(this._device,this._emptyVertexBuffer),this._depthCullingState=new vf(this._cacheRenderPipeline),this._stencilStateComposer=new gf(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new Cf(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()})).catch((e=>{throw we.Error("A fatal error occurred during WebGPU creation/initialization."),e}))}_initGlslang(e){return e=e||{},(e={...Wf._GLSLslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?hs.LoadBabylonScriptAsync(e.jsPath).then((()=>self.glslang(hs.GetBabylonScriptURL(e.wasmPath)))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(ip.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(ip.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(ip.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(ip.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(ip.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(ip.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(ip.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new Kp],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:op.E2d,format:this._options.swapChainFormat,usage:ap.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:op.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Ee(0,0,0,1),loadOp:Fp.Clear,storeOp:Bp.Store}]}else t=[{view:void 0,clearValue:new Ee(0,0,0,1),loadOp:Fp.Clear,storeOp:Bp.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?cp.Depth24PlusStencil8:cp.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:op.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:ap.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:op.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Fp.Clear,depthStoreOp:Bp.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Fp.Clear:void 0,stencilStoreOp:this.isStencilEnable?Bp.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:ap.RenderAttachment|ap.CopySrc,alphaMode:this.premultipliedAlpha?kp.Premultiplied:kp.Opaque})}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){mf.ResetCache(),Sf.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,r=t.indexOf(Gf)>=0,n=i===ui.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===ui.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf(Gf)>=0,n=t.indexOf(Gf)>=0,o="#version 450\n",a=s===ui.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=s===ui.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new U_(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new zp(e,this)}createMaterialContext(){return new bf}createDrawContext(){return new Tf(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(we.Log(["defines",a]),we.Log(t),we.Log(i),we.Log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},l.stages=s?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let e=0;e0,n.is3D=l>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=r.useSRGBBuffer,n.label=r.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,a,h||1,r.creationFlags),n}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,s,r,n,o,((e,t,i,s,r,n,o,a)=>{const l=s;if(e.baseWidth=l.width,e.baseHeight=l.height,e.width=l.width,e.height=l.height,e.format=-1!==e.format?e.format:h??5,e.type=-1!==e.type?e.type:0,e._creationFlags=_??0,a(e.width,e.height,l,t,e,(()=>{})),e._hardwareTexture?.underlyingResource)n||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,l.width,l.height,void 0,_);jp.IsImageBitmap(l)&&(this._textureHelper.updateTexture(l,e,l.width,l.height,e.depth,t.format,0,0,r,!1,0,0),n||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,p)}wrapWebGPUTexture(e){const t=new Kp(e),i=new Pi(this,Ai.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){if(e.generateMipMaps){const t=e._hardwareTexture?.underlyingResource;t||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e)}}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const s=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){const e=i+Gp.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let e=0;e0;for(const t in e){const r=e[t],n=i[t],o=n.group,a=n.binding,l=r.type,h=r.object;let c=r.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case tu.Sampler:{const e=h;void 0!==c&&s?u[c].resource=this._cacheSampler.getSampler(e):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case tu.Texture:case tu.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&s?(l===tu.Texture&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(r.indexInGroupEntries=u.length,l===tu.Texture&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case tu.StorageTexture:{const e=h,t=e._texture._hardwareTexture;t.textureAdditionalUsages&ap.StorageBinding||we.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&s?u[c].resource=t.viewForWriting:(r.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case tu.ExternalTexture:{const e=h.underlyingResource;void 0!==c&&s?u[c].resource=this._device.importExternalTexture({source:e}):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._device.importExternalTexture({source:e})}));break}case tu.UniformBuffer:case tu.StorageBuffer:case tu.DataBuffer:{const e=l===tu.DataBuffer?h:(tu.UniformBuffer,h.getBuffer()),t=e.underlyingResource;void 0!==c&&s?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e0&&c.dispatchWorkgroups(s,r,n),c.end(),a&&(this._timestampQuery.endPass(this._timestampIndex,a),this._timestampIndex+=2)},Wf.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},Wf.prototype._prepareComputePipelineContext=function(e,t,i,s,r){const n=e;this.dbgShowShaderCode&&(we.Log(s),we.Log(t)),n.sources={compute:t,rawCompute:i},n.stage=this._createComputePipelineStageDescriptor(t,s,r)},Wf.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},Wf.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},Wf.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((e=>{const i={numErrors:0,messages:[]};for(const t of e.messages)"error"===t.type&&i.numErrors++,i.messages.push({type:t.type,text:t.message,line:t.lineNum,column:t.linePos,length:t.length,offset:t.offset});t(i)}))},Wf.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},Wf.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},Wf.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Pi(this,t.generateStencil?Ai.DepthStencil:Ai.Depth);i.isCube=!0,i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=jp.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Wf.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,null,((e,t)=>{const i=t,n=i[0].width,a=n;this._setCubeMapTextureParams(e,!s),e.format=o??-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,n,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,n,a,l.format,!1,!1,0,0),s||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),r&&r()}),!!d)},Wf.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},Wf.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},Wf.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},Wf.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},Wf.prototype._debugFlushPendingCommands=function(){for(let e=0;e{const i=d.width,n=o(e);if(!n)return;const h=[0,2,4,1,3,5];if(a){const e=4===s,t=a(n),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let s=0;s>s,a=[];for(let i=0;i<6;i++){let o=t[s][l[i]];e&&(o=jf(o,n,n,r)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,n,n,o.format,u,!1,0,0)}}else{const e=[];for(let t=0;t<6;t++)e.push(n[h[t]]);this.updateRawCubeTexture(d,e,s,r,u)}d.isReady=!0,t?.removePendingData(d),l&&l()};return this._loadFile(e,(e=>{_(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},Wf.prototype.createRawTexture3D=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=Ai.Raw3D,d=new Pi(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is3D=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Wf.prototype.updateRawTexture3D=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=jf(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Wf.prototype.createRawTexture2DArray=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=Ai.Raw2DArray,d=new Pi(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is2DArray=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,s,c),this.updateRawTexture2DArray(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Wf.prototype.updateRawTexture2DArray=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=jf(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Wf.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,s,r,n,a)},Wf.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class Kf extends Ka{constructor(e,t,i,s,r){super(e,t,i,s,r),s.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new iu)}}Wf.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const s=new Kf(e,t,i,this);return this._renderTargetWrapperCache.push(s),s},Wf.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode,s.creationFlags=t.creationFlags??0,s.noColorAttachment=!!t.noColorAttachment,s.samples=t.samples,s.label=t.label):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.samplingMode=3,s.creationFlags=0,s.noColorAttachment=!1);const r=s.noColorAttachment?null:this._createInternalTexture(e,t,!0,Ai.RenderTarget);return i.label=s.label??"RenderTargetWrapper",i._samples=s.samples??1,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,!1,i._generateStencilBuffer,i.samples,s.generateStencilBuffer?13:14,s.label?s.label+"-DepthStencil":void 0),r&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r,void 0,void 0,void 0,s.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1)),i},Wf.prototype._createDepthStencilTexture=function(e,t){const i=new Pi(this,t.generateStencil?Ai.DepthStencil:Ai.Depth);i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=jp.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Wf.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.is3D=h>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=1,e._comparisonFunction=r,e._cachedWrapU=0,e._cachedWrapV=0},Wf.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},Wf.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=s.label??"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new Pi(this,Ai.RenderTarget);return r.width=e,r.height=e,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i},Ti.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},Wf.prototype.setTextureSampler=function(e,t){this._currentMaterialContext?.setSampler(e,t)},Ti.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},Wf.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,32|t,i)},Wf.prototype.updateStorageBuffer=function(e,t,i,s){const r=e;let n;void 0===i&&(i=0),void 0===s?(n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,s=n.byteLength):n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(r,i,n,0,s)},Wf.prototype.readFromStorageBuffer=function(e,t,i,s,r){i=i||e.capacity;const n=this._bufferManager.createRawBuffer(i,rp.MapRead|rp.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t??0,n,0,i),new Promise(((e,t)=>{const o=()=>{n.mapAsync(np.Read,0,i).then((()=>{const t=n.getMappedRange(0,i);let r=s;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}n.unmap(),this._bufferManager.releaseBuffer(n),e(r)}),(i=>{this.isDisposed?e(new Uint8Array):t(i)}))};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce((()=>{o()}))}))},Wf.prototype.setStorageBuffer=function(e,t){this._currentDrawContext?.setBuffer(e,t?.getBuffer()??null)},Wf.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),function(e){return!(!e||void 0===e.underlyingResource)}(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0})).catch((()=>{e.isReady=!0}))};class $f{static async CreateAsync(e,t){return await Wf.IsSupportedAsync?Wf.CreateAsync(e,t):gn.IsSupported?new gn(e,void 0,t):new jd(t)}}class qf{}qf.COPY=1,qf.CUT=2,qf.PASTE=3;class Zf{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return qf.COPY;case 86:return qf.PASTE;case 88:return qf.CUT;default:return-1}}}class Jf extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ce.Gray(),i=uu.DefaultUtilityLayer,s=null,r=1,n=Ce.Yellow(),o=Ce.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new X,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new de(0,0,0),this._incrementalStartupValue=de.Zero(),this._parent=s,this._coloredMaterial=new yc("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ce(.1,.1,.1)),this._hoverMaterial=new yc("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new yc("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new bo("axis",i.utilityLayerScene);const{arrowMesh:a,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,r),h=this._createGizmoMesh(this._gizmoMesh,r+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,fu.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const c=a.position.clone(),u=l.position.clone(),d=l.scaling.clone(),_=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;a.position.z+=t/3.5,l.scaling.y+=t,this.dragScale=l.scaling.y,l.position.z=a.position.z/2},p=()=>{a.position.set(c.x,c.y,c.z),l.position.set(u.x,u.y,u.z),l.scaling.set(d.x,d.y,d.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new sa({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let f=0,m=0;const g={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),s=this._tmpVector;let r=!1,n=0;if(this.uniformScaling?s.setAll(.57735):s.copyFrom(e),0==this.snapDistance)s.scaleToRef(i,s);else{f+=i,m+=i;const e=this.incrementalSnap?m:f;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),f%=this.snapDistance,s.scaleToRef(this.snapDistance*n,s),r=!0):s.scaleInPlace(0)}s.addInPlaceFromFloats(1,1,1),s.x=Math.abs(s.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,ge.Quaternion[0],ge.Vector3[2],fu.PreserveScaling?o:void 0),s.addInPlace(this._incrementalStartupValue),s.addInPlaceFromFloats(-1,-1,-1),s.x=Math.abs(s.x)*(this._incrementalStartupValue.x>0?1:-1),s.y=Math.abs(s.y)*(this._incrementalStartupValue.y>0?1:-1),s.z=Math.abs(s.z)*(this._incrementalStartupValue.z>0?1:-1),fe.ComposeToRef(s,ge.Quaternion[0],ge.Vector3[2],ge.Matrix[1])):(fe.ScalingToRef(s.x,s.y,s.z,ge.Matrix[2]),ge.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),ge.Matrix[1])),ge.Matrix[1].decompose(ge.Vector3[1],void 0,void 0,fu.PreserveScaling?o:void 0);const a=1e5;Math.abs(ge.Vector3[1].x){this._dragging=!0;const e=this.attachedNode._isMesh?this.attachedNode:void 0;this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,fu.PreserveScaling?e:void 0),f=0,m=0})),this.dragBehavior.onDragObservable.add((e=>_(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(p),s?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e=>_(e.delta.y))),s?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(p);const v={gizmoMeshes:[a,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,v),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(this._customMeshSet)return;let t=this._parent?.getAxisCache(this._gizmoMesh);if(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),t=this._parent?.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh))),!this._parent){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(v.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(v.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const s=yu("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),r=lu("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return s.scaling.scaleInPlace(.1),s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,s.position.z+=.3,r.material=this._coloredMaterial,r.position.z+=.1375,r.rotation.x=Math.PI/2,i&&(s.visibility=0,r.visibility=0),e.addChild(s),e.addChild(r),{arrowMesh:s,arrowTail:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}Jf.MinimumAbsoluteScale=K;class em extends fu{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let e=0;e<3;e++)for(let s=0;s<3;s++)for(let r=0;r<3;r++){const n=(1===e?1:0)+(1===s?1:0)+(1===r?1:0);if(1!==n&&3!==n){if(t[i]){const n=new de(e-1,s-1,r-1);n.multiplyInPlace(this._axisFactor),t[i].setEnabled(n.lengthSquared()>K)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}get isDragging(){return this._dragging||this._pointerDragBehavior.dragging}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new Ce(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach((t=>{t.color&&(t.color=e)}))}constructor(e=Ce.Gray(),t=uu.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new de(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._rotateSpheresDragBehaviors=[],this._scaleBoxesDragBehaviors=[],this._dragging=!1,this._tmpQuaternion=new pe,this._tmpVector=new de(0,0,0),this._tmpRotationMatrix=new fe,this._incrementalStartupValue=de.Zero(),this._incrementalAnchorStartupValue=de.Zero(),this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.scalingSnapDistance=0,this.rotationSnapDistance=0,this.onDragStartObservable=new X,this.onScaleBoxDragObservable=new X,this.onScaleBoxDragEndObservable=new X,this.onRotationSphereDragObservable=new X,this.onRotationSphereDragEndObservable=new X,this.scalePivot=null,this._axisFactor=new de(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new de,this._dragMesh=null,this._pointerDragBehavior=new sa,this.updateScale=!1,this._anchorMesh=new Sn("anchor",t.utilityLayerScene),this._coloredMaterial=new yc("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new yc("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new Sn("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new pe;const i=[];i.push(Zu("lines",{points:[new de(0,0,0),new de(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,0,0),new de(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,0,0),new de(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,0,0),new de(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,0,0),new de(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,this._boundingDimensions.y,0),new de(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,this._boundingDimensions.y,0),new de(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,0,this._boundingDimensions.z),new de(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(0,0,this._boundingDimensions.z),new de(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new de(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new de(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Zu("lines",{points:[new de(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new de(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach((t=>{t.color=e,t.position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),t.isPickable=!1,this._lineBoundingBox.addChild(t)})),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateSpheresParent=new Sn("",t.utilityLayerScene),this._rotateSpheresParent.rotationQuaternion=new pe;for(let e=0;e<12;e++){const i=Eu("",{diameter:1},t.utilityLayerScene);i.rotationQuaternion=new pe,i.material=this._coloredMaterial,i.isNearGrabbable=!0;const s=new sa({});s.moveAttached=!1,s.updateDragPlane=!1,i.addBehavior(s);const r=new de(1,0,0);let n=0,o=0;s.onDragStartObservable.add((()=>{r.copyFrom(i.forward),n=0,o=0})),s.onDragObservable.add((t=>{if(this.onRotationSphereDragObservable.notifyObservers({}),this.attachedMesh){const i=this.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void we.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Jo._RemoveAndStorePivotPoint(this.attachedMesh);const s=r,a=t.dragPlaneNormal.scale(de.Dot(t.dragPlaneNormal,s)),l=s.subtract(a).normalizeToNew();let h=de.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());if(h=h/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=pe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=pe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),n+=h,Math.abs(n)<=2*Math.PI){if(this.rotationSnapDistance>0){const e=Math.floor(Math.abs(n)/this.rotationSnapDistance)*(n<0?-1:1),t=this.rotationSnapDistance*e;h=t-o,o=t}e>=8?pe.RotationYawPitchRollToRef(0,0,h,this._tmpQuaternion):e>=4?pe.RotationYawPitchRollToRef(h,0,0,this._tmpQuaternion):pe.RotationYawPitchRollToRef(0,h,0,this._tmpQuaternion),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.copyFrom(this.attachedMesh.position),this._anchorMesh.addChild(this.attachedMesh),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._tmpQuaternion.normalize(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.rotationQuaternion.normalize(),this._anchorMesh.removeChild(this.attachedMesh),this.attachedMesh.setParent(i)}this.updateBoundingBox(),Jo._RestorePivotPoint(this.attachedMesh)}this._updateDummy()})),s.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(i)})),s.onDragEndObservable.add((e=>{this.onRotationSphereDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,i)})),this._rotateSpheresDragBehaviors.push(s),this._rotateSpheresParent.addChild(i)}this._rootMesh.addChild(this._rotateSpheresParent),this._scaleBoxesParent=new Sn("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new pe;for(let e=0;e<3;e++)for(let i=0;i<3;i++)for(let s=0;s<3;s++){const r=(1===e?1:0)+(1===i?1:0)+(1===s?1:0);if(1===r||3===r)continue;const n=yu("",{size:1},t.utilityLayerScene);n.material=this._coloredMaterial,n._internalMetadata=2===r,n.isNearGrabbable=!0;const o=new de(e-1,i-1,s-1).normalize(),a=new sa({dragAxis:o});a.updateDragPlane=!1,a.moveAttached=!1;let l=0,h=0;n.addBehavior(a),a.onDragObservable.add((e=>{if(this.onScaleBoxDragObservable.notifyObservers({}),this.attachedMesh){const t=this.attachedMesh.parent;if(t&&t.scaling&&t.scaling.isNonUniformWithinEpsilon(.001))return void we.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Jo._RemoveAndStorePivotPoint(this.attachedMesh);let i=e.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(l+=i,this.scalingSnapDistance>0){const e=Math.floor(Math.abs(l)/this.scalingSnapDistance)*(l<0?-1:1),t=this.scalingSnapDistance*e;i=t-h,h=t}const s=new de(i,i,i),a=new de(h,h,h);2===r&&(s.x*=Math.abs(o.x),s.y*=Math.abs(o.y),s.z*=Math.abs(o.z)),s.scaleInPlace(this._scaleDragSpeed),s.multiplyInPlace(this._axisFactor),a.scaleInPlace(this._scaleDragSpeed),a.multiplyInPlace(this._axisFactor),a.addInPlace(this._incrementalStartupValue),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),de.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),de.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(n.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.subtractInPlace(this.attachedMesh.getPivotPoint())),this._anchorMesh.addChild(this.attachedMesh),this.incrementalSnap?(a.x/=Math.abs(this._incrementalStartupValue.x){this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(n),l=0,h=0,this._incrementalStartupValue.copyFrom(this.attachedMesh.scaling),this._incrementalAnchorStartupValue.copyFrom(this._anchorMesh.scaling)})),a.onDragEndObservable.add((e=>{this.onScaleBoxDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,n)})),this._scaleBoxesParent.addChild(n),this._scaleBoxesDragBehaviors.push(a)}this._rootMesh.addChild(this._scaleBoxesParent);const s=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add((e=>{s[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=s[e.event.pointerId]&&(s[e.event.pointerId].material=this._coloredMaterial,delete s[e.event.pointerId],this._isHovered=!1):this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{e.pickInfo&&e.pickInfo.pickedMesh==t&&(s[e.event.pointerId]=t,t.material=this._hoverColoredMaterial,this._isHovered=!0)}))})),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationSpheres(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))})),this.updateBoundingBox()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),Jo._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),Jo._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach((e=>{e.markAsDirty("scaling")})),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce((()=>{this._updateDummy()}))}}_selectNode(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{t.isVisible=!e||t==e}))}_unhoverMeshOnTouchUp(e,t){e?.event instanceof PointerEvent&&"touch"===e?.event.pointerType&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){Jo._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=pe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=pe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),Jo._RestorePivotPoint(this.attachedMesh))}_updateRotationSpheres(){const e=this._rotateSpheresParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let s=0;s<2;s++){const r=4*t+2*i+s;if(0==t&&(e[r].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*s),e[r].position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(de.Cross(e[r].position.normalizeToNew(),de.Right()).normalizeToNew().add(e[r].position))),1==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*s),e[r].position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(de.Cross(e[r].position.normalizeToNew(),de.Up()).normalizeToNew().add(e[r].position))),2==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*s,this._boundingDimensions.z/2),e[r].position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(de.Cross(e[r].position.normalizeToNew(),de.Forward()).normalizeToNew().add(e[r].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const t=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(t,t,t)}else this.fixedDragMeshBoundsSize?e[r].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[r].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let s=0;s<3;s++)for(let r=0;r<3;r++){const n=(1===i?1:0)+(1===s?1:0)+(1===r?1:0);if(1!==n&&3!==n){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(s/2),this._boundingDimensions.z*(r/2)),e[t].position.addInPlace(new de(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);const i=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(i,i,i)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateSpheresParent.getChildMeshes().forEach(((t,i)=>{i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach((i=>{let s=e;t&&!0===i._internalMetadata&&(s=!1),i.setEnabled(s)}))}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=yu("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new pe,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}releaseDrag(){this._scaleBoxesDragBehaviors.forEach((e=>{e.releaseDrag()})),this._rotateSpheresDragBehaviors.forEach((e=>{e.releaseDrag()})),this._pointerDragBehavior.releaseDrag()}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),this._scaleBoxesDragBehaviors.length=0,this._rotateSpheresDragBehaviors.length=0,super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e),e.rotationQuaternion||(e.rotationQuaternion=pe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),s=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const r=yu("box",{size:1},e.getScene()),n=e.getHierarchyBoundingVectors();return n.max.subtractToRef(n.min,r.scaling),0===r.scaling.y&&(r.scaling.y=K),0===r.scaling.x&&(r.scaling.x=K),0===r.scaling.z&&(r.scaling.z=K),r.position.set((n.max.x+n.min.x)/2,(n.max.y+n.min.y)/2,(n.max.z+n.min.z)/2),e.addChild(r),e.rotationQuaternion.copyFrom(s),e.position.copyFrom(i),e.removeChild(r),r.addChild(e),r.visibility=0,r}setCustomMesh(){we.Error("Custom meshes are not supported on this gizmo")}}class tm extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ce.Gray(),i=uu.DefaultUtilityLayer,s=32,r=null,n=!1,o=1,a=Ce.Yellow(),l=Ce.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new X,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new de,this._parent=r,this._coloredMaterial=new yc("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ce(.1,.1,.1)),this._hoverMaterial=new yc("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._hoverMaterial.specularColor=a,this._disableMaterial=new yc("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new bo("",i.utilityLayerScene);const{rotationMesh:h,collider:c}=this._createGizmoMesh(this._gizmoMesh,o,s);this._rotationDisplayPlane=ta("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),Ti.ShadersStore.rotationGizmoVertexShader=tm._RotationGizmoVertexShader,Ti.ShadersStore.rotationGizmoFragmentShader=tm._RotationGizmoFragmentShader,this._rotationShaderMaterial=new Yu("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=a,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,fu.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new sa({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=tm.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new de,d=new fe,_=new de;let p=new de;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(d),de.TransformCoordinatesToRef(e.dragPlanePoint,d,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const f={snapDistance:0};let m=0;const g=new fe,v=new pe;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const s=new de(1,1,1),r=new pe(0,0,0,1),n=new de(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(s,r,n),!(Math.abs(Math.abs(s.x)-Math.abs(s.y))<=K&&Math.abs(Math.abs(s.x)-Math.abs(s.z))<=K)&&this.updateGizmoRotationToMatchAttachedMesh)return void we.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");r.normalize();const o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,a=t.dragPlanePoint.subtract(o).normalize(),l=u.subtract(o).normalize(),h=de.Cross(a,l),c=de.Dot(a,l);let x=Math.atan2(h.length(),c)*this.sensitivity;_.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(r.toRotationMatrix(d),p=de.TransformCoordinates(_,d));let b=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();de.Dot(e,p)>0&&(_.scaleInPlace(-1),p.scaleInPlace(-1),b=!0)}de.Dot(p,h)>0&&(x=-x),ge.Vector3[0].set(x,0,0),this.dragBehavior.validateDrag(ge.Vector3[0])||(x=0);let T=!1;if(0!=this.snapDistance)if(m+=x,Math.abs(m)>this.snapDistance){let e=Math.floor(Math.abs(m)/this.snapDistance);m<0&&(e*=-1),m%=this.snapDistance,x=this.snapDistance*e,T=!0}else x=0;const y=Math.sin(x/2);if(v.set(_.x*y,_.y*y,_.z*y,Math.cos(x/2)),g.determinant()>0){const e=new de;v.toEulerAnglesToRef(e),pe.RotationYawPitchRollToRef(e.y,-e.x,-e.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)r.multiplyToRef(v,r),r.normalize(),fe.ComposeToRef(s,r,n,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(ge.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(ge.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),T&&(f.snapDistance=x,this.onSnapObservable.notifyObservers(f)),this._angles.y+=x,this.angle+=b?-x:x,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[c],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=tm.MaxDragAngle,this._isHovered=!(-1==b.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const s=Xc("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);s.visibility=0;const r=Xc("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,s.rotation.x=Math.PI/2,e.addChild(r,fu.PreserveScaling),e.addChild(s,fu.PreserveScaling),{rotationMesh:r,collider:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}tm.MaxDragAngle=9*Math.PI/20,tm._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",tm._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ";class im extends fu{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&we.Log("Rotation Gizmo will not work with transforms in billboard mode.")}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=uu.DefaultUtilityLayer,t=32,i=!1,s=1,r,n){super(e),this.onDragStartObservable=new X,this.onDragObservable=new X,this.onDragEndObservable=new X,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=n&&n.xOptions&&n.xOptions.color?n.xOptions.color:Ce.Red().scale(.5),a=n&&n.yOptions&&n.yOptions.color?n.yOptions.color:Ce.Green().scale(.5),l=n&&n.zOptions&&n.zOptions.color?n.zOptions.color:Ce.Blue().scale(.5);this.xGizmo=new tm(new de(1,0,0),o,e,t,this,i,s),this.yGizmo=new tm(new de(0,1,0),a,e,t,this,i,s),this.zGizmo=new tm(new de(0,0,1),l,e,t,this,i,s),this.additionalTransformNode=n?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((e=>{n&&null!=n.updateScale&&(e.updateScale=n.updateScale),e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,r?r.addToAxisCache(this._gizmoAxisCache):fu.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}))}setCustomMesh(){we.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class sm extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new xn("plane",e),s=ta("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return s.material=t,s.parent=i,i}constructor(e,t=Ce.Gray(),i=uu.DefaultUtilityLayer,s=null,r=Ce.Yellow(),n=Ce.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new X,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new yc("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ce(.1,.1,.1)),this._hoverMaterial=new yc("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=r,this._disableMaterial=new yc("",i.utilityLayerScene),this._disableMaterial.diffuseColor=n,this._disableMaterial.alpha=.4,this._gizmoMesh=sm._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let o=0;const a=new de,l={snapDistance:0};this.dragBehavior=new sa({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(ge.Vector3[0]),ge.Vector3[0].addToRef(e.delta,ge.Vector3[0]),this.dragBehavior.validateDrag(ge.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z);else if(o+=e.dragDistance,Math.abs(o)>this.snapDistance){const t=Math.floor(Math.abs(o)/this.snapDistance);o%=this.snapDistance,e.delta.normalizeToRef(a),a.scaleInPlace(this.snapDistance*t),this.attachedNode.getWorldMatrix().getTranslationToRef(ge.Vector3[0]),ge.Vector3[0].addToRef(a,ge.Vector3[0]),this.dragBehavior.validateDrag(ge.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(a.x,a.y,a.z),l.snapDistance=this.snapDistance*t,this.onSnapObservable.notifyObservers(l))}this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const h=i._getSharedGizmoLight();h.includedOnlyMeshes=h.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const c={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,c),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==c.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=c.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(c.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(c.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class rm extends fu{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=uu.DefaultUtilityLayer,t=1,i,s){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new X,this.onDragObservable=new X,this.onDragEndObservable=new X,this._planarGizmoEnabled=!1,this.xGizmo=new mu(new de(1,0,0),Ce.Red().scale(.5),e,this,t),this.yGizmo=new mu(new de(0,1,0),Ce.Green().scale(.5),e,this,t),this.zGizmo=new mu(new de(0,0,1),Ce.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new sm(new de(1,0,0),Ce.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new sm(new de(0,1,0),Ce.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new sm(new de(0,0,1),Ce.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=s?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):fu.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))}),this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)}))}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear()}setCustomMesh(){we.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}class nm extends fu{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.uniformScaleGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=uu.DefaultUtilityLayer,t=1,i,s){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new X,this.onDragObservable=new X,this.onDragEndObservable=new X,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new Jf(new de(1,0,0),Ce.Red().scale(.5),e,this,t),this.yGizmo=new Jf(new de(0,1,0),Ce.Green().scale(.5),e,this,t),this.zGizmo=new Jf(new de(0,0,1),Ce.Blue().scale(.5),e,this,t),this.additionalTransformNode=s?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):fu.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new yc("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Ce.Gray(),this._hoverMaterial=new yc("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Ce.Yellow(),this._disableMaterial=new yc("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Ce.Gray(),this._disableMaterial.alpha=.4;const e=new Jf(new de(0,1,0),Ce.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=vd("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=vd("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._octahedron,this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))):we.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.anchorPoint=e)}))}get anchorPoint(){return this._anchorPoint}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set coordinatesMode(e){e==_u.World&&we.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.coordinatesMode=_u.Local}))}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set incrementalSnap(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.incrementalSnap=e)}))}get incrementalSnap(){return this._incrementalSnap}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}getAxisCache(e){return this._gizmoAxisCache.get(e)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach((e=>{e&&e.dispose()})),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class om{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}get isDragging(){let e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((t=>{t&&t.isDragging&&(e=!0)})),e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set coordinatesMode(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.coordinatesMode=e)}))}get coordinatesMode(){return this._coordinatesMode}get attachedMesh(){return this._attachedMesh}get attachedNode(){return this._attachedNode}get additionalTransformNode(){return this._additionalTransformNode}constructor(e,t=1,i=uu.DefaultUtilityLayer,s=uu.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new X,this.onAttachedToNodeObservable=new X,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Ce.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=_u.Local,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new oa,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=s,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const r=this._attachToMeshPointerObserver(e),n=fu.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[r,n]}_attachToMeshPointerObserver(e){return e.onPointerObservable.add((e=>{if(this.usePointerToAttachGizmos&&e.type==Ms.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){if(this.enableAutoPicking){let t=e.pickInfo.pickedMesh;if(null==this.attachableMeshes)for(;t&&null!=t.parent;)t=t.parent;else{let e=!1;this.attachableMeshes.forEach((i=>{t&&(t==i||t.isDescendantOf(i))&&(t=i,e=!0)})),e||(t=null)}t instanceof Sn?this._attachedMesh!=t&&this.attachToMesh(t):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}))}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new rm(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new im(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new nm(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new em(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}set additionalTransformNode(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()}_setAdditionalTransformNode(){for(const e in this.gizmos){const t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}}addToAxisCache(e){e.size>0&&e.forEach(((e,t)=>{this._gizmoAxisCache.set(t,e)}))}releaseDrag(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((e=>{e?.releaseDrag()}))}dispose(){this._pointerObservers.forEach((e=>{this._scene.onPointerObservable.remove(e)}));for(const e in this.gizmos){const t=this.gizmos[e];t&&t.dispose()}this._defaultKeepDepthUtilityLayer!==uu._DefaultKeepDepthUtilityLayer&&this._defaultKeepDepthUtilityLayer?.dispose(),this._defaultUtilityLayer!==uu._DefaultUtilityLayer&&this._defaultUtilityLayer?.dispose(),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class am extends yo{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=fe.Identity(),this._projectionMatrix=fe.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix||(this.transformedPosition||(this.transformedPosition=de.Zero()),de.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=de.Zero()),de.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=de.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=de.Cross(this.direction,_r.Y),t=de.Cross(e,this.direction);return de.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=de.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=fe.Identity()),fe.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=ge.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),de.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(de.Dot(t,de.Up()))&&(t.z=1e-13);const s=ge.Vector3[1];return i.addToRef(t,s),fe.LookAtLHToRef(i,s,de.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}qe([lt()],am.prototype,"position",null),qe([lt()],am.prototype,"direction",null),qe([st()],am.prototype,"shadowMinZ",null),qe([st()],am.prototype,"shadowMaxZ",null),Ct.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new lm(e,de.Zero(),t)));class lm extends am{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return yo.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&fe.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=de.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zr&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;fe.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?a:o,l?o:a,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function hm(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const s=Eu("",{slice:.5,diameter:t.diameter,segments:t.segments},i),r=Nu("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);r.rotation.x=-Math.PI/2,r.parent=s;const n=bo.MergeMeshes([r,s],!0);return n.name=e,n}qe([st()],lm.prototype,"shadowFrustumSize",null),qe([st()],lm.prototype,"shadowOrthoScale",null),qe([st()],lm.prototype,"autoUpdateExtends",void 0),qe([st()],lm.prototype,"autoCalcShadowZBounds",void 0),qe([st("orthoLeft")],lm.prototype,"_orthoLeft",void 0),qe([st("orthoRight")],lm.prototype,"_orthoRight",void 0),qe([st("orthoTop")],lm.prototype,"_orthoTop",void 0),qe([st("orthoBottom")],lm.prototype,"_orthoBottom",void 0);const cm={CreateHemisphere:hm};bo.CreateHemisphere=(e,t,i,s)=>hm(e,{segments:t,diameter:i},s),Ct.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new um(e,de.Zero(),de.Zero(),0,0,t)));class um extends am{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(um._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):um._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=fe.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=de.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=de.Zero(),this._projectionTextureViewLightMatrix=fe.Zero(),this._projectionTextureProjectionLightMatrix=fe.Zero(),this._projectionTextureScalingMatrix=fe.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return yo.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;fe.PerspectiveFovLHToRef(r,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),fe.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),s=-i*t,r=1/Math.tan(this._angle/2);fe.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Vo){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;fe.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=de.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=de.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?de.Normalize(this.transformedDirection):de.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}qe([st()],um.prototype,"angle",null),qe([st()],um.prototype,"innerAngle",null),qe([st()],um.prototype,"shadowAngleScale",null),qe([st()],um.prototype,"exponent",void 0),qe([st()],um.prototype,"projectionTextureLightNear",null),qe([st()],um.prototype,"projectionTextureLightFar",null),qe([st()],um.prototype,"projectionTextureUpDirection",null),qe([rt("projectedLightTexture")],um.prototype,"_projectionTexture",void 0);class dm extends fu{constructor(e=uu.DefaultUtilityLayer){super(e),this._cachedPosition=new de,this._cachedForward=new de(0,0,1),this._pointerObserver=null,this.onClickedObservable=new X,this._light=null,this.attachedMesh=new Sn("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new xn("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new yc("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Ce(.5,.5,.5),this._material.specularColor=new Ce(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),Ms.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){we.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof cu?dm._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof lm?dm._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof um?dm._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):dm._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new pe,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(ge.Vector3[0]),e=ge.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new de(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(de.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new de(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else de.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new bo("hemisphereLight",e),i=hm(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(dm._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new bo("pointLight",e),i=Eu(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(dm._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new bo("spotLight",e);Eu(t.name,{segments:10,diameter:1},e).parent=t;const i=hm(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(dm._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new bo("directionalLight",e),i=new bo(t.name,e);i.parent=t,Eu(t.name,{diameter:1.2,segments:10},e).parent=i;const s=lu(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let r=s.clone(t.name);r.scaling.y=.5,r.position.x+=1.25;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;const o=lu(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,r=o.clone(t.name),r.position.y=1.5,r.position.x+=1.25,n=o.clone(t.name),n.position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(dm._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}dm._Scale=.007,dm._CreateLightLines=(e,t)=>{const i=new bo("root",t);i.rotation.x=Math.PI/2;const s=new bo("linePivot",t);s.parent=i;const r=lu("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(r.position.y=r.scaling.y/2+1.2,r.parent=s,e<2)return s;for(let e=0;e<4;e++){const t=s.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(s.clone("linePivotClone").rotation.z=Math.PI),i};class _m extends fu{constructor(e=uu.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new X,this._camera=null,this._invProjection=new fe,this._material=new yc("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Ce(.5,.5,.5),this._material.specularColor=new Ce(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),Ms.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=_m._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const t=this._frustumLinesColor?.toColor4(1)??new Ee(1,1,1,1);this._cameraLinesMesh=_m._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,t),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new bo("rootCameraGizmo",e),i=new bo(t.name,e);i.parent=t,yu(t.name,{width:1,height:.8,depth:.5},e).parent=i;const s=lu(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;const r=lu(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);r.parent=i,r.position.y=.5,r.position.x=.4,r.rotation.x=.5*Math.PI;const n=lu(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(_m._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){const i=new bo("rootCameraGizmo",e),s=new bo(i.name,e);s.parent=i;for(let i=0;i<4;i+=2)for(let r=0;r<4;r+=2){let n=Zu("lines",{points:[new de(-1+r,-1+i,-1),new de(-1+r,-1+i,1)],colors:[t,t]},e);n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Zu("lines",{points:[new de(-1,-1+r,-1+i),new de(1,-1+r,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Zu("lines",{points:[new de(-1+r,-1,-1+i),new de(-1+r,1,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}_m._Scale=.05;bi.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";bi.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";bi.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";bi.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";bi.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";bi.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";bi.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class pm extends qa{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=Vo.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return yt.Parse((()=>new pm(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,s)}}qe([st("kernel")],pm.prototype,"_kernel",void 0),qe([st("packedFloat")],pm.prototype,"_packedFloat",void 0),qe([at()],pm.prototype,"direction",void 0),ee("BABYLON.BlurPostProcess",pm);class fm extends pl{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,s,r=0,n=Vo.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new ir(0,1,0,1),this._transformMatrix=fe.Zero(),this._mirrorMatrix=fe.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const a=i.getEngine();let l;a.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{a._debugPushGroup?.(`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),fe.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),l=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=de.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=l}))}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new pm("horizontal blur",new ue(1,0),this._blurKernelX,this._blurRatio,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new pm("vertical blur",new ue(0,1),this._blurKernelY,this._blurRatio,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new fm(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),this._sceneUBO?.dispose()}}Vo._CreateMirror=(e,t,i,s)=>new fm(e,t,i,s);class mm extends No{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(fe.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach((e=>s+=e)),new mm(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new mm(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,a=5,l=!1,h=null,c=!1,u=.8,d=0,_,p){super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new X,this.boundingBoxPosition=de.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new fe,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=a,this.isCube=!0,this._textureMatrix=fe.Identity(),this._createPolynomials=c,this.coordinatesMode=Vo.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=h,this._loaderOptions=_,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=d,(e||r)&&this.updateURL(e,h,n,l,o,i,this.getScene()?.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(d||u||c||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=ge.Vector3[0],i=ge.Quaternion[0],s=ge.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,fe.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Vo.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?hs.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const s=yt.Parse((()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new mm(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=de.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=de.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new mm(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}qe([st()],mm.prototype,"url",void 0),qe([lt()],mm.prototype,"boundingBoxPosition",void 0),qe([lt()],mm.prototype,"boundingBoxSize",null),qe([st("rotationY")],mm.prototype,"rotationY",null),qe([st("files")],mm.prototype,"_files",void 0),qe([st("forcedExtension")],mm.prototype,"_forcedExtension",void 0),qe([st("extensions")],mm.prototype,"_extensions",void 0),qe([pt("textureMatrix")],mm.prototype,"_textureMatrix",void 0),qe([pt("textureMatrixRefraction")],mm.prototype,"_textureMatrixRefraction",void 0),Vo._CubeTextureParser=mm.Parse,ee("BABYLON.CubeTexture",mm);bi.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n";bi.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};\n#include\n";bi.ShadersStore.backgroundPixelShader="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";bi.ShadersStore.backgroundVertexShader="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class gm extends Oa{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class vm extends Ra{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=vm.StandardReflectance0*t,this.reflectionReflectance90=vm.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=vm.StandardReflectance0+(1-vm.StandardReflectance0)*t,this.reflectionReflectance90=vm.StandardReflectance90+(1-vm.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=Ce.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=de.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new ds(16),this._reflectionControls=_e.Zero(),this._white=Ce.White(),this._primaryShadowColor=Ce.Black(),this._primaryHighlightColor=Ce.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new gm);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(Zn(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,no(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&lc.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Un(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&lc.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(n.REFLECTION=!0,n.GAMMAREFLECTION=e.gammaSpace,n.RGBDREFLECTION=e.isRGBD,n.REFLECTIONBLUR=this._reflectionBlur>0,n.LODINREFLECTIONALPHA=e.lodLevelInAlpha,n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Vo.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=e.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Vo.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case Vo.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case Vo.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case Vo.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case Vo.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case Vo.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Vo.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Vo.CUBIC_MODE:case Vo.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTION=!1,n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1}n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),qn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),eo(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),ro(e,n,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(ys.NormalKind)||(e.createNormals(!0),we.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const i=new ja;n.FOG&&i.addFallback(0,"FOG"),n.POINTSIZE&&i.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),Kn(n,i,this._maxSimultaneousLights);const s=[ys.PositionKind];n.NORMAL&&s.push(ys.NormalKind),n.UV1&&s.push(ys.UVKind),n.UV2&&s.push(ys.UV2Kind),Qn(s,e,n,i),jn(s,n);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];An(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];xs&&(xs.PrepareUniforms(a,n),xs.PrepareSamplers(l,n)),co({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});const c=n.toString(),u=r.getEngine().createEffect("background",{attributes:s,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(u,n,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),Wn(t,this._activeEffect);const o=this._mustRebind(s,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(s.texturesEnabled&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Gn(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&lc.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),s.texturesEnabled&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&lc.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),In(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&Yn(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),Nn(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&wn(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return yt.Clone((()=>new vm(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return yt.Parse((()=>new vm(e.name,t)),e,t,i)}}vm.StandardReflectance0=.05,vm.StandardReflectance90=.5,qe([nt()],vm.prototype,"_primaryColor",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],vm.prototype,"primaryColor",void 0),qe([nt()],vm.prototype,"__perceptualColor",void 0),qe([st()],vm.prototype,"_primaryColorShadowLevel",void 0),qe([st()],vm.prototype,"_primaryColorHighlightLevel",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],vm.prototype,"primaryColorHighlightLevel",null),qe([rt()],vm.prototype,"_reflectionTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionTexture",void 0),qe([st()],vm.prototype,"_reflectionBlur",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionBlur",void 0),qe([rt()],vm.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"shadowLights",void 0),qe([st()],vm.prototype,"_shadowLevel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"shadowLevel",void 0),qe([lt()],vm.prototype,"_sceneCenter",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"sceneCenter",void 0),qe([st()],vm.prototype,"_opacityFresnel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"opacityFresnel",void 0),qe([st()],vm.prototype,"_reflectionFresnel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionFresnel",void 0),qe([st()],vm.prototype,"_reflectionFalloffDistance",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionFalloffDistance",void 0),qe([st()],vm.prototype,"_reflectionAmount",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionAmount",void 0),qe([st()],vm.prototype,"_reflectionReflectance0",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionReflectance0",void 0),qe([st()],vm.prototype,"_reflectionReflectance90",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"reflectionReflectance90",void 0),qe([st()],vm.prototype,"_useRGBColor",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"useRGBColor",void 0),qe([st()],vm.prototype,"_enableNoise",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"enableNoise",void 0),qe([st()],vm.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],vm.prototype,"maxSimultaneousLights",void 0),qe([st()],vm.prototype,"_shadowOnly",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],vm.prototype,"shadowOnly",void 0),qe([dt()],vm.prototype,"_imageProcessingConfiguration",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],vm.prototype,"enableGroundProjection",void 0),qe([st()],vm.prototype,"projectedGroundRadius",void 0),qe([st()],vm.prototype,"projectedGroundHeight",void 0),ee("BABYLON.BackgroundMaterial",vm);class xm{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Ce(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Ce(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:de.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...xm._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new X,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new Ee(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof No)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=mm.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new bo("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const s=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Th&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const n=r.length();n>e&&(e=2*n,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=ta("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new vm("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof No?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Vo(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Vo.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new fm("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Vo.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new ir(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new vm("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof No?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new mm(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Vo.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}xm._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",xm._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",xm._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class bm extends xn{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Vo.CLAMP_ADDRESSMODE,this._texture.wrapV=Vo.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Vo.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=bm.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new X,this.onLoadObservable=new X,s=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(s.activeCamera?.48*s.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=Eu(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:bo.BACKSIDE},s);const n=this._material=new vm(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=Eu("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:bo.BACKSIDE},s),this._halfDomeMask.rotate(_r.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&s.activeCamera){const e=s.activeCamera,t=de.Forward(),i=de.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(de.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case bm.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case bm.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let s=i.isRightCamera;this._crossEye&&(s=!s),this._texture.uOffset=s?e:t}));break}case bm.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}bm.MODE_MONOSCOPIC=0,bm.MODE_TOPBOTTOM=1,bm.MODE_SIDEBYSIDE=2;class Tm extends bm{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new Vo(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}Tm.MODE_MONOSCOPIC=bm.MODE_MONOSCOPIC,Tm.MODE_TOPBOTTOM=bm.MODE_TOPBOTTOM,Tm.MODE_SIDEBYSIDE=bm.MODE_SIDEBYSIDE;let ym=0;const Sm=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const s=Vo.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+ym++,e,!0,!1,Vo.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const r=e.getEngine().getLoadedTexturesCache(),n=r.indexOf(s.getInternalTexture());-1!==n&&r.splice(n,1),s.isRGBD=!0,s.wrapU=Vo.CLAMP_ADDRESSMODE,s.wrapV=Vo.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=s,e.useDelayedTextureLoading=t,v_.ExpandRGBDTexture(s);const o=e.getEngine().onContextRestoredObservable.add((()=>{s.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{s.isReady()&&(e.onBeforeRenderObservable.remove(t),v_.ExpandRGBDTexture(s))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture},Cm={GetEnvironmentBRDFTexture:Sm};class Em extends Oa{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class Am extends gc{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new Em,t),this._useEnergyConservation=Am.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Am.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Am.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Am.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Am.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Am.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Am.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Am.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Am.DEFAULT_USE_ENERGY_CONSERVATION=!0,Am.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Am.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Am.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,qe([st(),it("_markAllSubMeshesAsMiscDirty")],Am.prototype,"useEnergyConservation",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Am.prototype,"useSmithVisibilityHeightCorrelated",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Am.prototype,"useSphericalHarmonics",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Am.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);bi.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";bi.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";bi.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";bi.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";bi.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#endif\n";bi.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";bi.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}";bi.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n";bi.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}\n#endif\n#endif\n";bi.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";bi.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";bi.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nfloat cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}Rm._DefaultIndexOfRefraction=1.5,qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"isEnabled",void 0),qe([st()],Rm.prototype,"intensity",void 0),qe([st()],Rm.prototype,"roughness",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"indexOfRefraction",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"texture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"useRoughnessFromMainTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"textureRoughness",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"remapF0OnInterfaceChange",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"bumpTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"isTintEnabled",void 0),qe([nt()],Rm.prototype,"tintColor",void 0),qe([st()],Rm.prototype,"tintColorAtDistance",void 0),qe([st()],Rm.prototype,"tintThickness",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Rm.prototype,"tintTexture",void 0);class Im extends Oa{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class Mm extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new Im,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Mm._DefaultMinimumThickness,this.maximumThickness=Mm._DefaultMaximumThickness,this.indexOfRefraction=Mm._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&lc.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&lc.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lc.IridescenceTextureEnabled?Un(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&lc.IridescenceTextureEnabled?Un(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&lc.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&Gn(this._texture,e,"iridescence"),this._thicknessTexture&&Gn(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&lc.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&lc.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){e&&(this._texture?.dispose(),this._thicknessTexture?.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}Mm._DefaultMinimumThickness=100,Mm._DefaultMaximumThickness=400,Mm._DefaultIndexOfRefraction=1.3,qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"isEnabled",void 0),qe([st()],Mm.prototype,"intensity",void 0),qe([st()],Mm.prototype,"minimumThickness",void 0),qe([st()],Mm.prototype,"maximumThickness",void 0),qe([st()],Mm.prototype,"indexOfRefraction",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"texture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"thicknessTexture",void 0);class Om extends Oa{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Dm extends gc{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new Om,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new ue(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&lc.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(ys.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lc.AnisotropicTextureEnabled?Un(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&lc.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Gn(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&lc.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"isEnabled",void 0),qe([st()],Dm.prototype,"intensity",void 0),qe([at()],Dm.prototype,"direction",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"texture",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Dm.prototype,"legacy",void 0);class wm extends Oa{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class Nm extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new wm,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Ce.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&lc.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&lc.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lc.SheenTextureEnabled?(Un(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&lc.SheenTextureEnabled?Un(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&lc.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&Gn(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Gn(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&lc.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&lc.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"isEnabled",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"linkSheenWithAlbedo",void 0),qe([st()],Nm.prototype,"intensity",void 0),qe([nt()],Nm.prototype,"color",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"texture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"useRoughnessFromMainTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"roughness",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"textureRoughness",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"albedoScaling",void 0);class Fm extends Oa{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class Bm extends gc{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Fm,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Ce.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Ce.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&lc.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&lc.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,void(e.SS_USE_GLTF_TEXTURES=!1);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&lc.ThicknessTextureEnabled&&Un(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&lc.RefractionIntensityTextureEnabled&&Un(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&lc.TranslucencyIntensityTextureEnabled&&Un(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&lc.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(ge.Vector3[0]);const r=Math.max(Math.abs(ge.Vector3[0].x),Math.abs(ge.Vector3[0].y),Math.abs(ge.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,a=r.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&lc.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Gn(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&lc.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Gn(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&lc.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),Gn(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&lc.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,s=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/s,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",i,xe.Log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&lc.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&lc.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&lc.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&lc.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){lc.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e}hasRenderTargetTextures(){return!!(lc.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"}]}}}qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"isRefractionEnabled",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"isTranslucencyEnabled",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"isDispersionEnabled",void 0),qe([st(),it("_markScenePrePassDirty")],Bm.prototype,"isScatteringEnabled",void 0),qe([st()],Bm.prototype,"_scatteringDiffusionProfileIndex",void 0),qe([st()],Bm.prototype,"refractionIntensity",void 0),qe([st()],Bm.prototype,"translucencyIntensity",void 0),qe([st()],Bm.prototype,"useAlbedoToTintRefraction",void 0),qe([st()],Bm.prototype,"useAlbedoToTintTranslucency",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"thicknessTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"refractionTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"indexOfRefraction",void 0),qe([st()],Bm.prototype,"_volumeIndexOfRefraction",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"volumeIndexOfRefraction",null),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"invertRefractionY",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"linkRefractionWithTransparency",void 0),qe([st()],Bm.prototype,"minimumThickness",void 0),qe([st()],Bm.prototype,"maximumThickness",void 0),qe([st()],Bm.prototype,"useThicknessAsDepth",void 0),qe([nt()],Bm.prototype,"tintColor",void 0),qe([st()],Bm.prototype,"tintColorAtDistance",void 0),qe([st()],Bm.prototype,"dispersion",void 0),qe([nt()],Bm.prototype,"diffusionDistance",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"useMaskFromThicknessTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"refractionIntensityTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"translucencyIntensityTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Bm.prototype,"useGltfStyleTextures",void 0);const Lm={effect:null,subMesh:null};class km extends Oa{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Vm extends Ra{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new _e(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Vm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=Ce.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Ce(0,0,0),this._albedoColor=new Ce(1,1,1),this._reflectivityColor=new Ce(1,1,1),this._reflectionColor=new Ce(1,1,1),this._emissiveColor=new Ce(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=Vm.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new ds(16),this._globalAmbientColor=new Ce(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Am(this),this.clearCoat=new Rm(this),this.iridescence=new Mm(this),this.anisotropy=new Dm(this),this.sheen=new Nm(this),this.subSurface=new Bm(this),this.detailMap=new xc(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),lc.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Sm(this.getScene()),this.prePassConfiguration=new ac}get hasRenderTargetTextures(){return!!(lc.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Vm.PBRMATERIAL_OPAQUE||this._transparencyMode===Vm.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Vm.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Vm.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(En.GetDefineNames,this._eventInfo),t.materialDefines=new km(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&lc.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&lc.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&lc.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&lc.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&lc.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&lc.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(lc.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&lc.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&lc.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(ys.NormalKind)||(e.createNormals(!0),we.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=r._areLightsDisposed;let h=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(Lm.effect=h,Lm.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Lm)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,r.markAsUnprocessed(),c=this.isFrozen,l)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,r,this._materialContext);return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!c,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new ja;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=Kn(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[ys.PositionKind];t.NORMAL&&c.push(ys.NormalKind),t.TANGENT&&c.push(ys.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(ys.ColorKind),Qn(c,e,t,l),jn(c,t),Bn(c,e,t),zn(c,0,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],p=["Material","Scene","Mesh"],f={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=p,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=f,this._callbackPluginEventGeneric(En.PrepareEffect,this._eventInfo),ac.AddUniforms(d),ac.AddSamplers(_),An(d),xs&&(xs.PrepareUniforms(d,t),xs.PrepareSamplers(_,t)),co({uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const m={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,p,_,t,c,m));const g=t.toString(),v=a.createEffect(u,{attributes:c,uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:g,fallbacks:l,onCompiled:i,onError:s,indexParameters:f,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,v}_prepareDefines(e,t,i=null,s=null,r=!1){const n=this.getScene(),o=n.getEngine();Zn(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,no(n,t);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(ao(n,t,this.canRenderToMRT&&!a),oo(n,t,a),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&lc.DiffuseTextureEnabled?(Un(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&lc.AmbientTextureEnabled?(Un(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&lc.OpacityTextureEnabled?(Un(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&lc.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Vo.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case Vo.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Vo.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Vo.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Vo.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Vo.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Vo.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Vo.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Vo.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Vo.CUBIC_MODE:case Vo.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Vo.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&lc.LightmapTextureEnabled?(Un(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&lc.EmissiveTextureEnabled?(Un(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,lc.SpecularTextureEnabled?(this._metallicTexture?(Un(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(Un(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(Un(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(Un(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?Un(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&lc.BumpTextureEnabled&&!this._disableBumpMap?(Un(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&lc.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&lc.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===Vm.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Vm.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(ys.NormalKind),t.DEBUGMODE=this._debugMode),eo(n,o,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ro(e,t,!0,!0,!0,this._transparencyMode!==Vm.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(En.GetDefineNames,this._eventInfo);const r=new km(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Lm.effect=n,Lm.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Lm)),n.isReady()?t&&t(this):n.onCompileObservable.add((()=>{t&&t(this)}))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=s.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const a=this._mustRebind(s,n,i,t.visibility);Wn(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(a){if(this.bindViewProjection(n),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&lc.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Gn(this._albedoTexture,h,"albedo")),this._ambientTexture&&lc.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Gn(this._ambientTexture,h,"ambient")),this._opacityTexture&&lc.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Gn(this._opacityTexture,h,"opacity")),l&&lc.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,xe.Log2(e))}if(!r.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&e)if(r.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&lc.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Gn(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&lc.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Gn(this._lightmapTexture,h,"lightmap")),lc.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Gn(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Gn(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Gn(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Gn(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Gn(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&lc.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Gn(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){Ae.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,Ae.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",Ae.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,Ae.Color3[0]);const s=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",Ae.Color3[0],s)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",lc.EmissiveTextureEnabled?this._emissiveColor:Ce.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&lc.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&lc.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&lc.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&lc.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),r.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),r.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&lc.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&lc.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),lc.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&lc.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),In(this._activeEffect,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!a&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&Yn(s,t,this._activeEffect,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Nn(s,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&kn(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),wn(r,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e}setPrePassRenderer(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Vm.PBRMATERIAL_OPAQUE=uo.MATERIAL_OPAQUE,Vm.PBRMATERIAL_ALPHATEST=uo.MATERIAL_ALPHATEST,Vm.PBRMATERIAL_ALPHABLEND=uo.MATERIAL_ALPHABLEND,Vm.PBRMATERIAL_ALPHATESTANDBLEND=uo.MATERIAL_ALPHATESTANDBLEND,Vm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Vm.LIGHTFALLOFF_PHYSICAL=0,Vm.LIGHTFALLOFF_GLTF=1,Vm.LIGHTFALLOFF_STANDARD=2,qe([dt()],Vm.prototype,"_imageProcessingConfiguration",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],Vm.prototype,"debugMode",void 0);class Um extends Vm{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Vm.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Vm.LIGHTFALLOFF_PHYSICAL:Vm.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Vm.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Vm.LIGHTFALLOFF_GLTF:Vm.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=Um.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Ce.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Ce(0,0,0),this.albedoColor=new Ce(1,1,1),this.reflectivityColor=new Ce(1,1,1),this.reflectionColor=new Ce(1,1,1),this.emissiveColor=new Ce(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=Sm(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=yt.Clone((()=>new Um(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=yt.Parse((()=>new Um(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),uo._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}Um.PBRMATERIAL_OPAQUE=Vm.PBRMATERIAL_OPAQUE,Um.PBRMATERIAL_ALPHATEST=Vm.PBRMATERIAL_ALPHATEST,Um.PBRMATERIAL_ALPHABLEND=Vm.PBRMATERIAL_ALPHABLEND,Um.PBRMATERIAL_ALPHATESTANDBLEND=Vm.PBRMATERIAL_ALPHATESTANDBLEND,Um.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Vm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"directIntensity",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"emissiveIntensity",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"environmentIntensity",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"specularIntensity",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"disableBumpMap",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"albedoTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"ambientTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"ambientTextureStrength",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesAndMiscDirty")],Um.prototype,"opacityTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectionTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"emissiveTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectivityTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallicTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallic",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"roughness",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallicF0Factor",void 0),qe([nt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallicReflectanceColor",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"metallicReflectanceTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectanceTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"microSurfaceTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"bumpTexture",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty",null)],Um.prototype,"lightmapTexture",void 0),qe([nt("ambient"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"ambientColor",void 0),qe([nt("albedo"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"albedoColor",void 0),qe([nt("reflectivity"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectivityColor",void 0),qe([nt("reflection"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"reflectionColor",void 0),qe([nt("emissive"),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"emissiveColor",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"microSurface",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useLightmapAsShadowmap",void 0),qe([st(),it("_markAllSubMeshesAsTexturesAndMiscDirty")],Um.prototype,"useAlphaFromAlbedoTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesAndMiscDirty")],Um.prototype,"forceAlphaTest",void 0),qe([st(),it("_markAllSubMeshesAsTexturesAndMiscDirty")],Um.prototype,"alphaCutOff",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useSpecularOverAlpha",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useRoughnessFromMetallicTextureGreen",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useMetallnessFromMetallicTextureBlue",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useAmbientInGrayScale",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),qe([st()],Um.prototype,"usePhysicalLightFalloff",null),qe([st()],Um.prototype,"useGLTFLightFalloff",null),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useRadianceOverAlpha",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useObjectSpaceNormalMap",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useParallax",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useParallaxOcclusion",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"parallaxScaleBias",void 0),qe([st(),it("_markAllSubMeshesAsLightsDirty")],Um.prototype,"disableLighting",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"forceIrradianceInFragment",void 0),qe([st(),it("_markAllSubMeshesAsLightsDirty")],Um.prototype,"maxSimultaneousLights",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"invertNormalMapX",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"invertNormalMapY",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"twoSidedLighting",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useAlphaFresnel",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useLinearAlphaFresnel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"environmentBRDFTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"forceNormalForward",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"enableSpecularAntiAliasing",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useHorizonOcclusion",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Um.prototype,"useRadianceOcclusion",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Um.prototype,"unlit",void 0),qe([st(),it("_markAllSubMeshesAsMiscDirty")],Um.prototype,"applyDecalMapAfterDetailMap",void 0),ee("BABYLON.PBRMaterial",Um);const Gm=131072,zm=131072;function Wm(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const Hm=Wm("DXT1"),Xm=Wm("DXT3"),Ym=Wm("DXT5"),Qm=Wm("DX10");class jm{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let s=1;t[2]&Gm&&(s=Math.max(1,t[7]));const r=t[21],n=r===Qm?i[32]:0;let o=0;switch(r){case 113:o=2;break;case 116:o=1;break;case Qm:if(10===n){o=2;break}if(2===n){o=1;break}}return{width:t[4],height:t[3],mipmapCount:s,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&zm)===zm,isCube:!(512&~t[28]),isCompressed:r===Hm||r===Xm||r===Ym,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),a=new Uint16Array(r,i);let l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,a){const l=new Uint8Array(s),h=new Uint8Array(r,i);let c=0;for(let i=0;i>8&255,C>>16&255,C>>24&255))])}var C;const E=jm._ExtractLongWordOrder(u[23]),A=jm._ExtractLongWordOrder(u[24]),P=jm._ExtractLongWordOrder(u[25]),R=jm._ExtractLongWordOrder(u[26]);S&&(b=e._getRGBABufferInternalSizedFormat(s.textureType)),g=1,u[2]&Gm&&!1!==r&&(g=Math.max(1,u[7]));const I=a||0,M=e.getCaps();for(let r=I;r0?s.sphericalPolynomial=b_.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}jm.StoreLODInAlphaChannel=!1,ki.prototype.createPrefilteredCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new l_,n._source=Ai.CubePrefiltered,this.getCaps().textureLOD)return void(r&&r(n));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let r=0;r<3;r++){const l=1-r/2,c=s,u=xe.Log2(a)*i+s,d=c+(u-c)*l,_=Math.round(Math.min(Math.max(d,0),u)),p=new Pi(this,Ai.Temp);if(p.type=n.type,p.format=n.format,p.width=Math.pow(2,Math.max(xe.Log2(a)-_,0)),p.height=p.width,p.isCube=!0,p._cachedWrapU=0,p._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,p,!0),p.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),jm.UploadDDSLevels(this,p,i,t,!0,6,_)}else we.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const f=new No(t);f._isCube=!0,f._texture=p,p.isReady=!0,h.push(f)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],r&&r(n)}),n,o,a,l,i,s)};class Km{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,s){const r=t.getEngine();let n,o=!1,a=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),jm.UploadDDSLevels(r,t,s,n,o,6,-1,i),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t)}else{const s=e;n=jm.GetDDSInfo(s),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new l_),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),jm.UploadDDSLevels(r,t,s,n,o,6),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t,!1)}r._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=jm.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1==1;i(s.width,s.height,r,s.isFourCC,(()=>{jm.UploadDDSLevels(t.getEngine(),t,e,s,r,1)}))}}gn._TextureLoaders.push(new Km);class $m{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=C_(e);if(n){t.width=n.width,t.height=n.width;try{D_(t,n),I_(t,e,n).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{r?.("Can not upload environment levels",e)}))}catch(e){r?.("Can not upload environment file",e)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}gn._TextureLoaders.push(new $m);class qm{constructor(e,t){if(this.data=e,this.isInvalid=!1,!qm.IsValid(e))return this.isInvalid=!0,void we.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),r=67305985===s.getUint32(0,!0);return this.glType=s.getUint32(1*i,r),this.glTypeSize=s.getUint32(2*i,r),this.glFormat=s.getUint32(3*i,r),this.glInternalFormat=s.getUint32(4*i,r),this.glBaseInternalFormat=s.getUint32(5*i,r),this.pixelWidth=s.getUint32(6*i,r),this.pixelHeight=s.getUint32(7*i,r),this.pixelDepth=s.getUint32(8*i,r),this.numberOfArrayElements=s.getUint32(9*i,r),this.numberOfFaces=s.getUint32(10*i,r),this.numberOfMipmapLevels=s.getUint32(11*i,r),this.bytesOfKeyValueData=s.getUint32(12*i,r),0!==this.glType?(we.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(we.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(we.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(we.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=qm.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case qm.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case qm.TEX_2D:case qm.COMPRESSED_3D:case qm.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=qm.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}qm.HEADER_LEN=64,qm.COMPRESSED_2D=0,qm.COMPRESSED_3D=1,qm.TEX_2D=2,qm.TEX_3D=3;class Zm{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((i=>{t(i,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class Jm extends Zm{constructor(e,t,i=Jm.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{s(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}var eg,tg,ig;function sg(e,t){const i=t?.jsDecoderModule||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function rg(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const s=i.data.urls;s&&(s.jsDecoderModule&&void 0===e&&(importScripts(s.jsDecoderModule),e=KTX2DECODER),sg(s)),i.data.wasmBinaries&&sg(void 0,{...i.data.wasmBinaries,jsDecoderModule:e}),t=new e.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}Jm.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(eg||(eg={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(tg||(tg={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(ig||(ig={}));class ng{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[tg.BC1_RGB,tg.BC3_RGBA],yes:{transcodeFormat:tg.RGBA32,engineFormat:ig.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class og{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(og._WorkerPoolPromise||og._DecoderModulePromise)return;const t={jsDecoderModule:hs.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:hs.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:hs.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:hs.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:hs.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?og._WorkerPoolPromise=new Promise((i=>{const s=`${sg}(${rg})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new Jm(e,(()=>function(e,t,i){return new Promise(((t,s)=>{const r=t=>{e.removeEventListener("error",r),e.removeEventListener("message",n),s(t)},n=i=>{"init"===i.data.action&&(e.removeEventListener("error",r),e.removeEventListener("message",n),t(e))};e.addEventListener("error",r),e.addEventListener("message",n),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(r),0,t))))})):void 0===og._KTX2DecoderModule?og._DecoderModulePromise=hs.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(og._KTX2DecoderModule=KTX2DECODER,og._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,og._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,sg(t,og._KTX2DecoderModule),new og._KTX2DecoderModule.KTX2Decoder))):(og._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,og._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,og._DecoderModulePromise=Promise.resolve(new og._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=og.DefaultNumWorkers){if(this._engine=e,"object"==typeof t&&t.workerPool)og._WorkerPoolPromise=Promise.resolve(t.workerPool);else{"object"==typeof t?og._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(og._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??og.DefaultNumWorkers;og._Initialize(e)}}_uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(og._WorkerPoolPromise)return og._WorkerPoolPromise.then((s=>new Promise(((n,o)=>{s.push(((s,a)=>{const l=e=>{s.removeEventListener("error",l),s.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(s.removeEventListener("error",l),s.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};s.addEventListener("error",l),s.addEventListener("message",h),s.postMessage({action:"setDefaultDecoderOptions",options:og.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),s.postMessage({action:"decode",data:c,caps:r,options:i},[c.buffer])}))}))));if(og._DecoderModulePromise)return og._DecoderModulePromise.then((i=>(og.DefaultDecoderOptions.isDirty&&(og._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=og.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((r,n)=>{i.decode(e,s).then((e=>{this._createTexture(e,t),r()})).catch((e=>{n({message:e})}))})))));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}og.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},og.DefaultNumWorkers=og.GetDefaultNumWorkers(),og.DefaultDecoderOptions=new ng;class ag{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new qm(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(qm.IsValid(e)){t._invertVScale=!t.invertY;const s=new qm(e,1),r=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(s.glInternalFormat);r?(t.format=r,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,(()=>{s.uploadLevels(t,t.generateMipMaps)}),s.isInvalid)}else og.IsValid(e)?new og(t.getEngine())._uploadAsync(e,t,s).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{we.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(we.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}}gn._TextureLoaders.unshift(new ag);class lg extends xh{constructor(e,t,i){super(e,de.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=pe.Identity(),this._referencedPosition=new de,this._trackingState=Fc.NOT_TRACKING,this.onXRCameraInitializedObservable=new X,this.onBeforeCameraTeleport=new X,this.onAfterCameraTeleport=new X,this.onTrackingStateChanged=new X,this.compensateOnFirstFrame=!0,this._rotate180=new pe(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new pe,this.cameraRigMode=Kr.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add((()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()}))})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new jr(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new jr(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,pe.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=ge.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),pe.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(Fc.NOT_TRACKING);const t=e.emulatedPosition?Fc.TRACKING_LOST:Fc.TRACKING;if(this._setTrackingState(t),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{const i=this.rigCameras[t];i.isLeftCamera||i.isRightCamera||("right"===e.eye?i._isRightCamera=!0:"left"===e.eye&&(i._isLeftCamera=!0));const s=this.getScene().customRenderTargets;for(let e=0;ee;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=ge.Matrix[0],t=ge.Matrix[1],i=ge.Matrix[2];fe.ComposeToRef(lg._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),fe.ComposeToRef(lg._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const s=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}lg._ScaleReadOnly=de.One();class hg{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new X,this.onStateChangedObservable=new X,this.state=Nc.NOT_IN_XR,this.sessionManager=new wc(e),this.camera=new lg("webxr",e,this.sessionManager),this.featuresManager=new ca(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new hg(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(Nc.NOT_IN_XR),t.dispose(),e}))}dispose(){this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._spectatorCamera?.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Nc.ENTERING_XR),"viewer"!==t&&"local"!==t&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),"immersive-ar"===e&&"unbounded"!==t&&we.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const r={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(ha.LAYERS)){const e=await i.initializeXRLayerAsync(this.sessionManager.session);r.baseLayer=e}return this.sessionManager.updateRenderState(r),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!this._nonVRCamera?.inputs?.attachedToElement,this._nonVRCamera?.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==Nc.EXITING_XR&&this._setState(Nc.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(Nc.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(Nc.IN_XR)})),this.sessionManager}catch(e){throw we.Log(e),we.Log(e.message),this._setState(Nc.NOT_IN_XR),e}}exitXRAsync(){return this.state!==Nc.IN_XR?Promise.resolve():(this._setState(Nc.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/(e?.fps?e.fps:1e3)*1e3,i=e?.preferredCameraIndex?e?.preferredCameraIndex:0,s=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===Nc.IN_XR?(this._spectatorCamera=new Dh("webxr-spectator",de.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new pe,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===Nc.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class cg{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new X,this.onButtonStateChangedObservable=new X}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}cg.BUTTON_TYPE="button",cg.SQUEEZE_TYPE="squeeze",cg.THUMBSTICK_TYPE="thumbstick",cg.TOUCHPAD_TYPE="touchpad",cg.TRIGGER_TYPE="trigger";class ug{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,s=t.gamepadIndices.button,r=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&r.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new cg(e,i,s,r)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new X,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?we.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,s)=>{const r=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void r(e[0].meshes)}Pa.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),r(e)}),null,((e,i)=>{we.Log(i),we.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const s=i?.5*t+.5:t;pe.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),de.LerpToRef(e.minMesh.position,e.maxMesh.position,s,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=pe.FromEulerAngles(0,Math.PI,0)}}class dg extends ug{constructor(e,t,i){super(e,_g[i],t,i),this.profileId=dg.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=pe.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}dg.ProfileId="generic-trigger";const _g={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class pg extends ug{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=Pa.IsPluginForExtensionAvailable(".glb");return e||we.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const s=t.visualResponses[i];if("transform"===s.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s.valueNodeName),minMesh:this._getChildByName(this.rootMesh,s.minNodeName),maxMesh:this._getChildByName(this.rootMesh,s.maxNodeName)};else{const r=t.type===cg.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:s.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r)},t.type===cg.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=Eu(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new yc(i+"mat",this.scene),t.material.diffuseColor=Ce.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new bo(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],s=this.layout.components[e];Object.keys(s.visualResponses).forEach((e=>{const r=s.visualResponses[e];let n=t.value;if("xAxis"===r.componentProperty?n=t.axes.x:"yAxis"===r.componentProperty&&(n=t.axes.y),"transform"===r.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==r.componentProperty);else{const s=i.states[e].valueMesh;s&&(s.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const fg=[];class mg{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const s=[];i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&s.push("oculus-touch-v2");const r=s.indexOf("windows-mixed-reality");if(-1!==r&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,r=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,s,e,t).catch((()=>r.call(this,s,e,t)))}return this._LoadProfilesFromAvailableControllers(s,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=hs.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e))),this._ProfilesList}static ClearControllerCache(){fg.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),fg.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=hs.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new pg(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:fg)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew dg(t,e.gamepad,e.handedness))),mg.DefaultFallbacks();let gg=0;class vg{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new de,this._disposed=!1,this.onDisposeObservable=new X,this.onMeshLoadedObservable=new X,this.onMotionControllerInitObservable=new X,this._uniqueId=`controller-${gg++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Sn(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new pe,this.inputSource.gripSpace&&(this.grip=new Sn(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new pe),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&mg.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&this.motionController?.dispose()}))}),(()=>{hs.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;de.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,s){const r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){const e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor);const t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(s.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(s.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class xg{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new X,this.onControllerRemovedObservable=new X,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(mg.BaseRepositoryUrl=this._options.customControllersRepositoryURL),mg.UseOnlineRepository=!this._options.disableOnlineControllerRepository,mg.UseOnlineRepository)try{mg.UpdateProfilesList().catch((()=>{mg.UseOnlineRepository=!1}))}catch(e){mg.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new vg(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const s=[],r=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?s.push(e):r.push(e)})),this.controllers=s,r.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),mg.ClearControllerCache()}}class bg extends ua{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Zo(new de,new de),disabledByNearInteraction:!1,id:bg._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":case"transient-pointer":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new de,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Ce(.9,.9,.9),this.laserPointerDefaultColor=new Ce(.7,.7,.7),this.selectionMeshDefaultColor=new Ce(.8,.8,.8),this.selectionMeshPickedColor=new Ce(.3,.3,1),this._identityMatrix=fe.Identity(),this._screenCoordinatesRef=de.Zero(),this._viewportRef=new jr(0,0,0,0),this._scene=this._xrSessionManager.scene,void 0===this._options.lookAndPickMode&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)}),!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Zo(new de,new de),disabledByNearInteraction:!1,id:bg._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(this._options.lookAndPickMode&&"transient-pointer"!==t.xrController?.inputSource.targetRayMode)return;if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=this._options.forceGripIfAvailable&&t.xrController.grip?t.xrController.grip.position:t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay,this._options.forceGripIfAvailable);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,s=this._options.xrInput.xrCamera;s&&(s.viewport.toGlobalToRef(e.getEngine().getRenderWidth()/s.rigCameras.length,e.getEngine().getRenderHeight(),this._viewportRef),de.ProjectToRef(i,this._identityMatrix,s.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||this._screenCoordinatesRef.x===1/0||this._screenCoordinatesRef.y===1/0||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let s=null;this._utilityLayerScene&&(s=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const r=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);s&&s.hit?r&&r.hit?s.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{const e=1-o/i;n.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),r=t.pick}})),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const s=s=>{this._options.overrideButtonId&&(t.selectionComponent=s.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=s.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((s=>{if(s.changes.pressed){const r=s.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),r?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor));else if(r&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const t=this._controllers[this._attachedController];t&&t.pointerDownTriggered&&!t.finalPointerUpTriggered&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(new Ss,{pointerId:t.id,pointerType:"xr"}),t.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}}))};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const e=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)}))},s=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)}))};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(de.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new Ss,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){hs.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():lu("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new yc("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():Xc("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new yc("targetMat",t);return n.specularColor=Ce.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;e.pickedPoint?.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}var Tg,yg,Sg;bg._IdCounter=200,bg.Name=ha.POINTER_SELECTION,bg.Version=1,ca.AddWebXRFeature(bg.Name,((e,t)=>()=>new bg(e,t)),bg.Version,!0),ln.prototype._projectOnTrianglesToRef=function(e,t,i,s,r,n){const o=ge.Vector3[0],a=ge.Vector3[1];let l=1/0;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh(),r=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s,currentAnimationState:Tg.DEHYDRATED,grabRay:new Zo(new de,new de),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:Cg._IdCounter++,pickedPointVisualCue:r},this._controllers[e.uniqueId]._worldScaleObserver=this._controllers[e.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add((t=>{if(t.newScaleFactor!==t.previousScaleFactor){this._controllers[e.uniqueId].touchCollisionMesh.dispose(),this._controllers[e.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh();this._controllers[e.uniqueId].touchCollisionMesh=t,this._controllers[e.uniqueId].touchCollisionMeshFunction=i,this._controllers[e.uniqueId].hydrateCollisionMeshFunction=s,this._controllers[e.uniqueId].pickedPointVisualCue=this._generateVisualCue()}})),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new Ce(.8,.8,.8),this.selectionMeshPickedColor=new Ce(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=yg.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case Tg.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===Tg.HOVER)break;case Tg.HOVER:if(e.touchCollisionMeshFunction(!0),t===Tg.TOUCH)break}else switch(e.currentAnimationState){case Tg.TOUCH:if(e.touchCollisionMeshFunction(!1),t===Tg.HOVER)break;case Tg.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===Tg.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(ge.Vector3[0]),s.grabRay.direction.copyFrom(ge.Vector3[0]),this._options.nearInteractionControllerMode!==yg.CENTERED_IN_FRONT||s.xrController?.inputSource.hand||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{const i=this._controllers[t],s=i.xrController?.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!s&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad))return void(i.pick=null);if(i.hoverInteraction=!1,i.nearInteraction=!1,!i.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const s=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(s&&s.transform){const e=this._scene.useRightHandedSystem?1:-1;ge.Vector3[0].set(s.transform.position.x,s.transform.position.y,s.transform.position.z*e),ge.Quaternion[0].set(s.transform.orientation.x,s.transform.orientation.y,s.transform.orientation.z*e,s.transform.orientation.w*e),this._processTouchPoint(t,ge.Vector3[0],ge.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==yg.DISABLED){let e=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===yg.CENTERED_ON_CONTROLLER&&(e=i.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new Ss,i=!1;const s=e&&e.pickedPoint&&e.hit;return e?.pickedPoint&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),s&&!i&&(t=e),t};if(!i.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const o=r(this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(o&&o.hit&&(e=n(o),e.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let t=null;const o=(s?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,o,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const a=n(r(this._pickWithSphere(i,o,this._scene,(e=>this._nearPickPredicate(e))),t));a.hit&&(e=a,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=e,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=Tg.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=Tg.TOUCH:i.hoverInteraction&&(o=Tg.HOVER),this._handleTransitionAnimation(i,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Eu("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=pe.Identity();const i=new yc("targetMat",e);return i.specularColor=Ce.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))}));const s=s=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),s&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!s&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!s||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},s=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{if(!t.downTriggered)return;const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new Ss,e)})),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._scene,i=Eu("PickSphere",{diameter:1*e},t);i.isVisible=!1,this._options.motionControllerOrbMaterial?i.material=this._options.motionControllerOrbMaterial:Tl.ParseFromSnippetAsync("8RUNKL#3",t).then((e=>{i.material=e}));const s=new Or;s.setEasingMode(Sr.EASINGMODE_EASEINOUT);const r=new de(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new de(n,n,n).scaleInPlace(e),a=this._controllerPickRadius*(7/6),l=new de(a,a,a).scaleInPlace(e),h=.8*this._controllerPickRadius,c=new de(h,h,h).scaleInPlace(e),u=1.5*this._controllerPickRadius,d=[{frame:0,value:r},{frame:10,value:new de(u,u,u).scaleInPlace(e)},{frame:18,value:o}],_=[{frame:0,value:o},{frame:10,value:c},{frame:18,value:r}],p=[{frame:0,value:de.ZeroReadOnly},{frame:12,value:l},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:de.ZeroReadOnly},{frame:15,value:de.ZeroReadOnly}],m=new Nt("touch","scaling",60,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT),g=new Nt("release","scaling",60,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT),v=new Nt("hydrate","scaling",60,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT),x=new Nt("dehydrate","scaling",60,Nt.ANIMATIONTYPE_VECTOR3,Nt.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(s),g.setEasingFunction(s),v.setEasingFunction(s),x.setEasingFunction(s),m.setKeys(d),g.setKeys(_),v.setKeys(p),x.setKeys(f),{touchCollisionMesh:i,touchCollisionMeshFunction:e=>{const s=e?m:g;t.beginDirectAnimation(i,[s],0,18,!1,1)},hydrateCollisionMeshFunction:e=>{const s=e?v:x;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[s],0,15,!1,1,(()=>{e||(i.isVisible=!1)}))}}}_pickWithSphere(e,t,i,s){const r=new Ss;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=Zr.CreateFromCenterAndRadius(n,t);for(let t=0;tc&&(h=0,a.copyFrom(t.center)),-1!==h&&h<_&&(_=h,Zo.CreateFromToToRef(t.center,a,l),l.length=2*_,d=l.intersectsMesh(e),o.copyFrom(a));return _()=>new Cg(e,t)),Cg.Version,!0);class Eg{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Ag{}class Pg{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new X,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw hs.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let s=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const r=document.createElement("style");r.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(r);const n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new Eg(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==Nc.NOT_IN_XR&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):hs.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const s=new Pg(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Nc.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Nc.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,s=i.title;i.title="Error entering XR session : "+s,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function Rg(e){let t=0;const i=Date.now();e.observableParameters=e.observableParameters??{};const s=e.contextObservable.add((r=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/e.timeout,payload:r};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),t>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(Sg||(Sg={}));class Ig{constructor(e){this.onEachCountObservable=new X,this.onTimerAbortedObservable=new X,this.onTimerEndedObservable=new X,this.onStateChangedObservable=new X,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},s=this._breakOnNextTick||this._breakCondition(i);s||this._timer>=this._timeToEnd?this._stop(i,s):this.onEachCountObservable.notifyObservers(i)},this._setState(Sg.INIT),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===Sg.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(Sg.STARTED)}stop(){this._state===Sg.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(Sg.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Mg extends ua{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new Ee(1,1,1,1),this._tmpRay=new Zo(new de,new de),this._tmpVector=new de,this._tmpQuaternion=new pe,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new X,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new X,this.onAfterCameraTeleportRotation=new X,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(cg.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(cg.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(!this.teleportationEnabled)return;const s=()=>{t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,Rg({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};i.changes.pressed&&(i.changes.pressed.current?this._options.timeToTeleportStart?Rg({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{i.pressed&&s()}}):s():(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,pe.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),pe.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else{t.teleportationState.mainComponentUsed=!0;let i=!1;const s=()=>{this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,Rg({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add((e=>{e.type===Ms.POINTERDOWN?(i=!1,this._options.timeToTeleportStart?Rg({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&s()},breakCondition:()=>!!i&&(i=!1,!0)}):s()):e.type===Ms.POINTERUP&&(i=!0,t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Ee(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add((e=>{this.parabolicCheckRadius=this.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,this._options.teleportationTargetMesh?.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor)}))}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(e))return!0;if(this._options.blockAllPickableMeshes&&e.isPickable)return!0;if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.blockerMeshesPredicate||!this._options.blockerMeshesPredicate(e))||!(!this._options.blockAllPickableMeshes||!e.isPickable)||!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e))),l=a&&a.pickedMesh&&-1!==this._floorMeshes.indexOf(a.pickedMesh);if(a&&a.pickedMesh&&!l)return e.teleportationState.mainComponentUsed&&!e.teleportationState.initialHit?void(e.teleportationState.forward=!1):(e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,r),void this._showParabolicPath(a));a&&a.pickedPoint&&(e.teleportationState.initialHit=!0,e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0,!1,r),this._showParabolicPath(a))}this._setTargetMeshVisibility(t,!1,r)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Uc("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,s=new Sc("teleportationPlaneDynamicTexture",i,e,!0);s.hasAlpha=!0;const r=s.getContext(),n=i/2,o=i/2,a=200;r.beginPath(),r.arc(n,o,a,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),s.update();const l=new yc("teleportationPlaneMaterial",e);l.diffuseTexture=s,t.material=l}const i=Xc("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new Nt("animationInnerCircle","position.y",30,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),t.setKeys(s);const r=new Nr;r.setEasingMode(Sr.EASINGMODE_EASEINOUT),t.setEasingFunction(r),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const s=lu("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(_r.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new yc("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new Ce(.3,.3,1):t.diffuseColor=new Ce(.3,.3,1),t.alpha=.9,i.material=t,s.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach((t=>{const n=de.DistanceSquared(t,e);n<=r&&n{t.isVisible=e})),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||uu.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=yr.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(r||this._cachedColor4White),o=s.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=Zu("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,pe.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}Mg.Name=ha.TELEPORTATION,Mg.Version=1,ca.AddWebXRFeature(Mg.Name,((e,t)=>()=>new Mg(e,t)),Mg.Version,!0);class Og{}class Dg{constructor(){}static CreateAsync(e,t={}){const i=new Dg;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const s={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Pg(e,s)}return hg.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new xg(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(bg.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Mg.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(Cg.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(Ml.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(we.Error("Error initializing XR"),we.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var wg=!0;function Ng(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}dr.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),s=t.max.subtract(t.min),r=t.min.add(s.scale(.5));let n,o=1.5*s.length();if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),e){const e=new Th("default camera",-Math.PI/2,Math.PI/2,o,r,this);e.lowerRadiusLimit=.01*o,e.wheelPrecision=100/o,n=e}else{const e=new xh("default camera",new de(r.x,r.y,-o),this);e.setTarget(r),n=e}n.minZ=.01*o,n.maxZ=1e3*o,n.speed=.2*o,this.activeCamera=n,i&&n.attachControl()}},dr.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},dr.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,s=0,r=!0){if(!e)return we.Warn("Can not create default skybox without environment texture."),null;r&&e&&(this.environmentTexture=e);const n=yu("hdrSkyBox",{size:i},this);if(t){const t=new Um("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Vo.SKYBOX_MODE),t.microSurface=1-s,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{const t=new yc("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Vo.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},dr.prototype.createDefaultEnvironment=function(e){return xm?new xm(e,this):null},dr.prototype.createDefaultVRExperience=function(e={}){return new $c(this,e)},dr.prototype.createDefaultXRExperienceAsync=function(e={}){return Dg.CreateAsync(this,e).then((e=>e))};class Fg extends Vo{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new X),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):we.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===e?.name){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return we.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,s=!1,r=!1,n=Vo.TRILINEAR_SAMPLINGMODE,o={},a,l=5){super(null,i,!s,r),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||hs.IsExponentOfTwo(this.video.videoWidth)&&hs.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Vo.WRAP_ADDRESSMODE,this.wrapV=Vo.WRAP_ADDRESSMODE):(this.wrapU=Vo.CLAMP_ADDRESSMODE,this.wrapV=Vo.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&h?h&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return hs.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(hs.SetCorsBehavior(e,t),t.src=e):(hs.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Ng(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new Fg(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),this._externalTexture?.dispose()}static CreateFromStreamAsync(e,t,i,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(void 0!==r.mozSrcObject?r.mozSrcObject=t:"object"==typeof r.srcObject?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const n=new Fg("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce((()=>{r.remove()})),n.onDisposeObservable.addOnce((()=>{Ng(r)})),t(n),r.removeEventListener("playing",i)};r.addEventListener("playing",i),r.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce((()=>{r.getTracks().forEach((e=>{e.stop()}))})),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then((function(e){t&&t(e)})).catch((function(e){we.Error(e.name)}))}}qe([st("settings")],Fg.prototype,"_settings",void 0),qe([st("src")],Fg.prototype,"_currentSrc",void 0),qe([st()],Fg.prototype,"isVideo",void 0),Vo._CreateVideoTexture=(e,t,i,s=!1,r=!1,n=Vo.TRILINEAR_SAMPLINGMODE,o={},a,l=5)=>new Fg(e,t,i,s,r,n,o,a,l),ee("BABYLON.VideoTexture",Fg);class Bg extends bm{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new Fg((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Vo.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{e.pickInfo?.pickedMesh===this.mesh&&this._texture.video.play()}),Ms.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}Bg.MODE_MONOSCOPIC=bm.MODE_MONOSCOPIC,Bg.MODE_TOPBOTTOM=bm.MODE_TOPBOTTOM,Bg.MODE_SIDEBYSIDE=bm.MODE_SIDEBYSIDE;class Lg{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((()=>{this._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new tr,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class kg{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((()=>{hs.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((()=>{hs.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring(!1)}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((()=>{hs.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((()=>{hs.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((()=>{hs.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((()=>{hs.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((()=>{hs.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((()=>{hs.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((()=>{hs.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((()=>{hs.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((()=>{this._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((()=>{this._renderTime.beginMonitoring(),hs.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((()=>{this._renderTime.endMonitoring(!1),hs.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((e=>{this._cameraRenderTime.beginMonitoring(),hs.StartPerformanceCounter(`Rendering camera ${e.name}`)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((e=>{this._cameraRenderTime.endMonitoring(!1),hs.EndPerformanceCounter(`Rendering camera ${e.name}`)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new tr,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new tr,this._captureFrameTime=!1,this._frameTime=new tr,this._captureRenderTime=!1,this._renderTime=new tr,this._captureInterFrameTime=!1,this._interFrameTime=new tr,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new tr,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new tr,this._capturePhysicsTime=!1,this._physicsTime=new tr,this._captureAnimationsTime=!1,this._animationsTime=new tr,this._captureCameraRenderTime=!1,this._cameraRenderTime=new tr,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add((()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(hs.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this._captureRenderTime&&this._renderTime.fetchNewFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.fetchNewFrame(),this.scene.getEngine()._drawCalls.fetchNewFrame()})),this._onAfterRenderObserver=e.onAfterRenderObservable.add((()=>{this._captureFrameTime&&(hs.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring(),this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.endFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.endFrame(),this._captureParticlesRenderTime&&this._particlesRenderTime.endFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.endFrame(),this._captureRenderTime&&this._renderTime.endFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.endFrame()}))}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}bi.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";class Vg{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let r;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const a=[],l=[ys.PositionKind];let h=!1,c=!1;if(o){const e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(a.push("#define DIFFUSE"),r.isVerticesDataPresent(ys.UV2Kind)&&1===t.coordinatesIndex?(a.push("#define DIFFUSEUV2"),c=!0):r.isVerticesDataPresent(ys.UVKind)&&(a.push("#define DIFFUSEUV1"),h=!0),e&&(a.push("#define ALPHATEST"),a.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||a.push("#define DIFFUSE_ISLINEAR"));const s=o.opacityTexture;s&&(a.push("#define OPACITY"),r.isVerticesDataPresent(ys.UV2Kind)&&1===s.coordinatesIndex?(a.push("#define OPACITYUV2"),c=!0):r.isVerticesDataPresent(ys.UVKind)&&(a.push("#define OPACITYUV1"),h=!0))}i&&(a.push("#define EMISSIVE"),r.isVerticesDataPresent(ys.UV2Kind)&&1===i.coordinatesIndex?(a.push("#define EMISSIVEUV2"),c=!0):r.isVerticesDataPresent(ys.UVKind)&&(a.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||a.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(ys.ColorKind)&&r.hasVertexAlpha&&o.transparencyMode!==uo.MATERIAL_OPAQUE&&(l.push(ys.ColorKind),a.push("#define VERTEXALPHA")),h&&(l.push(ys.UVKind),a.push("#define UV1")),c&&(l.push(ys.UV2Kind),a.push("#define UV2"));const u=new ja;if(r.useBones&&r.computeBonesUsingShaders){l.push(ys.MatricesIndicesKind),l.push(ys.MatricesWeightsKind),r.numBoneInfluencers>4&&(l.push(ys.MatricesIndicesExtraKind),l.push(ys.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,r)}else a.push("#define NUM_BONE_INFLUENCERS 0");const d=r.morphTargetManager;let _=0;d&&(_=d.numMaxInfluencers||d.numInfluencers,_>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+_),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Fn(l,r,_))),t&&(a.push("#define INSTANCES"),Ln(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),Pn(o,this._scene,a),this._addCustomEffectDefines(a);const p=e._getDrawWrapper(void 0,!0),f=p.defines,m=a.join("\n");if(f!==m){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];An(e),p.setEffect(this._engine.createEffect("glowMapGeneration",l,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,u,void 0,void 0,{maxSimultaneousMorphTargets:_}),m)}return p.effect.isReady()}render(){for(let e=0;eh.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return hs.Instantiate(e.customType).Parse(e,t,i)}}Vg._SceneComponentInitialization=e=>{throw vt("EffectLayerSceneComponent")},qe([st()],Vg.prototype,"name",void 0),qe([ut()],Vg.prototype,"neutralColor",void 0),qe([st()],Vg.prototype,"isEnabled",void 0),qe([ft()],Vg.prototype,"camera",null),qe([st()],Vg.prototype,"renderingGroupId",null),qe([st()],Vg.prototype,"disableBoundingBoxesFromEffectLayer",void 0),G.AddParser(Rs.NAME_EFFECTLAYER,((e,t,i,s)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const s=r._mainTexture;this._engine.currentRenderPassId=s.renderPassId;for(const s of e.subMeshes)if(!r.isReady(s,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===Kr.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==Kr.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const e=s._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(Rs.NAME_EFFECTLAYER);t||(t=new Ug(e),e._addComponent(t))};bi.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",G.prototype.getGlowLayerByName=function(e){for(let t=0;t{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new pm("GlowLayerVBP1",new ue(0,1),n,{width:e,height:t},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new pm("GlowLayerHBP2",new ue(1,0),n,{width:s,height:r},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new pm("GlowLayerVBP2",new ue(0,1),n,{width:s,height:r},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(uo.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=yt.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Gg(e.name,t,e.options)),e,t,i);let r;for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class Wg extends Vg{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new X,this.onAfterBlurObservable=new X,this._instanceGlowingMeshStencilReference=Wg.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Wg.NeutralColor,this._engine.isStencilEnable||we.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Wg.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[ys.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?gn.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?gn.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new pl("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Vo.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Vo.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Vo.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new Nh("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new zg("HighlightLayerHBP",new ue(1,0),this._options.blurHorizontalSize,1,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new zg("HighlightLayerVBP",new ue(0,1),this._options.blurVerticalSize,1,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new pm("HighlightLayerHBP",new ue(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new pm("HighlightLayerVBP",new ue(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(uo.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(uo.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!this._meshes&&!!super.hasMesh(e)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const e in this._meshes)if(this._meshes[e]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes)for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Wg.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=yt.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const s=yt.Parse((()=>new Wg(e.name,t,e.options)),e,t,i);let r;for(r=0;rthis._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,s,r){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(r)>-1&&!!(e.layerMask&s)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}bi.ShadersStore.layerPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.layerVertexShader="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Xg{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}constructor(e,t,i,s,r){this.name=e,this._applyPostProcess=!0,this.scale=new ue(1,1),this.offset=new ue(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new X,this.onBeforeRenderObservable=new X,this.onAfterRenderObservable=new X,this.texture=t?new Vo(t,i,!0):null,this.isBackground=void 0===s||s,this.color=void 0===r?new Ee(1,1,1,1):r,this._scene=i||se.LastCreatedScene;let n=this._scene._getComponent(Rs.NAME_LAYER);n||(n=new Hg(this._scene),this._scene._addComponent(n)),this._scene.layers.push(this);const o=this._scene.getEngine();this._drawWrapper=new Fi(o);const a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);const l=new ys(o,a,ys.PositionKind,!1,!1,2);this._vertexBuffers[ys.PositionKind]=l,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+="\n#define LINEAR"),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[ys.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));const i=this._drawWrapper.effect;return i?.isReady()&&this.texture?.isReady()}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(uo.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(uo.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[ys.PositionKind];e&&(e.dispose(),this._vertexBuffers[ys.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}class Yg{static AddFlare(e,t,i,s,r){return new Yg(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Ce(1,1,1),this.texture=s?new Vo(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new Fi(n),this._drawWrapper.effect=n.createEffect("lensFlare",[ys.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}bi.ShadersStore.lensFlarePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.lensFlareVertexShader="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Qg{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||se.LastCreatedScene,Qg._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&i.activeCamera.layerMask);const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[ys.PositionKind]=new ys(s,r,ys.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=de.Project(t,fe.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=de.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new Zo(this._scene.activeCamera.globalPosition,e),s=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,s;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,s=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let r=i>s?i:s;r-=this.viewportBorder,r>this.borderLimit&&(r=this.borderLimit);let n=1-xe.Clamp(r/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const o=t.x+t.width/2,a=t.y+t.height/2,l=o-this._positionX,h=a-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i{throw vt("LensFlareSystemSceneComponent")},G.AddParser(Rs.NAME_LENSFLARESYSTEM,((e,t,i,s)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let r=0,n=e.lensFlareSystems.length;r{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()}))}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;hs.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();hs.EndPerformanceCounter("Lens flares",t.length>0)}}}Qg._SceneComponentInitialization=e=>{let t=e._getComponent(Rs.NAME_LENSFLARESYSTEM);t||(t=new jg(e),e._addComponent(t))};bi.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";bi.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";bi.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";bi.ShadersStore.shadowMapPixelShader="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";bi.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";bi.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";bi.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n";bi.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";bi.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";bi.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";bi.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";bi.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";bi.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";bi.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";class Kg{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===Kg.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===Kg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===Kg.FILTER_PCF||e===Kg.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==Kg.FILTER_PCF&&e!==Kg.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===Kg.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Kg.FILTER_POISSONSAMPLING);(e||this.filter===Kg.FILTER_POISSONSAMPLING)&&(this.filter=e?t:Kg.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Kg.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Kg.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===Kg.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:Kg.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Kg.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Kg.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===Kg.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:Kg.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Kg.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Kg.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Kg.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Kg.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Kg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Kg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Kg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Kg.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Kg.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Kg.FILTER_PCF);(e||this.filter===Kg.FILTER_PCF)&&(this.filter=e?t:Kg.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===Kg.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Kg.FILTER_PCSS);(e||this.filter===Kg.FILTER_PCSS)&&(this.filter=e?t:Kg.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return Kg.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new X,this.onAfterShadowMapRenderObservable=new X,this.onBeforeShadowMapRenderMeshObservable=new X,this.onAfterShadowMapRenderMeshObservable=new X,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Kg.FILTER_NONE,this._filteringQuality=Kg.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=de.Zero(),this._viewMatrix=fe.Zero(),this._projectionMatrix=fe.Zero(),this._transformMatrix=fe.Zero(),this._cachedPosition=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=fe.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),Kg._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new pl(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new pl(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Vo.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Vo.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Vo.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,s)=>this._renderForShadowMap(e,t,i,s),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===Kg.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Kg.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0),e._debugPopGroup?.(1))}));const t=new Ee(0,0,0,0),i=new Ee(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===Kg.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=Ps.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new pm(this._light.name+"KernelBlurY",new ue(0,1),this.blurKernel,1,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new qa(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r{s===i||e?(s.getMeshUniformBuffer().bindToEffect(h,"Mesh"),s.transferToEffect(e?t:_)):(i.getMeshUniformBuffer().bindToEffect(h,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(h),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===Kg.FILTER_NONE||this.filter===Kg.FILTER_PCSS?this._shadowMap.updateSamplingMode(Vo.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Vo.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s)return void(e&&e(this));const r=s.renderList;if(!r)return void(e&&e(this));const n=[];for(const e of r)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let o=0;const a=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[o],i.useInstances,n[o].getMaterial()?.needAlphaBlendingForMesh(n[o].getMesh())??!1);)if(o++,o>=n.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(ys.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===yo.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,o=i.defines;const a=[ys.PositionKind],l=e.getMesh();this.normalBias&&l.isVerticesDataPresent(ys.NormalKind)&&(a.push(ys.NormalKind),n.push("#define NORMAL"),l.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const h=s.needAlphaTesting();if((h||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=s.alphaCutOff??Kg.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),h&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),l.isVerticesDataPresent(ys.UVKind)&&(a.push(ys.UVKind),n.push("#define UV1")),l.isVerticesDataPresent(ys.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(a.push(ys.UV2Kind),n.push("#define UV2"))}const c=new ja;if(l.useBones&&l.computeBonesUsingShaders&&l.skeleton){a.push(ys.MatricesIndicesKind),a.push(ys.MatricesWeightsKind),l.numBoneInfluencers>4&&(a.push(ys.MatricesIndicesExtraKind),a.push(ys.MatricesWeightsExtraKind));const e=l.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+l.numBoneInfluencers),l.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,l),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=l.morphTargetManager;let d=0;if(u&&(d=u.numMaxInfluencers||u.numInfluencers,d>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),Fn(a,l,d))),Pn(s,this._scene,n),t&&(n.push("#define INSTANCES"),Ln(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const _=l.bakedVertexAnimationManager;t&&_&&_.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),a.push("bakedVertexAnimationSettingsInstanced"));const p=n.join("\n");if(o!==p){o=p;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],s=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if(An(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===a.indexOf(e)&&a.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===s.indexOf(e)&&s.push(e)}const l=this._scene.getEngine();r=l.createEffect(e,{attributes:a,uniformsNames:t,uniformBuffersNames:n,samplers:s,defines:p,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d}},l),i.setEffect(r,o)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;i.shadowsEnabled&&s.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Kg.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Kg.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Kg.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Kg.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();r&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===Kg.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r.getSize().width,1/r.getSize().width,this.frustumEdgeFalloff,e)):this._filter===Kg.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r.getSize().width,this._contactHardeningLightSizeUVRatio*r.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/r.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e))}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),de.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(de.Dot(this._lightDirection,de.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),fe.LookAtLHToRef(t,t.add(this._lightDirection),de.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i{throw vt("ShadowGeneratorSceneComponent")};bi.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";bi.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";bi.ShadersStore.depthVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";class $g{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=Vo.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new Ee(1,1,1,1):this.clearColor=new Ee(n?1e8:1,0,0,1),$g._SceneComponentInitialization(this._scene);const a=e.getEngine();this._camera=i,r!==Vo.NEAREST_SAMPLINGMODE&&(1!==t||a._caps.textureFloatLinearFiltering||(r=Vo.NEAREST_SAMPLINGMODE),2!==t||a._caps.textureHalfFloatLinearFiltering||(r=Vo.NEAREST_SAMPLINGMODE));const l=this.isPacked||!a._features.supportExtendedTextureFormats?5:6;this._depthMap=new pl(o??"DepthRenderer",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,l),this._depthMap.wrapU=Vo.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Vo.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{a._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===s.getRenderId())return;const o=i._getWorldMatrixDeterminant()<0;let a=t.overrideMaterialSideOrientation??n.sideOrientation;o&&(a=0===a?1:0);const l=0===a;r.setState(n.backFaceCulling,0,!1,l,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const h=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(h.mustReturn)return;const c=r.getCaps().instancedArrays&&(null!==h.visibleInstances[e._id]&&void 0!==h.visibleInstances[e._id]||t.hasThinInstances),u=this._camera||s.activeCamera;if(this.isReady(e,c)&&u){e._renderId=s.getRenderId();const o=i._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];let a=e._getDrawWrapper();!a&&o&&(a=o._getDrawWrapper());const l=u.mode===Kr.ORTHOGRAPHIC_CAMERA;if(!a)return;const d=a.effect;let _,p;if(r.enableEffect(a),c||t._bind(e,d,n.fillMode),o?o.bindForSubMesh(i.getWorldMatrix(),i,e):(d.setMatrix("viewProjection",s.getTransformMatrix()),d.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&d.setMatrix("view",s.getViewMatrix())),l?(_=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(_=r.useReverseDepthBuffer&&r.isNDCHalfZRange?u.minZ:r.isNDCHalfZRange?0:u.minZ,p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:u.maxZ),d.setFloat2("depthValues",_,_+p),!o){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(d.setTexture("diffuseSampler",e),d.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices){const i=e.getTransformMatrixTexture(t);if(!i)return;d.setTexture("boneSampler",i),d.setFloat("boneTextureWidth",4*(e.bones.length+1))}else d.setMatrices("mBones",e.getTransformMatrices(t))}In(d,n,s),kn(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d),n.pointsCloud&&d.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,d,n.fillMode,h,c,((e,t)=>d.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,s)=>{let r;if(s.length)for(r=0;r4&&(l.push(ys.MatricesIndicesExtraKind),l.push(ys.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),a.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;t?.isUsingTextureForMatrices&&a.push("#define BONETEXTURE")}else a.push("#define NUM_BONE_INFLUENCERS 0");const h=s.morphTargetManager;let c=0;h&&(c=h.numMaxInfluencers||h.numInfluencers,c>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Fn(l,s,c))),o.pointsCloud&&a.push("#define POINTSIZE"),t&&(a.push("#define INSTANCES"),Ln(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&a.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&a.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&a.push("#define PACKED"),Pn(o,r,a);const u=e._getDrawWrapper(void 0,!0),d=u.defines,_=a.join("\n");if(d!==_){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];An(e),u.setEffect(i.createEffect("depth",l,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}$g._SceneComponentInitialization=e=>{throw vt("DepthRendererSceneComponent")};bi.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class qg{constructor(e){this.onAfterReductionPerformed=new X,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Cs(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new qa("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(n);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new qa("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,r.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=s,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const s=new Float32Array(4*e*t),n={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,s,!1),n.min=s[0],n.max=s[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(o,a,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),e._debugPopGroup?.(1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo()))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return rv.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=t+r*s,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*s,a=o-n,l=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Kg.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==Kg.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;const n=r.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===Kg.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,r),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===Kg.FILTER_PCSS){for(let e=0;enew rv(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}rv._FrustumCornersNDCSpace=[new de(-1,1,-1),new de(1,1,-1),new de(1,-1,-1),new de(-1,-1,-1),new de(-1,1,1),new de(1,1,1),new de(1,-1,1),new de(-1,-1,1)],rv.CLASSNAME="CascadedShadowGenerator",rv.DEFAULT_CASCADES_COUNT=4,rv.MIN_CASCADES_COUNT=2,rv.MAX_CASCADES_COUNT=4,rv._SceneComponentInitialization=e=>{throw vt("ShadowGeneratorSceneComponent")},G.AddParser(Rs.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,s=e.shadowGenerators.length;i{let t=e._getComponent(Rs.NAME_SHADOWGENERATOR);t||(t=new nv(e),e._addComponent(t))},Ct.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new ov(e,de.Zero(),t)));class ov extends am{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return yo.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new de(1,0,0);case 1:return new de(-1,0,0);case 2:return new de(0,-1,0);case 3:return new de(0,1,0);case 4:return new de(0,0,1);case 5:return new de(0,0,-1)}return de.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;fe.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}qe([st()],ov.prototype,"shadowAngle",null);class av{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;av.DefaultLogoUrl?t.src=av.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=new Image;if(av.DefaultSpinnerUrl?s.src=av.DefaultSpinnerUrl:s.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${i.w}vh`,s.style.height=`${i.h}vh`,s.style.left=`calc(50% - ${i.w/2}vh)`,s.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(s),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}av.DefaultLogoUrl="",av.DefaultSpinnerUrl="",gn.DefaultLoadingScreenFactory=e=>new av(e);class lv{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),back:this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),left:this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),right:this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),up:this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),down:this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r),size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=n?Math.max(1,Math.round(s/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),_=1/e;let p=0;for(let n=0;nMath.PI;)r-=2*Math.PI;let o=r/Math.PI;const a=n/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*s);h<0?h=0:h>=s&&(h=s-1);const c=s-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}lv.FACE_LEFT=[new de(-1,-1,-1),new de(1,-1,-1),new de(-1,1,-1),new de(1,1,-1)],lv.FACE_RIGHT=[new de(1,-1,1),new de(-1,-1,1),new de(1,1,1),new de(-1,1,1)],lv.FACE_FRONT=[new de(1,-1,-1),new de(1,-1,1),new de(1,1,-1),new de(1,1,1)],lv.FACE_BACK=[new de(-1,-1,1),new de(-1,-1,-1),new de(-1,1,1),new de(-1,1,-1)],lv.FACE_DOWN=[new de(1,1,-1),new de(1,1,1),new de(-1,1,-1),new de(-1,1,1)],lv.FACE_UP=[new de(-1,-1,-1),new de(-1,-1,1),new de(1,-1,-1),new de(1,-1,1)];class hv{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,s,r,n){r>0?(r=this._Ldexp(1,r-136),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return lv.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,a,l,h=t.dataPosition,c=0,u=0,d=0;const _=new ArrayBuffer(4*s),p=new Uint8Array(_),f=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(f);for(;i>0;){if(r=e[h++],n=e[h++],o=e[h++],a=e[h++],2!=r||2!=n||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=s)throw"HDR Bad header format, wrong scan line width";for(c=0,d=0;d<4;d++)for(u=(d+1)*s;c128){if(l=r-128,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)p[c++]=n}else{if(l=r,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(p[c++]=n,--l>0)for(let t=0;t0;){for(l=0;l{this._effectRenderer=new al(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(we.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class uv extends No{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(fe.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,s=!1,r=!0,n=!1,o=!1,a=null,l=null,h=!1){super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=de.Zero(),this.onLoadObservable=new X,e&&(this._coordinatesMode=Vo.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=fe.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),a&&a()},this._onError=l,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=h,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?hs.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):this.getScene()?.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new cv(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=hv.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=b_.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const s=[];let r=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(r=new Uint8Array(this._size*this._size*3));const o=t[uv._FacesMapping[e]];if(this.gammaSpace||n||r)for(let e=0;e255){const e=255/n;t*=e,i*=e,s*=e}r[3*e+0]=t,r[3*e+1]=i,r[3*e+2]=s}n?s.push(n):r?s.push(r):s.push(o)}return s}),null,this._onLoad,this._onError)}clone(){const e=new uv(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let s=null;return e.name&&!e.isRenderTarget&&(s=new uv(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=de.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=de.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}uv._FacesMapping=["right","left","up","down","front","back"],ee("BABYLON.HDRCubeTexture",uv);class dv{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new X,this._onDataLayoutChanged=new X,this._animationPropertiesOverride=null,this._scene=i||se.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=yt.Clone((()=>new dv(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),yt.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new dv(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new ds(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=se.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return pv.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new pv(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=pv.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void we.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new pv(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(dv.Parse(s,t));return i}}pv.EnableTextureStorage=!0,pv.MaxActiveMorphTargetsInVertexAttributeMode=8;class fv{constructor(){this._hasHit=!1,this._hitNormal=de.Zero(),this._hitPoint=de.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class mv extends fv{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=de.Zero(),this._rayToWorld=de.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=de.Distance(this._rayFromWorld,this._hitPoint)}reset(e=de.Zero(),t=de.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}class gv{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw vt("CannonJSPlugin")}constructor(e,t=gv.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new de(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter((function(s){return s.connectedImpostor===t&&s.joint===i&&s.mainImpostor===e}));s.length&&this._physicsPlugin.removeJoint(s[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void we.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(r[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const s=i[t];e.physicsBody[t].set(s.x,s.y,s.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const i=t=>{if(!t.rotationQuaternion)return;const s=t.getPhysicsImpostor();if(s&&s.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),r=t.rotationQuaternion.multiply(this._tmpQuaternion);s.physicsBody&&(this.removePhysicsBody(s),s.physicsBody=null),s.parent=e,s.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(s),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(r.x,r.y,r.z,r.w)),e.physicsBody.mass+=s.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let s;const r=e.joint.jointData,n={pivotA:r.mainPivot?(new this.BJSCANNON.Vec3).set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?(new this.BJSCANNON.Vec3).set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?(new this.BJSCANNON.Vec3).set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?(new this.BJSCANNON.Vec3).set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case da.HingeJoint:case da.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case da.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case da.SpringJoint:{const e=r;s=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case da.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case da.PointToPointJoint:case da.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce)}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==da.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==da.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;s1e3*i));e++);this.time+=s;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}gv.DefaultPluginFactory=()=>new vv;class xv{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=de.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new mv}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){we.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},s=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&s.push(e.physicsImpostor)}));const r=e=>Math.max(e,K),n=new pe;s.forEach((t=>{if(!t.object.rotationQuaternion)return;const s=t.object.rotationQuaternion;n.copyFrom(s),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=n.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case ga.ParticleImpostor:we.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case ga.SphereImpostor:{const e=a.x,t=a.y,s=a.z,n=Math.max(r(e),r(t),r(s))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case ga.CylinderImpostor:{const e=r(a.x)/2,t=r(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case ga.PlaneImpostor:case ga.BoxImpostor:default:{const e=r(a.x),t=r(a.y),s=r(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(s);break}}t.object.rotationQuaternion=s})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case da.BallAndSocketJoint:n="jointBall";break;case da.SpringJoint:{we.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=s;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case da.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case da.PrismaticJoint:n="jointPrisme";break;case da.SliderJoint:n="jointSlide";break;case da.WheelJoint:n="jointWheel";break;case da.HingeJoint:default:n="jointHinge"}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){we.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new de(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new de(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,s){void 0!==i?we.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return we.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){we.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class bv{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new pe,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new de,this._tmpContactNormal=new de,this._tmpVec3=new de,this._tmpMatrix=new fe,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new mv,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):we.Error("AmmoJS is not available. Please make sure you included the js file.")):we.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===ga.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,a;const l=new Array;for(let e=0;e{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData;let r;switch(s.mainPivot||(s.mainPivot=new de(0,0,0)),s.connectedPivot||(s.connectedPivot=new de(0,0,0)),e.joint.type){case da.DistanceJoint:{const e=s.maxDistance;e&&(s.mainPivot=new de(0,-e/2,0),s.connectedPivot=new de(0,e/2,0)),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case da.HingeJoint:{s.mainAxis||(s.mainAxis=new de(0,0,0)),s.connectedAxis||(s.connectedAxis=new de(0,0,0));const e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),n=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);r=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,n);break}case da.BallAndSocketJoint:r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:we.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n,o=i.getVerticesData(ys.PositionKind);if(o||(o=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?pe.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):pe.Identity(),fe.Compose(de.One(),e,t.position).invertToRef(this._tmpMatrix),n=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else fe.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),n=this._tmpMatrix;const a=r.length/3;for(let t=0;t{s+=this._addMeshVerts(e,t,i)}))}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(ys.PositionKind);i||(i=[]);let s=t.getVerticesData(ys.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let e=0;ee*e)).reduce(((e,t)=>e+t)))t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const s=e.getParam("path");if(null===e.getParam("shape"))return we.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=s.length,i=t-1,this._tmpAmmoVectorA.setValue(s[0].x,s[0].y,s[0].z),this._tmpAmmoVectorB.setValue(s[t-1].x,s[t-1].y,s[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(ys.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let t=0;t{s+=this._addHullVerts(e,t,i)}))}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==ga.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const r=this._createShape(t),n=e.parent.getWorldMatrix().clone(),o=new de;n.decompose(o),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*o.x,e.position.y*o.y,e.position.z*o.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,r),t.dispose(),i++}})),i>0){if(e.type!=ga.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,t))}return s}this.bjsAMMO.destroy(s),s=null}switch(e.type){case ga.SphereImpostor:if(xe.WithinEpsilon(r.x,r.y,1e-4)&&xe.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{const e=[new this.bjsAMMO.btVector3(0,0,0)],t=[1];s=new this.bjsAMMO.btMultiSphereShape(e,t,1),s.setLocalScaling(new this.bjsAMMO.btVector3(r.x/2,r.y/2,r.z/2))}break;case ga.CapsuleImpostor:{const e=r.x/2;s=new this.bjsAMMO.btCapsuleShape(e,r.y-2*e)}break;case ga.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case ga.PlaneImpostor:case ga.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case ga.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const r=this._addMeshVerts(t,i,i);s=0==r?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case ga.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),s=new this.bjsAMMO.btCompoundShape):s=t}break;case ga.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case ga.CustomImpostor:s=this._createCustom(e);break;case ga.SoftbodyImpostor:s=this._createSoftbody(e);break;case ga.ClothImpostor:s=this._createCloth(e);break;case ga.RopeImpostor:s=this._createRope(e);break;default:we.Warn("The impostor type is not currently supported by the ammo plugin.")}return s}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>K||Math.abs(s.getOrigin().y()-t.y)>K||Math.abs(s.getOrigin().z()-t.z)>K||Math.abs(s.getRotation().x()-i.x)>K||Math.abs(s.getRotation().y()-i.y)>K||Math.abs(s.getRotation().z()-i.z)>K||Math.abs(s.getRotation().w()-i.w)>K)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(s)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new de(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new de(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(we.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===ga.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):we.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(we.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):we.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(we.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):we.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(we.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):we.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*s));e.physicsBody.appendAnchor(a,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){we.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){we.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}bv._DISABLE_COLLISION_FLAG=4,bv._KINEMATIC_FLAG=2,bv._DISABLE_DEACTIVATION_FLAG=4,G.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},G.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class Tv{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=fe.Identity(),this._target=de.Zero(),this._add=de.Zero(),this._invertYAxis=!1,this.position=de.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(r){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new pl(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const a=i.getEngine().useReverseDepthBuffer;let l;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?fe.LookAtRHToRef:fe.LookAtLHToRef,s=i.useRightHandedSystem?fe.PerspectiveFovRH:fe.PerspectiveFovLH;t(this.position,this._target,de.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=s(Math.PI/2,1,a?i.activeCamera.maxZ:i.activeCamera.minZ,a?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{this._currentSceneUBO=i.getSceneUniformBuffer(),i.getEngine()._debugPushGroup?.(`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),i.getEngine()._debugPopGroup?.(1)}))}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=yt.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let i=0;is||new Tv(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}qe([ht()],Tv.prototype,"_attachedMesh",void 0),qe([lt()],Tv.prototype,"position",void 0);class yv{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class Sv extends yv{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new X,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new Ee(1,1,1,1),this.position=de.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=r.distance))&&(r=a,i))break}return r||new Ss},dr.prototype._internalMultiPickSprites=function(e,t,i){if(!Ss)return null;let s=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;r!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(Rs.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(Rs.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(Rs.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,Re.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,Re.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,Re.CreateNewFromSprite(i.pickedSprite,r,s))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,Re.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,Re.CreateNewFromSprite(i.pickedSprite,n,s)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,Re.CreateNewFromSprite(i.pickedSprite,n,s)),r&&i.pickedSprite.actionManager.processTrigger(6,Re.CreateNewFromSprite(i.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,Re.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}bi.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";bi.ShadersStore.spritesPixelShader="uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.spritesVertexShader="attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \nvColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class Ev{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,s=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Ts(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(ys.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Ts(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(ys.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ys.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[ys.ColorKind]=c,this._createEffects()}_createEffects(){this._drawWrapperBase?.dispose(),this._drawWrapperFog?.dispose(),this._drawWrapperDepth?.dispose(),this._drawWrapperFogDepth?.dispose(),this._drawWrapperBase=new Fi(this._engine),this._drawWrapperFog=new Fi(this._engine),this._drawWrapperDepth=new Fi(this._engine,!1),this._drawWrapperFogDepth=new Fi(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);const e=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[ys.PositionKind,"options","offsets","inverts","cellInfo",ys.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[ys.PositionKind,"options","offsets","inverts","cellInfo",ys.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],e+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,o=this._drawWrapperDepth,a=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(n=this._drawWrapperFog,o=this._drawWrapperFogDepth,a=!0);const l=n.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length);let _=0,p=!0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},r||(r=se.LastCreatedScene),r._getComponent(Rs.NAME_SPRITE)||r._addComponent(new Cv(r)),this._fromPacked=a,this._scene=r;const h=this._scene.getEngine();if(this._spriteRenderer=new Ev(h,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else{if(void 0===s)return void(this._spriteRenderer=null);this.cellWidth=s,this.cellHeight=s}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Vo(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const s=e.substring(0,i-1)+".json",r=()=>{we.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},n=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};hs.LoadFile(s,n,void 0,void 0,!1,r)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=ge.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const a=(o.x-s.x)/(r.x-s.x),l=1-(o.y-s.y)/(r.y-s.y),h=e._xOffset*n.width+a*e._xSize|0,c=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[4*(h+c*n.width)+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=de.Zero(),o=de.Zero();let a=Number.MAX_VALUE,l=null;const h=ge.Vector3[0],c=ge.Vector3[1],u=t.getViewMatrix();let d=e,_=e;for(let t=0;te){if(!this._checkTextureAlpha(r,d,e,n,o))continue;if(_=d,a=e,l=r,s)break}}}}if(l){const e=new Ss;u.invertToRef(ge.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=a;const t=ge.Vector3[2];return t.copyFrom(_.direction),t.normalize(),t.scaleInPlace(a),_.origin.addToRef(t,h),e.pickedPoint=de.TransformCoordinates(h,ge.Matrix[0]),e}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=de.Zero(),n=de.Zero();let o;const a=[],l=ge.Vector3[0].copyFromFloats(0,0,0),h=ge.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{const o=new At;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=Av.Parse(t,i||se.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new Av("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((s,r)=>{const n=new At;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.spriteManager),a=Av.Parse(o,t||se.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Av.SnippetUrl="https://snippet.babylonjs.com",Av.CreateFromSnippetAsync=Av.ParseFromSnippetAsync;var Pv=!0;class Rv{}Rv.LoaderInjectedPhysicsEngine=void 0;let Iv={},Mv={};const Ov=(e,t,i,s)=>{if(!t.materials)return null;for(let r=0,n=t.materials.length;r{for(const s in t)if(e.name===t[s])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},wv=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),Nv=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const s=t._waitingData.lods.ids,r=i.isEnabled(!1);if(t._waitingData.lods.distances){const n=t._waitingData.lods.distances;if(n.length>=s.length){const t=n.length>s.length?n[n.length-1]:0;i.setEnabled(!1);for(let t=0;t0&&i.addLODLevel(t,null),!0===r&&i.setEnabled(!0)}else hs.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},Fv=(e,t,i)=>{if("number"!=typeof e){const s=i.getLastEntryById(e);return s&&null!=t?s.instances[parseInt(t)]:s}const s=Iv[e];return s&&null!=t?s.instances[parseInt(t)]:s},Bv=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):Mv[e],Lv=(e,t,i,s,r=!1)=>{const n=new Eo(e);let o="importScene has failed JSON parse";try{var a=JSON.parse(t);o="";const s=Pa.loggingLevel===Pa.DETAILED_LOGGING;let r,l;if(void 0!==a.environmentTexture&&null!==a.environmentTexture){const t=void 0===a.isPBR||a.isPBR;if(a.environmentTextureType&&"BABYLON.HDRCubeTexture"===a.environmentTextureType){const s=a.environmentTextureSize?a.environmentTextureSize:128,r=new uv((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,s,!0,!t,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(r.rotationY=a.environmentTextureRotationY),e.environmentTexture=r}else if("object"==typeof a.environmentTexture){const t=mm.Parse(a.environmentTexture,e,i);e.environmentTexture=t}else if(a.environmentTexture.endsWith(".env")){const t=new mm((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}else{const t=mm.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}if(!0===a.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,s=a.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,s)}n.environmentTexture=e.environmentTexture}if(void 0!==a.environmentIntensity&&null!==a.environmentIntensity&&(e.environmentIntensity=a.environmentIntensity),void 0!==a.lights&&null!==a.lights)for(r=0,l=a.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})))}if(void 0!==a.multiMaterials&&null!==a.multiMaterials)for(r=0,l=a.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==a.morphTargetManagers&&null!==a.morphTargetManagers)for(const t of a.morphTargetManagers){const i=pv.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==a.skeletons&&null!==a.skeletons)for(r=0,l=a.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)}))}if(void 0!==a.transformNodes&&null!==a.transformNodes)for(r=0,l=a.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(Bv(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=Bv(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,l=e.skeletons.length;r{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,l=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),G.Parse(a,e,n,i),r=0,l=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,n,o,a)=>{let l="importMesh has failed JSON parse";try{var h=JSON.parse(i);l="";const a=Pa.loggingLevel===Pa.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const c=[],u=new Map,d=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(let e=0,i=h.transformNodes.length;e{!0!==e&&h.geometries[i]&&Array.isArray(h.geometries[i])&&h.geometries[i].forEach((r=>{r.id===f.geometryId&&("vertexData"===i&&_n.Parse(r,t,s),e=!0)}))})),!1===e&&we.Warn("Geometry not found for mesh "+f.id)}if(f.materialUniqueId||f.materialId){const e=f.materialUniqueId?_:n;let i=-1!==e.indexOf(f.materialUniqueId||f.materialId);if(!1===i&&void 0!==h.multiMaterials&&null!==h.multiMaterials){const r=(i,r)=>{e.push(i);const n=Ov(r,h,t,s);n&&n.material&&(Mv[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,l+="\n\tMaterial "+n.material.toString(a))};for(let s=0,n=h.multiMaterials.length;sr(e,(t=>t.uniqueId===e)))):n.materials.forEach((e=>r(e,(t=>t.id===e)))),e.push(n.uniqueId||n.id);const s=_o.ParseMultiMaterial(n,t);Mv[n.uniqueId||n.id]=s,s&&(i=!0,l+="\n\tMulti-Material "+s.toString(a));break}}}if(!1===i){e.push(f.materialUniqueId||f.materialId);const i=Ov((e=>f.materialUniqueId&&e.uniqueId===f.materialUniqueId||e.id===f.materialId),h,t,s);i&&i.material?(Mv[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,l+="\n\tMaterial "+i.material.toString(a)):we.Warn("Material not found for mesh "+f.id)}}if(null!==f.skeletonId&&void 0!==f.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(i.indexOf(f.skeletonId)>-1))for(let e=0,s=h.skeletons.length;e-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(p.indexOf(f.morphTargetManagerId)>-1))for(let e=0,i=h.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(Bv(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=Bv(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,i=t.transformNodes.length;e-1&&d.splice(e,1)}f._waitingParentId=null}f._waitingData.lods&&Nv(t,f)}for(const e of d)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(e){const t=wv("importMesh",h?h.producer:"Unknown")+l;if(!a)throw we.Log(t),e;a(t,e)}finally{null!==l&&Pa.loggingLevel!==Pa.NO_LOGGING&&we.Log(wv("importMesh",h?h.producer:"Unknown")+(Pa.loggingLevel!==Pa.MINIMAL_LOGGING?l:"")),Mv={}}return!1},load:(e,t,i,s)=>{let r="importScene has failed JSON parse";try{var n=JSON.parse(t);if(r="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!Pa.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=Ee.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=Ce.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=de.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),n.fogMode&&0!==n.fogMode)switch(e.fogMode=n.fogMode,e.fogColor=Ce.FromArray(n.fogColor),e.fogStart=n.fogStart,e.fogEnd=n.fogEnd,e.fogDensity=n.fogDensity,r+="\tFog mode for scene: ",e.fogMode){case 1:r+="exp\n";break;case 2:r+="exp2\n";break;case 3:r+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===vv.name?t=new vv(void 0,void 0,Rv.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===xv.name?t=new xv(void 0,Rv.LoaderInjectedPhysicsEngine):"ammo"!==n.physicsEngine&&n.physicsEngine!==bv.name||(t=new bv(void 0,Rv.LoaderInjectedPhysicsEngine,void 0)),r="\tPhysics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";const i=n.physicsGravity?de.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!!Lv(e,t,i,s,!0)&&(n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0)}catch(e){const t=wv("importScene",n?n.producer:"Unknown")+r;if(!s)throw we.Log(t),e;s(t,e)}finally{null!==r&&Pa.loggingLevel!==Pa.NO_LOGGING&&we.Log(wv("importScene",n?n.producer:"Unknown")+(Pa.loggingLevel!==Pa.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:(e,t,i,s)=>Lv(e,t,i,s)});class kv{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,gn.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||Ce.White(),this.rightColor=e.rightColor||Ce.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new kv;return Xe.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new kv({isEnabled:e.isEnabled,leftColor:Ce.FromArray(e.leftColor),rightColor:Ce.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}yt._FresnelParametersParser=kv.Parse;class Vv{}Vv.BindSceneUniformBuffer=Vn,Vv.PrepareDefinesForMergedUV=Un,Vv.BindTextureMatrix=Gn,Vv.GetFogState=$n,Vv.PrepareDefinesForMisc=qn,Vv.PrepareDefinesForCamera=lo,Vv.PrepareDefinesForFrameBoundValues=eo,Vv.PrepareDefinesForBones=to,Vv.PrepareDefinesForMorphTargets=io,Vv.PrepareDefinesForBakedVertexAnimation=so,Vv.PrepareDefinesForAttributes=ro,Vv.PrepareDefinesForMultiview=no,Vv.PrepareDefinesForOIT=oo,Vv.PrepareDefinesForPrePass=ao,Vv.PrepareDefinesForLight=Jn,Vv.PrepareDefinesForLights=Zn,Vv.PrepareUniformsAndSamplersForLight=ho,Vv.PrepareUniformsAndSamplersList=co,Vv.HandleFallbacksForShadows=Kn,Vv.PrepareAttributesForMorphTargetsInfluencers=Fn,Vv.PrepareAttributesForMorphTargets=Bn,Vv.PrepareAttributesForBakedVertexAnimation=zn,Vv.PrepareAttributesForBones=Qn,Vv.PrepareAttributesForInstances=jn,Vv.PushAttributesForInstances=Ln,Vv.BindLightProperties=Hn,Vv.BindLight=Xn,Vv.BindLights=Yn,Vv.BindFogParameters=Nn,Vv.BindBonesParameters=Wn,Vv.BindMorphTargetParameters=kn,Vv.BindLogDepth=wn;class Uv extends Yu{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new Ee(0,0,0,1))}}class Gv extends Vm{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new Ce(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}qe([st(),it("_markAllSubMeshesAsLightsDirty")],Gv.prototype,"maxSimultaneousLights",void 0),qe([st(),it("_markAllSubMeshesAsLightsDirty")],Gv.prototype,"disableLighting",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Gv.prototype,"environmentTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"invertNormalMapX",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"invertNormalMapY",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Gv.prototype,"normalTexture",void 0),qe([nt("emissive"),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"emissiveColor",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"emissiveTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Gv.prototype,"occlusionStrength",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Gv.prototype,"occlusionTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Gv.prototype,"alphaCutOff",void 0),qe([st()],Gv.prototype,"doubleSided",null),qe([rt(),it("_markAllSubMeshesAsTexturesDirty",null)],Gv.prototype,"lightmapTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Gv.prototype,"useLightmapAsShadowmap",void 0);class zv extends Gv{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=yt.Clone((()=>new zv(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=yt.Parse((()=>new zv(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}qe([nt(),it("_markAllSubMeshesAsTexturesDirty","_albedoColor")],zv.prototype,"baseColor",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],zv.prototype,"baseTexture",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],zv.prototype,"metallic",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],zv.prototype,"roughness",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],zv.prototype,"metallicRoughnessTexture",void 0),ee("BABYLON.PBRMetallicRoughnessMaterial",zv);class Wv extends Gv{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=yt.Clone((()=>new Wv(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=yt.Parse((()=>new Wv(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}qe([nt("diffuse"),it("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Wv.prototype,"diffuseColor",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Wv.prototype,"diffuseTexture",void 0),qe([nt("specular"),it("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Wv.prototype,"specularColor",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty","_microSurface")],Wv.prototype,"glossiness",void 0),qe([rt(),it("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Wv.prototype,"specularGlossinessTexture",void 0),ee("BABYLON.PBRSpecularGlossinessMaterial",Wv);class Hv extends No{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=fe.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=i=>{if("string"!=typeof i)return;let s,r=null,n=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)r[e]=255;else{const t=n[e];r[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,r,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,r,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new Hv(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new Hv(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}Hv._NoneEmptyLineRegex=/\S+/,ee("BABYLON.ColorGradingTexture",Hv);class Xv extends No{constructor(e,t,i,s=!1,r=!0,n=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Vo.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?hs.SetImmediate((()=>n())):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage((()=>this._loadTexture()),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const s=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);s.generateMipMaps=!this._noMipmap,i.addPendingData(s),s.url=this.url,s.isReady=!1,i.getEngine()._internalTexturesCache.push(s),this._texture=s;const r=document.createElement("canvas");Qi(this.url,(t=>{this._width=t.width,this._height=t.height,r.width=this._width,r.height=this._height;const i=r.getContext("2d");i.drawImage(t,0,0);const s=i.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,r.remove(),e()}),((e,r)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,r)}),i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene();if(!e)return;const t=(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=lv.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const s=t[Xv._FacesMapping[e]];i.push(s)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let s=0;for(let r=0;rt.length)return void we.Error("Unable to load TGA file - Not enough data");i+=s.id_length;let r,n=!1,o=!1,a=!1;switch(s.image_type){case $v:n=!0;case Qv:o=!0;break;case qv:n=!0;case jv:break;case Zv:n=!0;case Kv:a=!0}const l=s.pixel_size>>3,h=s.width*s.height*l;let c,u,d,_,p,f,m;if(o&&(c=t.subarray(i,i+=s.colormap_length*(s.colormap_size>>3))),n){let e,s,n;r=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i>ex){default:case sx:u=0,_=1,m=s.width,d=0,p=1,f=s.height;break;case tx:u=0,_=1,m=s.width,d=s.height-1,p=-1,f=-1;break;case rx:u=s.width-1,_=-1,m=-1,d=0,p=1,f=s.height;break;case ix:u=s.width-1,_=-1,m=-1,d=s.height-1,p=-1,f=-1}const g="_getImageData"+(a?"Grey":"")+s.pixel_size+"bits",v=ax[g](s,c,r,d,p,f,u,_,m);e.getEngine()._uploadDataToTextureDirectly(e,v)}const ax={GetTGAHeader:nx,UploadContent:ox,_getImageData8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=t,u=e.width,d=e.height;let _,p,f,m=0;const g=new Uint8Array(u*d*4);for(f=s;f!==n;f+=r)for(p=o;p!==l;p+=a,m++)_=h[m],g[4*(p+u*f)+3]=255,g[4*(p+u*f)+2]=c[3*_+0],g[4*(p+u*f)+1]=c[3*_+1],g[4*(p+u*f)+0]=c[3*_+2];return g},_getImageData16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p,f=0;const m=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(_=o;_!==l;_+=a,f+=2){d=h[f+0]+(h[f+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(_+c*p)+0]=e,m[4*(_+c*p)+1]=t,m[4*(_+c*p)+2]=i,m[4*(_+c*p)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=3)f[4*(d+c*_)+3]=255,f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+1]=h[p+1],f[4*(d+c*_)+0]=h[p+2];return f},_getImageData32bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=4)f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+1]=h[p+1],f[4*(d+c*_)+0]=h[p+2],f[4*(d+c*_)+3]=h[p+3];return f},_getImageDataGrey8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p,f=0;const m=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(_=o;_!==l;_+=a,f++)d=h[f],m[4*(_+c*p)+0]=d,m[4*(_+c*p)+1]=d,m[4*(_+c*p)+2]=d,m[4*(_+c*p)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=2)f[4*(d+c*_)+0]=h[p+0],f[4*(d+c*_)+1]=h[p+0],f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+3]=h[p+1];return f}};class lx{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=nx(s);i(r.width,r.height,t.generateMipMaps,!1,(()=>{ox(t,s)}))}}gn._TextureLoaders.push(new lx);class hx{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=hv.RGBE_ReadHeader(s),n=hv.RGBE_ReadPixels(s,r),o=r.width*r.height,a=new Float32Array(4*o);for(let e=0;e{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}}function cx(){let e=null;function t(e,t,i,s,r){const n=e.getImageTranscodedSizeInBytes(t,i,s);let o=new Uint8Array(n);return e.transcodeImage(o,t,i,s,1,0)?(r&&(o=function(e,t,i,s){const r=new Uint16Array(4),n=new Uint16Array(i*s),o=i/4,a=s/4;for(let t=0;t>2&3],n[h++]=r[l>>4&3],n[h++]=r[l>>6&3]}}return n}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,s=i.data.imageData,r=new BASIS.BasisFile(s),n=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),s=[];for(let t=0;t{let i;switch(e){case _x.cTFETC1:i=36196;break;case _x.cTFBC1:i=33776;break;case _x.cTFBC4:i=33779;break;case _x.cTFASTC_4x4:i=37808;break;case _x.cTFETC2:i=37496;break;case _x.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i};let mx=null,gx=null,vx=0;const xx=e=>{gx=e},bx=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,s)=>{(mx||(mx=new Promise(((e,t)=>{gx?e(gx):hs.LoadFileAsync(hs.GetBabylonScriptURL(px.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const s=URL.createObjectURL(new Blob([`(${cx})()`],{type:"application/javascript"}));gx=new Worker(s),function(e,t,i){return new Promise(((s,r)=>{const n=t=>{"init"===t.data.action?(e.removeEventListener("message",n),s(e)):"error"===t.data.action&&r(t.data.error||"error initializing worker")};e.addEventListener("message",n),e.postMessage({action:"init",url:i?hs.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(gx,i,px.JSModuleURL).then(e,t)})).catch(t)}))),mx).then((()=>{const r=vx++,n=t=>{"transcode"===t.data.action&&t.data.id===r&&(gx.removeEventListener("message",n),t.data.success?e(t.data):s("Transcode is not supported on this device"))};gx.addEventListener("message",n);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),gx.postMessage({action:"transcode",id:r,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{s(e)}))}))},Tx=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},yx=(e,t)=>{const i=e.getEngine();for(let s=0;s{i._releaseTexture(t),Tx(e,i)}))}else{e.width=r.width,e.height=r.height,e.generateMipMaps=t.fileInfo.images[s].levels.length>1;const n=Sx.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,Tx(e,i),t.fileInfo.images[s].levels.forEach(((t,r)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,s,r)})),!i._features.basisNeedsPOT||xe.Log2(e.width)%1==0&&xe.Log2(e.height)%1==0||(hs.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=Vo.CLAMP_ADDRESSMODE,e._cachedWrapV=Vo.CLAMP_ADDRESSMODE)}}},Sx={JSModuleURL:px.JSModuleURL,WasmModuleURL:px.WasmModuleURL,GetInternalFormatFromBasisFormat:fx,TranscodeAsync:bx,LoadTextureFromTranscodeResult:yx};Object.defineProperty(Sx,"JSModuleURL",{get:function(){return px.JSModuleURL},set:function(e){px.JSModuleURL=e}}),Object.defineProperty(Sx,"WasmModuleURL",{get:function(){return px.WasmModuleURL},set:function(e){px.WasmModuleURL=e}});class Cx{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};bx(e,o).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;yx(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()})).catch((e=>{hs.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,r&&r(e)}))}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};bx(e,r).then((e=>{const s=e.fileInfo.images[0].levels[0],r=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(s.width,s.height,r,-1!==e.format,(()=>{yx(t,e)}))})).catch((e=>{hs.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),hs.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}}gn._TextureLoaders.push(new Cx);class Ex extends pl{get isSupported(){return this._engine?.getCaps().drawBuffersExtension??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}class Ax{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Px{constructor(e,t,i,s){return this.name=e,this.meshes=t,this.scene=s,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??ys.UVKind,this.options.uvsOut=this.options.uvsOut??ys.UVKind,this.options.layout=this.options.layout??Px.LAYOUT_STRIP,this.options.layout===Px.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Px.SUBUV_WRAP,this.options.paddingMode===Px.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new Ee(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new ue(1,1).divide(t);let s=0;const r=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(a,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{s++,d.update(!1);const i=_.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*p.x,t.y*p.y),d.dispose(),n.update(!1),s==r)return c(),void e()},m=o[u]||"_blank";if(n&&null!==n[m]){const e=n[m],t=new Image;t.src=e instanceof Sc?e.getContext().canvas.toDataURL("image/png"):e.url,hs.SetCorsBehavior(t.src,t),t.onload=()=>{_.fillStyle="rgba(0,0,0,0)",_.fillRect(0,0,h,h),d.update(!1),_.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)_.drawImage(t,0,0,t.width,t.height,l+a*e[i],l+a*e[i+1]-h,a,a);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},s=Object.keys(this.sets),r=Object.keys(this.options);try{for(let r=0;r{try{this.setFragment(this._texturePath)}catch(e){we.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",s=new At;s.open("GET",i),s.addEventListener("load",(()=>{if(200===s.status||s.responseText&&s.responseText.length>0)try{this._config=JSON.parse(s.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch(e){t()}else t()}),!1),s.addEventListener("error",(()=>{t()}),!1);try{s.send()}catch(e){we.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=.03*t.getAnimationRatio(),this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e{}))}clone(){return yt.Clone((()=>{const e=this.getScene(),t=this._texture,i=new Mx(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===Ai.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}class Ox extends Vo{constructor(e,t,i,s,r,n,o=!0,a=!1,l=Vo.TRILINEAR_SAMPLINGMODE,h=0,c){super(null,n,!o,a),this.format=r,this._texture=n.getEngine().createRawTexture3D(e,t,i,s,r,o,a,l,null,h,c),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class Dx extends pl{constructor(e,t,i,s){super(e,t,i,s,!0),this.refractionPlane=new ir(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((()=>{this.getScene().clipPlane=this.refractionPlane})),this.onAfterRenderObservable.add((()=>{this.getScene().clipPlane=null}))}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Dx(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}class wx extends wo{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){this._renderTarget?.dispose(!0),this._renderTarget=null,e||super.dispose()}}class Nx extends Da{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Nx&&e._blockName===this._blockName?Ta.Compatible:Ta.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class Fx extends wa{constructor(e){super(e,ba.Vertex),this.registerInput("matricesIndices",xa.Vector4),this.registerInput("matricesWeights",xa.Vector4),this.registerInput("matricesIndicesExtra",xa.Vector4,!0),this.registerInput("matricesWeightsExtra",xa.Vector4,!0),this.registerInput("world",xa.Matrix),this.registerOutput("output",xa.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name&&t(e)));i||(i=new Wa("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name&&t(e)));i||(i=new Wa("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.World&&t(e)));i||(i=new Wa("world"),i.setAsSystemValue(Ea.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){Wn(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&to(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const s=this._outputs[0],r=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",e.compilationString+=this._declareOutput(s,e)+` = ${r.associatedVariableName} * ${i};\n`,e.compilationString+="#else\n",e.compilationString+=this._declareOutput(s,e)+` = ${r.associatedVariableName};\n`,e.compilationString+="#endif\n",this}}ee("BABYLON.BonesBlock",Fx);class Bx extends wa{constructor(e){super(e,ba.Vertex),this.registerInput("world0",xa.Vector4),this.registerInput("world1",xa.Vector4),this.registerInput("world2",xa.Vector4),this.registerInput("world3",xa.Vector4),this.registerInput("world",xa.Matrix,!0),this.registerOutput("output",xa.Matrix),this.registerOutput("instanceID",xa.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=(()=>!0)){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name&&t(e)));i||(i=new Wa("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name&&t(e)));i||(i=new Wa("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name&&t(e)));i||(i=new Wa("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name&&t(e)));i||(i=new Wa("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name&&t(e)));i||(i=new Wa("world"),i.setAsSystemValue(Ea.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!r?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!r?.getRenderingMesh().hasThinInstances),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,a=this.world3;return e.compilationString+="#ifdef INSTANCES\n",e.compilationString+=this._declareOutput(i,e)+` = mat4(${r.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\n`,e.compilationString+="#ifdef THIN_INSTANCES\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\n`,e.compilationString+="#endif\n",t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(s,e)+" = float(gl_InstanceID);\n":e.compilationString+=this._declareOutput(s,e)+" = 0.0;\n",e.compilationString+="#else\n",e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName};\n`,e.compilationString+=this._declareOutput(s,e)+" = 0.0;\n",e.compilationString+="#endif\n",this}}ee("BABYLON.InstancesBlock",Bx);class Lx extends wa{constructor(e){super(e,ba.Vertex),this.registerInput("position",xa.Vector3),this.registerInput("normal",xa.Vector3),this.registerInput("tangent",xa.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(xa.Color4|xa.Vector4|xa.Vector3),this.registerInput("uv",xa.Vector2),this.registerOutput("positionOutput",xa.Vector3),this.registerOutput("normalOutput",xa.Vector3),this.registerOutput("tangentOutput",xa.Vector4),this.registerOutput("uvOutput",xa.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Wa("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Wa("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&t(e)));i||(i=new Wa("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Wa("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;t?.isUsingTextureForTargets&&(t.numMaxInfluencers||t.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&io(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(kn(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,_=s.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,f=p&&p.supportsNormals&&s.NORMAL,m=p&&p.supportsTangents&&s.TANGENT,g=p&&p.supportsUVs&&s.UV1;let v="";if(p?.isUsingTextureForTargets&&_>0&&(v+="float vertexID;\n"),v+="#ifdef MORPHTARGETS\n",p?.isUsingTextureForTargets)v+="for (int i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n",v+="if (i >= morphTargetCount) break;\n",v+="vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\n",v+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${r.associatedVariableName}) * morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",f&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${a.associatedVariableName}) * morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * morphTargetInfluences[i];\n`,o.type===xa.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n"),v+="}\n";else for(let e=0;e<_;e++)v+=`${l.associatedVariableName} += (position${e} - ${r.associatedVariableName}) * morphTargetInfluences[${e}];\n`,f&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (normal${e} - ${n.associatedVariableName}) * morphTargetInfluences[${e}];\n`,v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName}.xy += (uv_${e} - ${a.associatedVariableName}.xy) * morphTargetInfluences[${e}];\n`,v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (tangent${e} - ${o.associatedVariableName}.xyz) * morphTargetInfluences[${e}];\n`,o.type===xa.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n");if(v+="#endif\n",d.compilationString=d.compilationString.replace(this._repeatableContentAnchor,v),_>0)for(let e=0;e<_;e++)d.attributes.push(ys.PositionKind+e),f&&d.attributes.push(ys.NormalKind+e),m&&d.attributes.push(ys.TangentKind+e),g&&d.attributes.push(ys.UVKind+"_"+e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);const t=this.position,i=this.normal,s=this.tangent,r=this.uv,n=this.positionOutput,o=this.normalOutput,a=this.tangentOutput,l=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetCount"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${this._declareOutput(n,e)} = ${t.associatedVariableName};\n`,e.compilationString+="#ifdef NORMAL\n",e.compilationString+=`${this._declareOutput(o,e)} = ${i.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${this._declareOutput(o,e)} = vec3(0., 0., 0.);\n`,e.compilationString+="#endif\n",e.compilationString+="#ifdef TANGENT\n",e.compilationString+=`${this._declareOutput(a,e)} = ${s.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${this._declareOutput(a,e)} = vec4(0., 0., 0., 0.);\n`,e.compilationString+="#endif\n",e.compilationString+="#ifdef UV1\n",e.compilationString+=`${this._declareOutput(l,e)} = ${r.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${this._declareOutput(l,e)} = vec2(0., 0.);\n`,e.compilationString+="#endif\n",this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}}ee("BABYLON.MorphTargetsBlock",Lx);class kx extends wa{constructor(e){super(e,ba.Vertex),this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerOutput("direction",xa.Vector3),this.registerOutput("color",xa.Color3),this.registerOutput("intensity",xa.Float),this.registerOutput("shadowBias",xa.Float),this.registerOutput("shadowNormalBias",xa.Float),this.registerOutput("shadowDepthScale",xa.Float),this.registerOutput("shadowDepthRange",xa.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let s=this.light;const r=t.getScene();if(!s&&r.lights.length&&(s=this.light=r.lights[0],this._forcePrepareDefines=!0),!s||!s.isEnabled)return e.setFloat3(this._lightDataUniformName,0,0,0),void e.setFloat4(this._lightColorUniformName,0,0,0,0);s.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,s.diffuse,s.intensity);const n=s.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(n?e.setFloat3(this._lightShadowUniformName,n.bias,n.normalBias,n.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange)if(n&&r.activeCamera){const t=s;e.setFloat2(this._lightShadowExtraUniformName,t.getDepthMinZ(r.activeCamera),t.getDepthMinZ(r.activeCamera)+t.getDepthMaxZ(r.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;const s=this.light;i.setValue(this._lightTypeDefineName,!!(s&&s instanceof ov),!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=this.direction,i=this.color,s=this.intensity,r=this.shadowBias,n=this.shadowNormalBias,o=this.shadowDepthScale,a=this.shadowDepthRange;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+=`#ifdef ${this._lightTypeDefineName}\n`,e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});\n`,e.compilationString+="#else\n",e.compilationString+=this._declareOutput(t,e)+` = ${this._lightDataUniformName};\n`,e.compilationString+="#endif\n",e.compilationString+=this._declareOutput(i,e)+` = ${this._lightColorUniformName}.rgb;\n`,e.compilationString+=this._declareOutput(s,e)+` = ${this._lightColorUniformName}.a;\n`,(r.hasEndpoints||n.hasEndpoints||o.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,"vec3"),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${this._lightShadowUniformName}.x;\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${this._lightShadowUniformName}.y;\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${this._lightShadowUniformName}.z;\n`)),a.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,"vec2"),e.compilationString+=this._declareOutput(a,e)+` = ${this._lightShadowUniformName};\n`),this}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId))}}ee("BABYLON.LightInformationBlock",kx);class Vx extends wa{constructor(e){super(e,ba.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",xa.AutoDetect),this.registerOutput("output",xa.Color4),this.registerOutput("rgb",xa.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Color4|xa.Vector3|xa.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");const t=this.color,i=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),t.connectedPoint?.isConnected&&(t.connectedPoint.type===xa.Color4||t.connectedPoint.type===xa.Vector4?e.compilationString+=`${this._declareOutput(i,e)} = ${t.associatedVariableName};\n`:e.compilationString+=`${this._declareOutput(i,e)} = vec4(${t.associatedVariableName}, 1.0);\n`,e.compilationString+="#ifdef IMAGEPROCESSINGPOSTPROCESS\n",this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);\n`),e.compilationString+="#else\n",e.compilationString+="#ifdef IMAGEPROCESSING\n",this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);\n`),e.compilationString+=`${i.associatedVariableName} = applyImageProcessing(${i.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+="#endif\n",this.rgb.hasEndpoints&&(e.compilationString+=this._declareOutput(this.rgb,e)+` = ${this.output.associatedVariableName}.xyz;\n`)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\n`,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertInputToLinearSpace=e.convertInputToLinearSpace??!0}}qe([Ba("Convert input to linear space",Sa.Boolean,"ADVANCED")],Vx.prototype,"convertInputToLinearSpace",void 0),ee("BABYLON.ImageProcessingBlock",Vx);class Ux extends wa{constructor(e){super(e,ba.Fragment,!0),this.registerInput("normal",xa.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(xa.Color4|xa.Vector4|xa.Vector3),this.registerInput("tangent",xa.Vector4,!1),this.registerInput("world",xa.Matrix,!1),this.registerOutput("TBN",xa.Object,ba.Fragment,new Nx("TBN",this,ya.Output,Ux,"TBNBlock")),this.registerOutput("row0",xa.Vector3,ba.Fragment),this.registerOutput("row1",xa.Vector3,ba.Fragment),this.registerOutput("row2",xa.Vector3,ba.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return ba.Fragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===Ea.World&&t(e)));i||(i=new Wa("world"),i.setAsSystemValue(Ea.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Wa("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===xa.Vector4&&t(e)));i||(i=new Wa("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){const s=this.normal,r=this.tangent;let n=s.isConnected;s.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(s.connectInputBlock?.name)&&(n=!1);let o=r.isConnected;r.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(r.connectInputBlock?.name)&&(o=!1);const a=n&&o;i.setValue("TBNBLOCK",a,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,a=this.row2;return e.target===ba.Fragment&&(e.compilationString+=`\n // ${this.name}\n vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz;\n vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz);\n vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n mat3 ${r.associatedVariableName} = mat3(${s.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal);\n `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]);\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]);\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]);\n`),e.sharedData.blocksWithDefines.push(this)),this}}ee("BABYLON.TBNBlock",Ux);class Gx extends wa{constructor(e){super(e,ba.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",xa.Vector4,!1),this.registerInput("worldNormal",xa.Vector4,!1),this.registerInput("worldTangent",xa.Vector4,!0),this.registerInput("uv",xa.Vector2,!1),this.registerInput("normalMapColor",xa.Color3,!1),this.registerInput("strength",xa.Float,!1),this.registerInput("viewDirection",xa.Vector3,!0),this.registerInput("parallaxScale",xa.Float,!0),this.registerInput("parallaxHeight",xa.Float,!0),this.registerInput("TBN",xa.Object,!0,ba.VertexAndFragment,new Nx("TBN",this,ya.Input,Ux,"TBNBlock")),this.registerInput("world",xa.Matrix,!0),this.registerOutput("output",xa.Vector4),this.registerOutput("uvOffset",xa.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Wa("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Wa("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let o=null;this.normalMapColor.connectedPoint&&(o=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const a=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const c={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},u=this.TBN;u.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n mat3 vTBN = ${u.associatedVariableName};\n #endif\n `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${r.associatedVariableName}.xyz);\n`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz);\n`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`,e.compilationString+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\n"),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[c,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const d=a&&o?`texture2D(${o}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${a&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${a?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:a?this.viewDirection.associatedVariableName:"vec3(0.)"},c]}),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}qe([Ba("Invert X axis",Sa.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Gx.prototype,"invertX",void 0),qe([Ba("Invert Y axis",Sa.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Gx.prototype,"invertY",void 0),qe([Ba("Use parallax occlusion",Sa.Boolean)],Gx.prototype,"useParallaxOcclusion",void 0),qe([Ba("Object Space Mode",Sa.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Gx.prototype,"useObjectSpaceNormalMap",void 0),ee("BABYLON.PerturbNormalBlock",Gx);class zx extends wa{constructor(e){super(e,ba.Fragment,!0),this.registerInput("value",xa.Float,!0),this.registerInput("cutoff",xa.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard;\n`,this}}ee("BABYLON.DiscardBlock",zx);class Wx extends wa{constructor(e){super(e,ba.Fragment),this.registerOutput("output",xa.Float,ba.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===ba.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+" = gl_FrontFacing ? 1.0 : 0.0;\n",this}}ee("BABYLON.FrontFacingBlock",Wx);class Hx extends wa{constructor(e){super(e,ba.Fragment),this.registerInput("input",xa.AutoDetect,!1),this.registerOutput("dx",xa.BasedOnInput),this.registerOutput("dy",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName});\n`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName});\n`),this}}ee("BABYLON.DerivativeBlock",Hx);class Xx extends wa{constructor(e){super(e,ba.Fragment),this.registerOutput("xy",xa.Vector2,ba.Fragment),this.registerOutput("xyz",xa.Vector3,ba.Fragment),this.registerOutput("xyzw",xa.Vector4,ba.Fragment),this.registerOutput("x",xa.Float,ba.Fragment),this.registerOutput("y",xa.Float,ba.Fragment),this.registerOutput("z",xa.Float,ba.Fragment),this.registerOutput("w",xa.Float,ba.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(const i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name};\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===ba.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}ee("BABYLON.FragCoordBlock",Xx);class Yx extends wa{constructor(e){super(e,ba.Fragment),this.registerOutput("xy",xa.Vector2,ba.Fragment),this.registerOutput("x",xa.Float,ba.Fragment),this.registerOutput("y",xa.Float,ba.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const s of this._outputs)s.hasEndpoints&&(i+=`${this._declareOutput(s,e)} = ${t}.${s.name};\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===ba.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}}ee("BABYLON.ScreenSizeBlock",Yx);class Qx extends wa{constructor(e){super(e,ba.Fragment),this.registerInput("vector",xa.AutoDetect),this.registerInput("worldViewProjection",xa.Matrix),this.registerOutput("output",xa.Vector2),this.registerOutput("x",xa.Float),this.registerOutput("y",xa.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.WorldViewProjection&&t(e)));i||(i=new Wa("worldViewProjection"),i.setAsSystemValue(Ea.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case xa.Vector3:e.compilationString+=`vec4 ${r} = ${s} * vec4(${t.associatedVariableName}, 1.0);\n`;break;case xa.Vector4:e.compilationString+=`vec4 ${r} = ${s} * ${t.associatedVariableName};\n`}return e.compilationString+=`${r}.xy /= ${r}.w;`,e.compilationString+=`${r}.xy = ${r}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${r}.xy;\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${r}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${r}.y;\n`),this}}ee("BABYLON.ScreenSpaceBlock",Qx);class jx extends wa{constructor(e){super(e,ba.Fragment),this.registerInput("input",xa.Vector2),this.registerInput("strength",xa.Float),this.registerInput("center",xa.Vector2),this.registerInput("offset",xa.Vector2),this.registerOutput("output",xa.Vector2),this.registerOutput("x",xa.Float),this.registerOutput("y",xa.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Wa("center");e.value=new ue(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Wa("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Wa("offset");e.value=new ue(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=`\n vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n float ${i} = ${this.strength.associatedVariableName} * length(${t});\n float ${s} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n float ${r} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n vec2 ${n} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n};\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y;\n`),this}}ee("BABYLON.TwirlBlock",jx);class Kx extends wa{constructor(e){super(e,ba.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",xa.Float),this.registerInput("worldPosition",xa.Vector3),this.registerInput("worldNormal",xa.Vector3),this.registerInput("worldTangent",xa.AutoDetect,!0),this.registerOutput("output",xa.Vector4),this.registerOutput("xyz",xa.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||we.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(normal, tangent);\n mat3 TBN = mat3(tangent, biTangent, normal);\n ",s=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ",r=`\n vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {\n ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""}\n ${this.automaticNormalizationNormal?"normal = normalize(normal);":""}\n ${i}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(normal, worlddX);\n vec3 crossY = cross(normal, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * normal) - inToNormal);\n ${s}\n return vec4(result, 0.);\n }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",r,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName});\n`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}qe([Ba("Generate in world space instead of tangent space",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kx.prototype,"generateInWorldSpace",void 0),qe([Ba("Force normalization for the worldNormal input",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kx.prototype,"automaticNormalizationNormal",void 0),qe([Ba("Force normalization for the worldTangent input",Sa.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kx.prototype,"automaticNormalizationTangent",void 0),ee("BABYLON.HeightToNormalBlock",Kx);class $x extends wa{constructor(e){super(e,ba.Fragment,!0),this.registerInput("depth",xa.Float,!0),this.registerInput("worldPos",xa.Vector4,!0),this.registerInput("viewProjection",xa.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName};\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n float v = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n gl_FragDepth = v;\n \n `:we.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}ee("BABYLON.FragDepthBlock",$x);class qx extends wa{constructor(e){super(e,ba.Fragment),this.registerInput("worldPosition",xa.Vector4,!1),this.registerInput("viewProjection",xa.Matrix,!1),this.registerInput("worldNormal",xa.AutoDetect,!0),this.registerOutput("depth",xa.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};\n`,e.compilationString+="vec3 vPositionWSM;\n",e.compilationString+="float vDepthMetricSM = 0.0;\n",e.compilationString+="float zSM;\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.);\n`,this}}ee("BABYLON.ShadowMapBlock",qx);class Zx extends wa{constructor(e){super(e,ba.Fragment,!0),this.registerInput("viewDepth",xa.Float,!0),this.registerInput("worldPosition",xa.AutoDetect,!0),this.registerInput("viewNormal",xa.AutoDetect,!0),this.registerInput("reflectivity",xa.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(xa.Vector3|xa.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(xa.Vector3|xa.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(xa.Vector3|xa.Vector4|xa.Color3|xa.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth,r=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="#ifdef PREPASS_DEPTH\r\n",s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=" gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_POSITION\r\n",t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===xa.Vector4?t.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_NORMAL\r\n",i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===xa.Vector4?i.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===xa.Vector4?r.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this}}ee("BABYLON.PrePassOutputBlock",Zx);class Jx extends wa{constructor(e){super(e,ba.VertexAndFragment,!1),this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerInput("view",xa.Matrix,!1,ba.Vertex),this.registerInput("input",xa.AutoDetect,!1,ba.Fragment),this.registerInput("fogColor",xa.AutoDetect,!1,ba.Fragment),this.registerOutput("output",xa.Color3,ba.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.View&&t(e)));i||(i=new Wa("view"),i.setAsSystemValue(Ea.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.FogColor&&t(e)));i||(i=new Wa("fogColor",void 0,xa.Color3),i.setAsSystemValue(Ea.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&$n(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===ba.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});const t=e._getFreeVariableName("fog"),i=this.input,s=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const r=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+="#ifdef FOG\n",e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});\n`,e.compilationString+=this._declareOutput(r,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${s.associatedVariableName}.rgb;\n`,e.compilationString+=`#else\n${this._declareOutput(r,e)} = ${i.associatedVariableName}.rgb;\n`,e.compilationString+="#endif\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\n`}return this}}ee("BABYLON.FogBlock",Jx);class eb extends wa{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,we.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ba.Fragment:ba.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ba.Fragment:ba.Vertex}constructor(e){super(e,ba.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerInput("worldNormal",xa.Vector4,!1,ba.Fragment),this.registerInput("cameraPosition",xa.Vector3,!1,ba.Fragment),this.registerInput("glossiness",xa.Float,!0,ba.Fragment),this.registerInput("glossPower",xa.Float,!0,ba.Fragment),this.registerInput("diffuseColor",xa.Color3,!0,ba.Fragment),this.registerInput("specularColor",xa.Color3,!0,ba.Fragment),this.registerInput("view",xa.Matrix,!0),this.registerOutput("diffuseOutput",xa.Color3,ba.Fragment),this.registerOutput("specularOutput",xa.Color3,ba.Fragment),this.registerOutput("shadow",xa.Float,ba.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.CameraPosition&&t(e)));i||(i=new Wa("cameraPosition"),i.setAsSystemValue(Ea.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Jn(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else Zn(s,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;ho(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Xn(this.light,this._lightId,s,e,!0):Yn(s,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,"vec4")&&(e.compilationString+=`${s} = ${t.associatedVariableName};\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==ba.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=`//${this.name}`,i=this.worldPosition;let s=i.associatedVariableName;this.generateOnlyFragmentCode?(s=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${s};\n`,t),e.compilationString+=`${s} = ${i.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):s="v_"+s+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${s});\n`),e.compilationString+="lightingInfo info;\n",e.compilationString+="float shadow = 1.;\n",e.compilationString+="float aggShadow = 0.;\n",e.compilationString+="float numLights = 0.;\n",e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\n`,e.compilationString+="vec3 diffuseBase = vec3(0., 0., 0.);\n",e.compilationString+="vec3 specularBase = vec3(0., 0., 0.);\n",e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:s+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${s}.xyz`}),0===this._lightId&&(e.compilationString+="aggShadow = aggShadow / numLights;\n");const r=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(r,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\n`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\n`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+" = aggShadow;\n"),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}qe([Ba("Generate only fragment code",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:eb._OnGenerateOnlyFragmentCodeChanged}})],eb.prototype,"generateOnlyFragmentCode",void 0),ee("BABYLON.LightBlock",eb);class tb extends wa{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??se.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,ba.VertexAndFragment),this.registerOutput("source",xa.Object,ba.VertexAndFragment,new Nx("source",this,ya.Output,tb,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===ba.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Tl.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}ee("BABYLON.ImageSourceBlock",tb);class ib extends wa{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??se.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _IsPrePassTextureBlock(e){return"PrePassTextureBlock"===e?.getClassName()}get _isSourcePrePass(){return ib._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!ib._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??se.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??se.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?ba.Fragment:ba.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",xa.AutoDetect,!1,ba.VertexAndFragment),this.registerInput("source",xa.Object,!0,ba.VertexAndFragment,new Nx("source",this,ya.Input,tb,"ImageSourceBlock")),this.registerInput("layer",xa.Float,!0),this.registerInput("lod",xa.Float,!0),this.registerOutput("rgba",xa.Color4,ba.Neutral),this.registerOutput("rgb",xa.Color3,ba.Neutral),this.registerOutput("r",xa.Float,ba.Neutral),this.registerOutput("g",xa.Float,ba.Neutral),this.registerOutput("b",xa.Float,ba.Neutral),this.registerOutput("a",xa.Float,ba.Neutral),this.registerOutput("level",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return ba.Fragment;if(!this.uv.isConnected)return ba.VertexAndFragment;if(this.uv.sourceBlock.isInput)return ba.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===ba.Fragment)return ba.Fragment;if(e.target===ba.Vertex)return ba.VertexAndFragment;if(e.target===ba.Neutral||e.target===ba.VertexAndFragment){const t=e.ownerBlock;if(t.target===ba.Fragment)return ba.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return ba.VertexAndFragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected)if(e.mode===il.PostProcess){const i=e.getBlockByPredicate((e=>"uv"===e.name&&t(e)));i&&i.connectTo(this)}else{const i=e.mode===il.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===i&&t(e)));s||(s=new Wa("uv"),s.setAsAttribute(i)),s.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==ba.Fragment}_injectVertexCode(e){const t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0));\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,e.compilationString+="#endif\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){let t=e;const i=this._texture?._texture?.is2DArray??!1,s=this._texture?._texture?.is3D??!1;return(i||s)&&(t=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),t}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){const t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix});\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix});\n`,e.compilationString+="#endif\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ba.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==ba.Fragment?this._generateTextureLookup(e):e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix});\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ba.Fragment)return;return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===ba.Fragment)return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i);let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===ba.Vertex||this._fragmentOnly||e.target===ba.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===ba.Fragment||this._isMixed&&e.target===ba.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==ba.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&(this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!Tl.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}ee("BABYLON.TextureBlock",ib);class sb extends wa{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??se.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ba.Fragment:ba.VertexAndFragment)}constructor(e){super(e,ba.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Wa("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.World&&t(e)));i||(i=new Wa("world"),i.setAsSystemValue(Ea.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.View&&t(e)));i||(i=new Wa("view"),i.setAsSystemValue(Ea.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();s&&s.getTextureMatrix&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===s.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===s.coordinatesMode,!0),i.setValue(this._defineCubicName,3===s.coordinatesMode||6===s.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===s.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===s.coordinatesMode,!0),i.setValue(this._definePlanarName,2===s.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===s.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===s.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,s){const r=this._getTexture();if(i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize)){const t=r;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===ba.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`,t+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\n`,t+="#endif\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${r});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${r});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\n`;return s||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\n`,i+="\n #else\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\n`,i+="#endif\n",i}writeOutputs(e,t){let i="";if(e.target===ba.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${this._declareOutput(s,e)} = ${t}.${s.name};\n`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Tl.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=mm.Parse(e.texture,t,i):this.texture=Vo.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}qe([Ba("Generate only fragment code",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:sb._OnGenerateOnlyFragmentCodeChanged}})],sb.prototype,"generateOnlyFragmentCode",void 0),ee("BABYLON.ReflectionTextureBaseBlock",sb);class rb extends sb{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,we.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,we.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?ba.Fragment:ba.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ba.Fragment:ba.Vertex}constructor(e){super(e),this.registerInput("position",xa.AutoDetect,!1,ba.Vertex),this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerInput("worldNormal",xa.Vector4,!1,ba.Fragment),this.registerInput("world",xa.Matrix,!1,ba.Vertex),this.registerInput("cameraPosition",xa.Vector3,!1,ba.Fragment),this.registerInput("view",xa.Matrix,!1,ba.Fragment),this.registerOutput("rgb",xa.Color3,ba.Fragment),this.registerOutput("rgba",xa.Color4,ba.Fragment),this.registerOutput("r",xa.Float,ba.Fragment),this.registerOutput("g",xa.Float,ba.Fragment),this.registerOutput("b",xa.Float,ba.Fragment),this.registerOutput("a",xa.Float,ba.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=(()=>!0)){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.CameraPosition&&t(e)));i||(i=new Wa("cameraPosition"),i.setAsSystemValue(Ea.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==ba.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}ee("BABYLON.ReflectionTextureBlock",rb);class nb extends wa{constructor(e){super(e,ba.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",xa.AutoDetect,!1,ba.VertexAndFragment),this.registerOutput("depth",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?ba.VertexAndFragment:ba.Fragment:ba.VertexAndFragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===xa.Vector3?"3":t.type===xa.Vector4?"4":"2"))),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ba.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}else this.uv.ownerBlock.target!==ba.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ba.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target,ba.Fragment,e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==ba.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.isConnectedInFragmentShader))){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}qe([Ba("Use non linear depth",Sa.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],nb.prototype,"useNonLinearDepth",void 0),qe([Ba("Store Camera space Z",Sa.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],nb.prototype,"storeCameraSpaceZ",void 0),qe([Ba("Force 32 bits float",Sa.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e?.disableDepthRenderer()}})],nb.prototype,"force32itsFloat",void 0),ee("BABYLON.SceneDepthBlock",nb);class ob extends wa{constructor(e){super(e,ba.VertexAndFragment,!0),this.registerInput("worldPosition",xa.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return ba.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const s=e.getScene(),r=!!(t.clipPlane??s.clipPlane),n=!!(t.clipPlane2??s.clipPlane2),o=!!(t.clipPlane3??s.clipPlane3),a=!!(t.clipPlane4??s.clipPlane4),l=!!(t.clipPlane5??s.clipPlane5),h=!!(t.clipPlane6??s.clipPlane6);i.setValue("CLIPPLANE",r,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",a,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){i&&In(e,t,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==ba.Fragment){const i=this.worldPosition;return e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),void e._emitUniformFromString("vClipPlane6","vec4")}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}ee("BABYLON.ClipPlanesBlock",ob);class ab extends wa{get texture(){return null}set texture(e){}constructor(e,t=ba.VertexAndFragment){super(e,t,!1),this.registerOutput("position",xa.Object,ba.VertexAndFragment,new Nx("position",this,ya.Output,tb,"ImageSourceBlock")),this.registerOutput("depth",xa.Object,ba.VertexAndFragment,new Nx("depth",this,ya.Output,tb,"ImageSourceBlock")),this.registerOutput("normal",xa.Object,ba.VertexAndFragment,new Nx("normal",this,ya.Output,tb,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==ba.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const i=t.getScene().enablePrePassRenderer();if(!i)return;const s=i.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[i.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[i.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[i.getIndex(6)]))}}ee("BABYLON.PrePassTextureBlock",ab);class lb extends wa{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==ba.VertexAndFragment)return t.target;if(e.connectedPoint.target!==ba.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,ba.Neutral),this._endpoints=[],this.registerInput("input",xa.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some((e=>e.output.isConnectedInFragmentShader))}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}ee("BABYLON.NodeMaterialTeleportInBlock",lb);class hb extends wa{constructor(e){super(e,ba.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",xa.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName};\n`)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}ee("BABYLON.NodeMaterialTeleportOutBlock",hb);class cb extends el{constructor(e){super(e)}getClassName(){return"AddBlock"}_buildBlock(e){return super._buildBlock(e),e.compilationString+=this._declareOutput(this.output,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\n`,this}}ee("BABYLON.AddBlock",cb);class ub extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.AutoDetect),this.registerInput("factor",xa.Float),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\n`,this}}ee("BABYLON.ScaleBlock",ub);class db extends wa{constructor(e){super(e,ba.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}qe([Ba("Minimum",Sa.Float)],db.prototype,"minimum",void 0),qe([Ba("Maximum",Sa.Float)],db.prototype,"maximum",void 0),ee("BABYLON.ClampBlock",db);class _b extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[0].excludedConnectionPointTypes.push(xa.Vector2),this._inputs[1].excludedConnectionPointTypes.push(xa.Float),this._inputs[1].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xa.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\n`,this}}ee("BABYLON.CrossBlock",_b);class pb extends wa{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),this._outputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=this._declareOutput(t,e)+";\n"})),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=t.connectedPoint?.ownerBlock?.samplerName??t.associatedVariableName:e.compilationString+=t.associatedVariableName,s=!0})),this._outputs.forEach(((t,i)=>{(i>0||s)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=ba[e.target],e.inParameters?.forEach(((e,t)=>{const i=xa[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,xa.Object,!0,ba.VertexAndFragment,new Nx(e.name,this,ya.Input,tb,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),e.outParameters?.forEach(((e,t)=>{this.registerOutput(e.name,xa[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),e.inLinkedConnectionTypes?.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.CameraPosition&&t(e)));i||(i=new Wa("cameraPosition"),i.setAsSystemValue(Ea.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\n`,this}}ee("BABYLON.ViewDirectionBlock",Cb);class Eb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("worldNormal",xa.Vector4),this.registerInput("viewDirection",xa.Vector3),this.registerInput("bias",xa.Float),this.registerInput("power",xa.Float),this.registerOutput("fresnel",xa.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new Cb("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Wa("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Wa("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}ee("BABYLON.FresnelBlock",Eb);class Ab extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}ee("BABYLON.MaxBlock",Ab);class Pb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}ee("BABYLON.MinBlock",Pb);class Rb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xa.Float),this._inputs[1].excludedConnectionPointTypes.push(xa.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\n`,this}}ee("BABYLON.DistanceBlock",Rb);class Ib extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerOutput("output",xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName});\n`,this}}ee("BABYLON.LengthBlock",Ib);class Mb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName};\n`,this}}ee("BABYLON.NegateBlock",Mb);class Ob extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerInput("power",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}ee("BABYLON.PowBlock",Ob);class Db extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("seed",xa.AutoDetect),this.registerOutput("output",xa.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Vector2|xa.Vector3|xa.Vector4|xa.Color3|xa.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy);\n`,this}}ee("BABYLON.RandomNumberBlock",Db);class wb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("x",xa.Float),this.registerInput("y",xa.Float),this.registerOutput("output",xa.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`,this}}ee("BABYLON.ArcTan2Block",wb);class Nb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerInput("edge0",xa.Float),this.registerInput("edge1",xa.Float),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName});\n`,this}}ee("BABYLON.SmoothStepBlock",Nb);class Fb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===xa.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName});\n`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName};\n`,this}}ee("BABYLON.ReciprocalBlock",Fb);class Bb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerInput("reference",xa.AutoDetect),this.registerInput("distance",xa.Float),this.registerInput("replacement",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(xa.Float),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xa.Float),this._inputs[1].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[3].excludedConnectionPointTypes.push(xa.Float),this._inputs[3].excludedConnectionPointTypes.push(xa.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+";\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\n`,e.compilationString+="} else {\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\n`,e.compilationString+="}\n",this}}ee("BABYLON.ReplaceColorBlock",Bb);class Lb extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("value",xa.AutoDetect),this.registerInput("steps",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(xa.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\n`,this}}var kb;ee("BABYLON.PosterizeBlock",Lb),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(kb||(kb={}));class Vb extends wa{constructor(e){super(e,ba.Neutral),this.kind=kb.SawTooth,this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case kb.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`;break;case kb.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`;break;case kb.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}ee("BABYLON.WaveBlock",Vb);class Ub{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class Gb extends wa{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,ba.Neutral),this.colorSteps=[new Ub(0,Ce.Black()),new Ub(1,Ce.White())],this.onValueChangedObservable=new X,this.registerInput("gradient",xa.AutoDetect),this.registerOutput("output",xa.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Float|xa.Vector2|xa.Vector3|xa.Vector4|xa.Color3|xa.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){const t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=this._declareOutput(t,e)+" = vec3(0., 0., 0.);\n");const i=e._getFreeVariableName("gradientTempColor"),s=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)};\n`,e.compilationString+=`float ${s};\n`;let r=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==xa.Float&&(r+=".x");for(let t=1;t!0)){if(!this.intensity.isConnected){const e=new Wa("Refraction intensity",ba.Fragment,xa.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.View&&t(e)));i||(i=new Wa("view"),i.setAsSystemValue(Ea.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){super.bind(e,t,i);const s=this._getTexture();if(!s)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),e.setMatrix(this._refractionMatrixName,s.getRefractionTextureMatrix());let r=1;s.isCube||s.depth&&(r=s.depth);const n=this.volumeIndexOfRefraction.connectInputBlock?.value??this.indexOfRefractionConnectionPoint.connectInputBlock?.value??1.5;e.setFloat4(this._vRefractionInfosName,s.level,1/n,r,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset,1/n);const o=s.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,xe.Log2(o)),s.boundingBoxSize){const t=s;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=mm.Parse(e.texture,t,i):this.texture=Vo.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}qe([Ba("Link refraction to transparency",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],tT.prototype,"linkRefractionWithTransparency",void 0),qe([Ba("Invert refraction Y",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],tT.prototype,"invertRefractionY",void 0),qe([Ba("Use thickness as depth",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],tT.prototype,"useThicknessAsDepth",void 0),ee("BABYLON.RefractionBlock",tT);class iT extends wa{constructor(e){super(e,ba.Fragment),this._isUnique=!0,this.registerInput("thickness",xa.Float,!1,ba.Fragment),this.registerInput("tintColor",xa.Color3,!0,ba.Fragment),this.registerInput("translucencyIntensity",xa.Float,!0,ba.Fragment),this.registerInput("translucencyDiffusionDist",xa.Color3,!0,ba.Fragment),this.registerInput("refraction",xa.Object,!0,ba.Fragment,new Nx("refraction",this,ya.Input,tT,"RefractionBlock")),this.registerInput("dispersion",xa.Float,!0,ba.Fragment),this.registerOutput("subsurface",xa.Object,ba.Fragment,new Nx("subsurface",this,ya.Output,iT,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Wa("SubSurface thickness",ba.Fragment,xa.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,s){let r="";const n=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",a=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",l=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t?.refraction.isConnected?t?.refraction.connectedPoint?.ownerBlock:null,c=h?.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",u=h?.intensity.isConnected?h.intensity.associatedVariableName:"1.",d=h?.view.isConnected?h.view.associatedVariableName:"",_=t?.dispersion.isConnected?t?.dispersion.associatedVariableName:"0.0";return r+=h?.getCode(e)??"",r+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${n});\n vec4 vTintColor = vec4(${o}, ${c});\n vec3 vSubSurfaceIntensity = vec3(${u}, ${a}, 0.);\n float dispersion = ${_};\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${i?._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${i?._cubeSamplerName},\n ${i?._vReflectionFilteringInfoName},\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n surfaceAlbedo,\n #endif\n #ifdef SS_REFRACTION\n ${s}.xyz,\n viewDirectionW,\n ${d},\n ${h?._vRefractionInfosName??""},\n ${h?._refractionMatrixName??""},\n ${h?._vRefractionMicrosurfaceInfosName??""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${h?._defineLODRefractionAlpha??"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${h?._defineLinearSpecularRefraction??"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n ${h?._2DSamplerName??""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${h?._vRefractionFilteringInfoName??""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #ifdef SS_DISPERSION\n dispersion,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${l},\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n`,r}_buildBlock(e){return e.target===ba.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}ee("BABYLON.SubSurfaceBlock",iT);const sT={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class rT extends wa{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,we.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ba.Fragment:ba.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ba.Fragment:ba.Vertex}constructor(e){super(e,ba.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Ce.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",xa.Vector4,!1,ba.Vertex),this.registerInput("worldNormal",xa.Vector4,!1,ba.Fragment),this.registerInput("view",xa.Matrix,!1),this.registerInput("cameraPosition",xa.Vector3,!1,ba.Fragment),this.registerInput("perturbedNormal",xa.Vector4,!0,ba.Fragment),this.registerInput("baseColor",xa.Color3,!0,ba.Fragment),this.registerInput("metallic",xa.Float,!1,ba.Fragment),this.registerInput("roughness",xa.Float,!1,ba.Fragment),this.registerInput("ambientOcc",xa.Float,!0,ba.Fragment),this.registerInput("opacity",xa.Float,!0,ba.Fragment),this.registerInput("indexOfRefraction",xa.Float,!0,ba.Fragment),this.registerInput("ambientColor",xa.Color3,!0,ba.Fragment),this.registerInput("reflection",xa.Object,!0,ba.Fragment,new Nx("reflection",this,ya.Input,Zb,"ReflectionBlock")),this.registerInput("clearcoat",xa.Object,!0,ba.Fragment,new Nx("clearcoat",this,ya.Input,Jb,"ClearCoatBlock")),this.registerInput("sheen",xa.Object,!0,ba.Fragment,new Nx("sheen",this,ya.Input,$b,"SheenBlock")),this.registerInput("subsurface",xa.Object,!0,ba.Fragment,new Nx("subsurface",this,ya.Input,iT,"SubSurfaceBlock")),this.registerInput("anisotropy",xa.Object,!0,ba.Fragment,new Nx("anisotropy",this,ya.Input,qb,"AnisotropyBlock")),this.registerInput("iridescence",xa.Object,!0,ba.Fragment,new Nx("iridescence",this,ya.Input,eT,"IridescenceBlock")),this.registerOutput("ambientClr",xa.Color3,ba.Fragment),this.registerOutput("diffuseDir",xa.Color3,ba.Fragment),this.registerOutput("specularDir",xa.Color3,ba.Fragment),this.registerOutput("clearcoatDir",xa.Color3,ba.Fragment),this.registerOutput("sheenDir",xa.Color3,ba.Fragment),this.registerOutput("diffuseInd",xa.Color3,ba.Fragment),this.registerOutput("specularInd",xa.Color3,ba.Fragment),this.registerOutput("clearcoatInd",xa.Color3,ba.Fragment),this.registerOutput("sheenInd",xa.Color3,ba.Fragment),this.registerOutput("refraction",xa.Color3,ba.Fragment),this.registerOutput("lighting",xa.Color3,ba.Fragment),this.registerOutput("shadow",xa.Float,ba.Fragment),this.registerOutput("alpha",xa.Float,ba.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.CameraPosition&&t(e)));i||(i=new Wa("cameraPosition"),i.setAsSystemValue(Ea.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Ea.View&&t(e)));i||(i=new Wa("view"),i.setAsSystemValue(Ea.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===Vm.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Vm.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const r=e.getScene();if(r.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&lc.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Jn(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else Zn(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,no(r,i)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;ho(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Xn(this.light,this._lightId,s,e,!0):Yn(s,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const r=this._scene.ambientColor;r&&e.setColor3("ambientFromScene",r);const n=s.useRightHandedSystem===(null!=s._mirroredCameraPosition);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=this.indexOfRefraction.connectInputBlock?.value??1.5,a=Math.pow((o-1)/(o+1),2);this._metallicReflectanceColor.scaleToRef(a*this._metallicF0Factor,Ae.Color3[0]);const l=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,Ae.Color3[0],l),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,"vec4")&&(e.compilationString+=`${s} = ${t.associatedVariableName};\n`);const r=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;r&&(r.viewConnectionPoint=this.view),e.compilationString+=r?.handleVertexSide(e)??"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\n",e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n`,t}_buildBlock(e){super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=Sm(this._scene));const t=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==ba.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const i=`//${this.name}`,s=this.perturbedNormal;let r=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${r};\n`,i),e.compilationString+=`${r} = ${this.worldPosition.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n",e.compilationString+="#endif\n"):r="v_"+r,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity","vec4"),t?.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}.xyz);\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\n`,e.compilationString+=`vec3 normalW = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const n=this.anisotropy.isConnected?this.anisotropy.connectedPoint?.ownerBlock:null;n&&(n.worldPositionConnectionPoint=this.worldPosition,n.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=n.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,n?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:t?._vReflectionFilteringInfoName??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?this.sheen.connectedPoint?.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"}]});const a=this.iridescence.isConnected?this.iridescence.connectedPoint?.ownerBlock:null;e.compilationString+=eT.GetCode(a),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const l=this.clearcoat.isConnected?this.clearcoat.connectedPoint?.ownerBlock:null,h=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,c=this.perturbedNormal.isConnected&&(this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected,u=this.anisotropy.isConnected&&(this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;let d=c||!this.perturbedNormal.isConnected&&u;e.compilationString+=Jb.GetCode(e,l,t,r,h,d,this.worldNormal.associatedVariableName),h&&(d=l?.worldTangent.isConnected??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:d?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const _=this.subsurface.isConnected?this.subsurface.connectedPoint?.ownerBlock:null,p=this.subsurface.isConnected?(this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock:null;p&&(p.viewConnectionPoint=this.view,p.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=iT.GetCode(e,_,t,r),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:p?._define3DName??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:p?._defineLODRefractionAlpha??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:p?._defineLinearSpecularRefraction??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:p?._defineOppositeZ??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+="#endif\n";const f=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let m=Vm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===m.indexOf(".")&&(m+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:f+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:m}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:r},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]});for(const t of this._outputs)if(t.hasEndpoints){const i=sT[t.name];if(i){const[s,r]=i;r&&(e.compilationString+=`#if ${r}\n`),e.compilationString+=`${this._declareOutput(t,e)} = ${s};\n`,r&&(e.compilationString+="#else\n",e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.);\n`,e.compilationString+="#endif\n")}else we.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}qe([Ba("Direct lights",Sa.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],rT.prototype,"directIntensity",void 0),qe([Ba("Environment lights",Sa.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],rT.prototype,"environmentIntensity",void 0),qe([Ba("Specular highlights",Sa.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],rT.prototype,"specularIntensity",void 0),qe([Ba("Light falloff",Sa.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Vm.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Vm.LIGHTFALLOFF_GLTF},{label:"Standard",value:Vm.LIGHTFALLOFF_STANDARD}]})],rT.prototype,"lightFalloff",void 0),qe([Ba("Alpha Testing",Sa.Boolean,"OPACITY")],rT.prototype,"useAlphaTest",void 0),qe([Ba("Alpha CutOff",Sa.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],rT.prototype,"alphaTestCutoff",void 0),qe([Ba("Alpha blending",Sa.Boolean,"OPACITY")],rT.prototype,"useAlphaBlending",void 0),qe([Ba("Radiance over alpha",Sa.Boolean,"RENDERING",{notifiers:{update:!0}})],rT.prototype,"useRadianceOverAlpha",void 0),qe([Ba("Specular over alpha",Sa.Boolean,"RENDERING",{notifiers:{update:!0}})],rT.prototype,"useSpecularOverAlpha",void 0),qe([Ba("Specular anti-aliasing",Sa.Boolean,"RENDERING",{notifiers:{update:!0}})],rT.prototype,"enableSpecularAntiAliasing",void 0),qe([Ba("Realtime filtering",Sa.Boolean,"RENDERING",{notifiers:{update:!0}})],rT.prototype,"realTimeFiltering",void 0),qe([Ba("Realtime filtering quality",Sa.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],rT.prototype,"realTimeFilteringQuality",void 0),qe([Ba("Energy Conservation",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"useEnergyConservation",void 0),qe([Ba("Radiance occlusion",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"useRadianceOcclusion",void 0),qe([Ba("Horizon occlusion",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"useHorizonOcclusion",void 0),qe([Ba("Unlit",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"unlit",void 0),qe([Ba("Force normal forward",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],rT.prototype,"forceNormalForward",void 0),qe([Ba("Generate only fragment code",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:rT._OnGenerateOnlyFragmentCodeChanged}})],rT.prototype,"generateOnlyFragmentCode",void 0),qe([Ba("Debug mode",Sa.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],rT.prototype,"debugMode",void 0),qe([Ba("Split position",Sa.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],rT.prototype,"debugLimit",void 0),qe([Ba("Output factor",Sa.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],rT.prototype,"debugFactor",void 0),ee("BABYLON.PBRMetallicRoughnessBlock",rT);class nT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("left",xa.AutoDetect),this.registerInput("right",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(xa.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}ee("BABYLON.ModBlock",nT);class oT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("row0",xa.Vector4),this.registerInput("row1",xa.Vector4),this.registerInput("row2",xa.Vector4),this.registerInput("row3",xa.Vector4),this.registerOutput("output",xa.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Wa("row0");e.value=new _e(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Wa("row1");e.value=new _e(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Wa("row2");e.value=new _e(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Wa("row3");e.value=new _e(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName});\n`,this}}var aT,lT,hT,cT,uT,dT;ee("BABYLON.MatrixBuilder",oT),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(aT||(aT={}));class _T extends wa{constructor(e){super(e,ba.Neutral),this.condition=aT.LessThan,this.registerInput("a",xa.Float),this.registerInput("b",xa.Float),this.registerInput("true",xa.AutoDetect,!0),this.registerInput("false",xa.AutoDetect,!0),this.registerOutput("output",xa.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=xa.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case aT.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${s};\n`;break;case aT.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${s};\n`;break;case aT.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${s};\n`;break;case aT.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${s};\n`}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${aT[this.condition]};\n`}}ee("BABYLON.ConditionalBlock",_T);class pT extends wa{constructor(e){super(e,ba.Neutral),this.octaves=6,this.registerInput("seed",xa.AutoDetect),this.registerInput("chaos",xa.AutoDetect,!0),this.registerInput("offsetX",xa.Float,!0),this.registerInput("offsetY",xa.Float,!0),this.registerInput("offsetZ",xa.Float,!0),this.registerOutput("output",xa.Float),this._inputs[0].acceptedConnectionPointTypes.push(xa.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(xa.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;const t=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode","\n\n float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise(in vec2 x, in vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise(in vec3 x, in vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }","// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,"\n float fbm(in vec2 st, in vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise(st, chaos);\n st *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm(in vec3 x, in vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n for (int i = 0; i < OCTAVES; ++i) {\n value += amplitude * cloudNoise(x, chaos);\n x = x * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }".replace(/fbm/gi,t).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const i=e._getFreeVariableName("st"),s=this.seed.connectedPoint?.type===xa.Vector2?"vec2":"vec3";e.compilationString+=`${s} ${i} = ${this.seed.associatedVariableName};\n`,this.offsetX.isConnected&&(e.compilationString+=`${i}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`),this.offsetY.isConnected&&(e.compilationString+=`${i}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`),this.offsetZ.isConnected&&"vec3"===s&&(e.compilationString+=`${i}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`);let r="";return r=this.chaos.isConnected?this.chaos.associatedVariableName:this.seed.connectedPoint?.type===xa.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${t}(${i}, ${r});\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}qe([Ba("Octaves",Sa.Int)],pT.prototype,"octaves",void 0),ee("BABYLON.CloudBlock",pT);class fT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("seed",xa.Vector2),this.registerInput("offset",xa.Float),this.registerInput("density",xa.Float),this.registerOutput("output",xa.Float),this.registerOutput("cells",xa.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 seed, float offset){\n mat2 m = mat2(15.27, 47.63, 99.41, 89.98);\n vec2 uv = fract(sin(m * seed) * 46839.32);\n return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);\n }\n ";e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 g = floor(seed * density);\n vec2 f = fract(seed * density);\n float t = 8.0;\n vec3 res = vec3(8.0, 0.0, 0.0);\n\n for(int y=-1; y<=1; y++)\n {\n for(int x=-1; x<=1; x++)\n {\n vec2 lattice = vec2(x,y);\n vec2 randomOffset = voronoiRandom(lattice + g, offset);\n float d = distance(lattice + randomOffset, f);\n if(d < res.x)\n {\n res = vec3(d, randomOffset.x, randomOffset.y);\n outValue = res.x;\n cells = res.y;\n }\n }\n }\n }\n ",e._emitFunction("voronoi",t,"// Voronoi");const i=e._getFreeVariableName("tempOutput"),s=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0;\n`,e.compilationString+=`float ${s} = 0.0;\n`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${s});\n`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i};\n`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${s};\n`),this}}ee("BABYLON.VoronoiNoiseBlock",fT);class mT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==ba.VertexAndFragment)return t.target;if(e.connectedPoint.target!==ba.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName};\n`,this}}ee("BABYLON.ElbowBlock",mT);class gT extends wa{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??se.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){return this.sourceY.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}get textureZ(){return this.sourceZ?.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){return this._getImageSourceBlock(this.sourceY)?.samplerName??null}get samplerZName(){return this._getImageSourceBlock(this.sourceZ)?.samplerName??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??se.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??se.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,ba.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",xa.AutoDetect,!1),this.registerInput("normal",xa.AutoDetect,!1),this.registerInput("sharpness",xa.Float,!0),this.registerInput("source",xa.Object,!0,ba.VertexAndFragment,new Nx("source",this,ya.Input,tb,"ImageSourceBlock")),this.registerInput("sourceY",xa.Object,!0,ba.VertexAndFragment,new Nx("sourceY",this,ya.Input,tb,"ImageSourceBlock")),t||this.registerInput("sourceZ",xa.Object,!0,ba.VertexAndFragment,new Nx("sourceZ",this,ya.Input,tb,"ImageSourceBlock")),this.registerOutput("rgba",xa.Color4,ba.Neutral),this.registerOutput("rgb",xa.Color3,ba.Neutral),this.registerOutput("r",xa.Float,ba.Neutral),this.registerOutput("g",xa.Float,ba.Neutral),this.registerOutput("b",xa.Float,ba.Neutral),this.registerOutput("a",xa.Float,ba.Neutral),this.registerOutput("level",xa.Float,ba.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(xa.Color3|xa.Vector3|xa.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,s=this.samplerZName??t,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),a=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),c=e._getFreeVariableName("uvx"),u=e._getFreeVariableName("uvy"),d=e._getFreeVariableName("uvz");e.compilationString+=`\n vec3 ${h} = ${this.normal.associatedVariableName}.xyz;\n\n vec2 ${c} = ${this.position.associatedVariableName}.yz;\n vec2 ${u} = ${this.position.associatedVariableName}.zx;\n vec2 ${d} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${c}.xy = ${c}.yx;\n\n if (${h}.x >= 0.0) {\n ${c}.x = -${c}.x;\n }\n if (${h}.y < 0.0) {\n ${u}.y = -${u}.y;\n }\n if (${h}.z < 0.0) {\n ${d}.x = -${d}.x;\n }\n `),e.compilationString+=`\n vec4 ${n} = texture2D(${t}, ${c});\n vec4 ${o} = texture2D(${i}, ${u});\n vec4 ${a} = texture2D(${s}, ${d});\n \n // blend weights\n vec3 ${l} = pow(abs(${h}), vec3(${r}));\n\n // blend and return\n vec4 ${this._tempTextureRead} = (${n}*${l}.x + ${o}*${l}.y + ${a}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); \n `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!Tl.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Vo.Parse(e.texture,t,i))}}qe([Ba("Project as cube",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],gT.prototype,"projectAsCube",void 0),ee("BABYLON.TriPlanarBlock",gT);class vT extends gT{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dpdx"),n=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),a=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),d=e._getFreeVariableName("y");e.compilationString+=`\n // grab coord derivatives for texturing\n vec3 ${r} = dFdx(${this.position.associatedVariableName}.xyz);\n vec3 ${n} = dFdy(${this.position.associatedVariableName}.xyz);\n vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ivec3 ${a} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) :\n (${o}.y>${o}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine minor axis (in x; yz are following axis)\n ivec3 ${l} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) :\n (${o}.y<${o}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine median axis (in x; yz are following axis)\n ivec3 ${h} = ivec3(3) - ${l} - ${a};\n \n // project+fetch\n vec4 ${c} = textureGrad( ${t}, vec2( ${this.position.associatedVariableName}[${a}.y], ${this.position.associatedVariableName}[${a}.z]), \n vec2(${r}[${a}.y],${r}[${a}.z]), \n vec2(${n}[${a}.y],${n}[${a}.z]) );\n vec4 ${u} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), \n vec2(${r}[${h}.y],${r}[${h}.z]),\n vec2(${n}[${h}.y],${n}[${h}.z]) );\n \n // blend factors\n vec2 ${d} = vec2(${o}[${a}.x],${o}[${h}.x]);\n // make local support\n ${d} = clamp( (${d}-0.5773)/(1.0-0.5773), 0.0, 1.0 );\n // shape transition\n ${d} = pow( ${d}, vec2(${s}/8.0) );\n // blend and return\n vec4 ${this._tempTextureRead} = (${c}*${d}.x + ${u}*${d}.y) / (${d}.x + ${d}.y);\n `}}ee("BABYLON.BiPlanarBlock",vT);class xT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.Matrix),this.registerOutput("output",xa.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName});\n`,this}}ee("BABYLON.MatrixDeterminantBlock",xT);class bT extends wa{constructor(e){super(e,ba.Neutral),this.registerInput("input",xa.Matrix),this.registerOutput("output",xa.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName});\n`,this}}ee("BABYLON.MatrixTransposeBlock",bT),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(lT||(lT={}));class TT extends wa{constructor(e){super(e,ba.Neutral),this.attributeType=lT.None,this.registerInput("input",xa.AutoDetect),this.registerInput("fallback",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{if(this.attributeType)return;const t=e.ownerBlock;if(t instanceof Wa&&t.isAttribute)switch(t.name){case"color":this.attributeType=lT.VertexColor;break;case"normal":this.attributeType=lT.Normal;break;case"tangent":this.attributeType=lT.Tangent;break;case"uv":this.attributeType=lT.UV1;break;case"uv2":this.attributeType=lT.UV2;break;case"uv3":this.attributeType=lT.UV3;break;case"uv4":this.attributeType=lT.UV4;break;case"uv5":this.attributeType=lT.UV5;break;case"uv6":this.attributeType=lT.UV6}else if(t instanceof Lx)switch(this.input.connectedPoint?.name){case"normalOutput":this.attributeType=lT.Normal;break;case"tangentOutput":this.attributeType=lT.Tangent;break;case"uvOutput":this.attributeType=lT.UV1}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case lT.VertexColor:t="VERTEXCOLOR_NME";break;case lT.Normal:t="NORMAL";break;case lT.Tangent:t="TANGENT";break;case lT.UV1:t="UV1";break;case lT.UV2:t="UV2";break;case lT.UV3:t="UV3";break;case lT.UV4:t="UV4";break;case lT.UV5:t="UV5";break;case lT.UV6:t="UV6"}const i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t}\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\n`,t&&(e.compilationString+="#else\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\n`,e.compilationString+="#endif\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??lT.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\n`,e}}qe([Ba("Attribute lookup",Sa.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:lT.None},{label:"Normal",value:lT.Normal},{label:"Tangent",value:lT.Tangent},{label:"Vertex Color",value:lT.VertexColor},{label:"UV1",value:lT.UV1},{label:"UV2",value:lT.UV2},{label:"UV3",value:lT.UV3},{label:"UV4",value:lT.UV4},{label:"UV5",value:lT.UV5},{label:"UV6",value:lT.UV6}]})],TT.prototype,"attributeType",void 0),ee("BABYLON.MeshAttributeExistsBlock",TT),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(hT||(hT={}));class yT extends wa{constructor(e){super(e,ba.Neutral),this.type=hT.EaseInOutSine,this.registerInput("input",xa.AutoDetect),this.registerOutput("output",xa.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(xa.Matrix),this._inputs[0].excludedConnectionPointTypes.push(xa.Object),this._inputs[0].excludedConnectionPointTypes.push(xa.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if("float"===t)return this._duplicateEntryDirect(e);const i=parseInt(t.replace("vec",""));let s=`\n vec${i} ret = vec${i}(0.0);\n `;for(let t=1;t<=i;t++)s+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return s+="return ret;\n",s}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="",r="";switch(this.input.type){case xa.Float:r="float";break;case xa.Vector2:r="vec2";break;case xa.Vector3:case xa.Color3:r="vec3";break;case xa.Vector4:case xa.Color4:r="vec4"}switch(s=hT[this.type]+"_"+r,this.type){case hT.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case hT.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case hT.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case hT.EaseInQuad:i="return v * v";break;case hT.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case hT.EaseInOutQuad:{const e="VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInCubic:i="return v * v * v";break;case hT.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,r);break}case hT.EaseInOutCubic:{const e="VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInQuart:i="return v * v * v * v";break;case hT.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,r);break}case hT.EaseInOutQuart:{const e="VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInQuint:i="return v * v * v * v * v";break;case hT.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,r);break}case hT.EaseInOutQuint:{const e="VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInExpo:{const e="VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)";i=this._duplicateVector(e,r);break}case hT.EaseOutExpo:{const e="VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)";i=this._duplicateVector(e,r);break}case hT.EaseInOutExpo:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,r);break}case hT.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,r);break}case hT.EaseInOutCirc:{const e="VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case hT.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,r);break}case hT.EaseInOutBack:{const e="VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0";i=this._duplicateVector(e,r);break}case hT.EaseInElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))";i=this._duplicateVector(e,r);break}case hT.EaseOutElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0";i=this._duplicateVector(e,r);break}case hT.EaseInOutElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0";i=this._duplicateVector(e,r);break}}return e._emitFunction(s,`${r} ${s}(${r} v) {${i};}\n`,""),e.compilationString+=this._declareOutput(t,e)+` = ${s}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${hT[this.type]};\n`}}ee("BABYLON.CurveBlock",yT);class ST{optimize(e,t){}}class CT{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(void 0!==i)return i.get(t)}set(e,t,i){let s=this.mm.get(e);void 0===s&&this.mm.set(e,s=new Map),s.set(t,i)}}class ET{get standalone(){return this._options?.standalone??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){return this._options?.doNotInjectCode??!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??se.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new CT,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add((e=>{const t=e.subMesh?.getMesh();t&&!this._meshes.has(t)&&this._meshes.set(t,t.onDisposeObservable.add((e=>{const t=this._subMeshToEffect.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value;t?.getMesh()===e&&(this._subMeshToEffect.delete(t),this._deleteDepthWrapperEffect(t))}}))),this._subMeshToEffect.get(e.subMesh)?.[0]!==e.effect&&(this._subMeshToEffect.set(e.subMesh,[e.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(e.subMesh))}))}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach((e=>{e.mainDrawWrapper.effect?.dispose()})),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){const s=this._subMeshToDepthWrapper.mm.get(e)?.get(t);if(!s)return null;let r=s.drawWrapper[i];return r||(r=s.drawWrapper[i]=new Fi(this._scene.getEngine()),r.setEffect(s.mainDrawWrapper.effect,s.mainDrawWrapper.defines)),r}isReadyForSubMesh(e,t,i,s,r){return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,s))&&(this._makeEffect(e,t,i,r)?.isReady()??!1)}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;e.onDisposeObservable.remove(i)}}_makeEffect(e,t,i,s){const r=this._scene.getEngine(),n=this._subMeshToEffect.get(e);if(!n)return null;const[o,a]=n;let l=this._subMeshToDepthWrapper.get(e,i);if(!l){const t=new Fi(r);t.defines=e._getDrawWrapper(a)?.defines??null,l={drawWrapper:[],mainDrawWrapper:t,depthDefines:"",token:ns()},l.drawWrapper[s]=t,this._subMeshToDepthWrapper.set(e,i,l)}const h=t.join("\n");if(l.mainDrawWrapper.effect&&h===l.depthDefines)return l.mainDrawWrapper.effect;l.depthDefines=h;const c=o.getUniformNames().slice();let u=o.vertexSourceCodeBeforeMigration,d=o.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const e=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",t=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",i=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",s="#include",r="#include";u=o.shaderLanguage===ui.GLSL?u.replace(/void\s+?main/g,`\n${r}\nvoid main`):u.replace(/@vertex/g,`\n${r}\n@vertex`),u=u.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,e),u=-1!==u.indexOf("#define SHADOWDEPTH_METRIC")?u.replace(/#define SHADOWDEPTH_METRIC/g,t):u.replace(/}\s*$/g,t+"\n}"),u=u.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const n=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,a=-1!==d.indexOf("#define SHADOWDEPTH_FRAGMENT");let l="";n?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,i):l=i+"\n",d=d.replace(/void\s+?main/g,Ti.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\nvoid main"),a?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,s):l+=s+"\n",l&&(d=d.replace(/}\s*$/g,l+"}")),c.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}l.mainDrawWrapper.effect=r.createEffect({vertexSource:u,fragmentSource:d,vertexToken:l.token,fragmentToken:l.token},{attributes:o.getAttributesNames(),uniformsNames:c,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:h+"\n"+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters(),shaderLanguage:o.shaderLanguage},r);for(let e=0;e0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof de){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach((e=>{t.push(Array.from(e))})),t}return[]}static OmitZeroLengthPredicate(e,t,i){const s=[];return t.subtract(e).lengthSquared()>0&&s.push([e,t]),i.subtract(t).lengthSquared()>0&&s.push([t,i]),e.subtract(i).lengthSquared()>0&&s.push([i,e]),0===s.length?null:s}static OmitDuplicatesPredicate(e,t,i,s){const r=[];return BT._SearchInPoints(e,t,s)||r.push([e,t]),BT._SearchInPoints(t,i,s)||r.push([t,i]),BT._SearchInPoints(i,e,s)||r.push([i,e]),0===r.length?null:r}static _SearchInPoints(e,t,i){for(const s of i)for(let i=0;i{const r=e.getVerticesData(ys.PositionKind),n=e.getIndices();if(r&&n)for(let o=0,a=0;o[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?BT.ToVector3Array(e):e;const i=ge.Vector3[0];let s=0;for(let e=0;e{e.length>t?BT.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{s.push(e)})):(s.push(e.point1),s.push(e.point2))})),s}static SegmentizeLineBySegmentCount(e,t){const i="number"==typeof e[0]?BT.ToVector3Array(e):e,s=BT.GetLineLength(i)/t;return BT.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const a=e.length;for(let t=0;t[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],a=Vd(e,t,i,s);for(const e of a){for(const t of e.paths){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,r);o.push(e)}if(n)for(const t of e.holes){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,r);o.push(e)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(4*e.length);for(let i=0,s=0;i{BT.DisposeEmptyColorsTexture()})),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const t=this._scene.activeCamera;if(!t)throw Error("GreasedLinePluginMaterial requires an active camera.");{const i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}const i=ge.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}const t=ge.Vector4[0];t.x=BT.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=ge.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=BT.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",this.colorsTexture??FT.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===dT.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return kT.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){const e={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:`\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ${uT.COLOR_MODE_SET}.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ${uT.COLOR_MODE_ADD}.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ${uT.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.);\n #endif\n if (grlColorMode == ${uT.COLOR_MODE_SET}.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ${uT.COLOR_MODE_ADD}.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ${uT.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n `}:null}dispose(){this.colorsTexture?.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&s===e.length&&!i){const t=BT.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else this.colorsTexture?.dispose(),this.colorsTexture=BT.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}else this.colorsTexture?.dispose()}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){super.parse(e,t,i);const s=e.greasedLineMaterialOptions;this.colorsTexture?.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=BT.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):BT.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){const t=e;t.colorsTexture?.dispose(),this._colors&&(t.colorsTexture=BT.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}kT.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",ee(`BABYLON.${kT.GREASED_LINE_MATERIAL_NAME}`,kT);bi.ShadersStore.greasedLinePixelShader="precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}\n";bi.ShadersStore.greasedLineVertexShader="precision highp float;\n#include\nattribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";class VT extends Yu{constructor(e,t,i){const s=[`COLOR_DISTRIBUTION_TYPE_LINE ${dT.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${dT.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${uT.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${uT.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${uT.COLOR_MODE_MULTIPLY}.`],r=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&s.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(s.push("GREASED_LINE_CAMERA_FACING"),r.push("grl_previousAndSide","grl_nextAndCounters")):(r.push("grl_slopes"),r.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:r,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:s}),this._color=Ce.White(),this._colorsDistributionType=dT.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:FT.DEFAULT_COLOR};const n=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?FT.DEFAULT_WIDTH_ATTENUATED:FT.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Ce.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??dT.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??Wo.NEAREST_NEAREST,this.colorMode=i.colorMode??uT.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new ue(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=BT.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),n.onDisposeObservable.add((()=>{BT.DisposeEmptyColorsTexture()}))}dispose(){this._colorsTexture?.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new ue(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&s===e.length&&!i){const t=BT.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else this._colorsTexture?.dispose(),this.colorsTexture=BT.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}else this._colorsTexture?.dispose()}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",BT.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",BT.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",BT.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??FT.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){const s=e.greasedLineMaterialOptions;this._colorsTexture?.dispose(),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),s.colors?this.colorsTexture=BT.CreateColorsTexture(`${this.name}-colors-texture`,s.colors,this.colorsSampling,this.getScene()):this.colorsTexture=BT.PrepareEmptyColorsTexture(t),this._cameraFacing=s.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const UT=[new Ce(.98,.26,.38),new Ce(.47,.75,.3),new Ce(0,.26,.77),new Ce(.97,.6,.76),new Ce(.19,.63,.78),new Ce(.98,.8,.6),new Ce(.65,.43,.15),new Ce(.15,.47,.22),new Ce(.67,.71,.86),new Ce(.09,.46,.56),new Ce(.8,.98,.02),new Ce(.39,.29,.13),new Ce(.53,.63,.06),new Ce(.95,.96,.41),new Ce(1,.72,.94),new Ce(.63,.08,.31),new Ce(.66,.96,.95),new Ce(.22,.14,.19),new Ce(.14,.65,.59),new Ce(.93,1,.68),new Ce(.93,.14,.44),new Ce(.47,.86,.67),new Ce(.85,.07,.78),new Ce(.53,.64,.98),new Ce(.43,.37,.56),new Ce(.71,.65,.25),new Ce(.66,.19,.01),new Ce(.94,.53,.12),new Ce(.41,.44,.44),new Ce(.24,.71,.96),new Ce(.57,.28,.56),new Ce(.44,.98,.42)];var GT;!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(GT||(GT={}));class zT extends Oa{constructor(){super(...arguments),this.DBG_MODE=GT.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class WT extends gc{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new zT;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new Ce(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Ce(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Ce(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Ce(.8,.8,.8),this.vertexColor=t.vertexColor??new Ce(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Ce(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Ce(.5,.5,.5),this._materialColor=WT.MaterialColors[WT._PluginCount++%WT.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().webGLVersion)return we.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=GT.VERTICES&&this._mode!=GT.TRIANGLES&&this._mode!=GT.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||we.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif"}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(UV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(UV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}}static Reset(){this._PluginCount=0,this.MaterialColors=UT}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){const t=e.getVerticesDataKinds(),s=e.getIndices(),r={};for(const i of t)r[i]=e.getVerticesData(i);i=function(){e.setIndices(s);for(const i of t){const t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,r[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let e=0;enew XT(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return yt.Parse((()=>new XT(e.name,t)),e,t,i)}}ee("BABYLON.GaussianSplattingMaterial",XT),Object.defineProperty(yc.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new PT(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Vm.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new PT(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Sn.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});class YT{constructor(e,t){this.radius=e,this.theta=t,this.radius=e,this.theta=t}getClassName(){return"Polar"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t}add(e){const t=new YT(0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t){return this.radius+=e,this.theta+=t,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t}subtract(e){const t=new YT(0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i){return i.radius=this.radius-e,i.theta=this.theta-t,i}subtractFromFloats(e,t){const i=new YT(0,0);return this.subtractFromFloatsToRef(e,t,i),i}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t}multiply(e){const t=new YT(0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t}divide(e){const t=new YT(0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new YT(this.radius,this.theta)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this}copyFromFloats(e,t){return this.radius=e,this.theta=t,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t}scale(e){const t=new YT(0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t){return this.radius=e,this.theta=t,this}setAll(e){return this.set(e,e),this}toVector2ToRef(e){const t=this.radius*Math.cos(this.theta),i=this.radius*Math.sin(this.theta);return e.set(t,i),e}toVector2(){const e=new ue(0,0);return this.toVector2ToRef(e)}static FromVector2ToRef(e,t){const i=Math.sign(e.y)*Math.acos(e.x/e.length());return t.radius=e.length(),t.theta=i,t}static FromVector2(e){const t=new YT(0,0);return YT.FromVector2ToRef(e,t),t}static FromArray(e){return new YT(e[0],e[1])}}class QT{constructor(e,t,i){this.radius=e,this.theta=t,this.phi=i,this.radius=e,this.theta=t,this.phi=i}getClassName(){return"Spherical"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta,this.phi]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t.phi=this.phi+e.phi,t}add(e){const t=new QT(0,0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t,i){return this.radius+=e,this.theta+=t,this.phi+=i,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t.phi=this.phi-e.phi,t}subtract(e){const t=new QT(0,0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i,s){return s.radius=this.radius-e,s.theta=this.theta-t,s.phi=this.phi-i,s}subtractFromFloats(e,t,i){const s=new QT(0,0,0);return this.subtractFromFloatsToRef(e,t,i,s),s}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t.phi=this.phi*e.phi,t}multiply(e){const t=new QT(0,0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t.phi=this.phi/e.phi,t}divide(e){const t=new QT(0,0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new QT(this.radius,this.theta,this.phi)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this.phi=e.phi,this}copyFromFloats(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t.phi=this.phi*e,t}scale(e){const t=new QT(0,0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}setAll(e){return this.set(e,e,e),this}toVector3ToRef(e){const t=this.radius*Math.sin(this.theta)*Math.cos(this.phi),i=this.radius*Math.cos(this.theta),s=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,s),e}toVector3(){const e=new de(0,0,0);return this.toVector3ToRef(e)}static FromVector3ToRef(e,t){return t.radius=e.length(),t.theta=Math.acos(e.y/t.radius),t.phi=Math.atan2(e.z,e.x),t}static FromVector3(e){const t=new QT(0,0,0);return QT.FromVector3ToRef(e,t),t}static FromArray(e){return new QT(e[0],e[1],e[2])}}class jT{constructor(e,t=2,i=3,s=1,r=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=s,this._height=r,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,s=0;for(;e>0;)i/=t,s+=i*(e%t),e=~~(e/t);return s}}function KT(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)}}`}function $T(e,t){return`{X: ${e._x.toFixed(t)} Y: ${e._y.toFixed(t)} Z: ${e._z.toFixed(t)}}`}function qT(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)} Z: ${e.z.toFixed(t)} W: ${e.w.toFixed(t)}}`}function ZT(e,t,i,s,r){let n=null,o=null,a=null;try{let l;n=new e.Decoder,o=new e.DecoderBuffer,o.Init(t,t.byteLength);const h=n.GetEncodedGeometryType(o);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=n.DecodeBufferToMesh(o,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),r=4*i,h=e._malloc(r);try{n.GetTrianglesUInt32Array(t,r,h);const o=new Uint32Array(i);o.set(new Uint32Array(e.HEAPF32.buffer,h,i)),s(o)}finally{e._free(h)}a=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=n.DecodeBufferToPointCloud(o,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());a=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=a.num_points(),u=(t,i,s,n)=>{const o=n.data_type(),a=n.num_components(),l=n.normalized(),h=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[o];if(!d)throw new Error(`Invalid data type ${o}`);const _=c*a,p=_*d.typedArrayConstructor.BYTES_PER_ELEMENT,f=e._malloc(p);try{t.GetAttributeDataArrayForAllPoints(i,n,o,p,f);const e=new d.typedArrayConstructor(d.heap.buffer,f,_);r(s,e.slice(),a,u,h,l)}finally{e._free(f)}};if(i)for(const e in i){const t=i[e],s=n.GetAttributeByUniqueId(a,t);u(n,a,e,s)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=n.GetAttributeId(a,t[e]);if(-1!==i){const t=n.GetAttribute(a,i);u(n,a,e,t)}}}return c}finally{a&&e.destroy(a),o&&e.destroy(o),n&&e.destroy(n)}}function JT(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary}),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=ZT(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,s,r,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:s,byteStride:r,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}class ey{static get DecoderAvailable(){const e=ey.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return ey._Default||(ey._Default=new ey),ey._Default}constructor(e=ey.DefaultNumWorkers){const t=ey.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,s="number"==typeof e?e:e.numWorkers,r=s&&"function"==typeof Worker&&"function"==typeof URL,n=r||!r&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?hs.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):hs.LoadFileAsync(hs.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?hs.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=o.wasmBinaryPromise.then((e=>{const t=`${ZT}(${JT})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new Jm(s,(()=>function(e,t,i){return new Promise(((s,r)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",o),r(t)},o=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",o),s(e))};e.addEventListener("error",n),e.addEventListener("message",o);const a=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:a}},[a])}))}(new Worker(i),e,o.url)))})):this._decoderModulePromise=o.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await hs.LoadBabylonScriptAsync(o.url)}return await(i=e,s=t.jsModule,new Promise((e=>{(s||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,s}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}_decodeMeshAsync(e,t,i){const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((r,n)=>{e.push(((e,o)=>{let a=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),n(t),o()},c=t=>{const s=t.data;switch(s.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),r({indices:a,attributes:l,totalVertices:s.totalVertices}),o();break;case"indices":a=s.data;break;case"attribute":l.push({kind:s.kind,data:s.data,size:s.size,byteOffset:s.byteOffset,byteStride:s.byteStride,normalized:(n=s.kind,u=s.normalized,i&&void 0!==i[n]?(u!==i[n]&&we.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):u)})}var n,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=s.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const r=[],n=ZT(e.module,s,t,(e=>{i=e}),((e,t,i,s,n,o)=>{r.push({kind:e,data:t,size:i,byteOffset:s,byteStride:n,normalized:o})}));return{indices:i,attributes:r,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const r=await this._decodeMeshAsync(i,s),n=new _n(e,t);r.indices&&n.setIndices(r.indices);for(const e of r.attributes)n.setVerticesBuffer(new ys(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,r){const n=await this._decodeMeshAsync(i,s,r),o=new _n(e,t);n.indices&&o.setIndices(n.indices);for(const e of n.attributes)o.setVerticesBuffer(new ys(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this._decodeMeshAsync(e,t),s=new cn;i.indices&&(s.indices=i.indices);for(const e of i.attributes){const t=ys.GetFloatData(e.data,e.size,ys.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);s.set(t,e.kind)}return s}}ey.Configuration={decoder:{wasmUrl:`${hs._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${hs._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${hs._DefaultCdnUrl}/draco_decoder_gltf.js`}},ey.DefaultNumWorkers=ey.GetDefaultNumWorkers(),ey._Default=null;class ty{static get Default(){return ty._Default||(ty._Default=new ty),ty._Default}constructor(){const e=ty.Configuration.decoder;this._decoderModulePromise=hs.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then((()=>{const n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,s,r),n}))}}ty.Configuration={decoder:{url:`${hs._DefaultCdnUrl}/meshopt_decoder.js`}},ty._Default=null;let iy=0;class sy{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){return new sy(this.pos.clone(),this.normal.clone(),this.uv?.clone(),this.vertColor?.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new sy(de.Lerp(this.pos,e.pos,t),de.Lerp(this.normal,e.normal,t),this.uv&&e.uv?ue.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?Ee.Lerp(this.vertColor,e.vertColor,t):void 0)}}class ry{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(0===s.lengthSquared()||0===r.lengthSquared())return null;const n=de.Normalize(de.Cross(s,r));return new ry(n,de.Dot(n,e))}clone(){return new ry(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let n=0;const o=[];let a,l;for(a=0;ary.EPSILON?1:0;n|=t,o.push(t)}switch(n){case 0:(de.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const t=[],i=[];for(a=0;a=3&&(n=new ny(t,e.shared),n.plane&&s.push(n)),i.length>=3&&(n=new ny(i,e.shared),n.plane&&r.push(n));break}}}}ry.EPSILON=1e-5;class ny{constructor(e,t){this.vertices=e,this.shared=t,this.plane=ry.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new ny(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class oy{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new oy;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map((e=>e.clone())),e}invert(){for(let e=0;ee.clone())),e.copyTransformAttributes(this),e}union(e){const t=new oy(this.clone()._polygons),i=new oy(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),ay._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new oy(this._polygons),i=new oy(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new oy(this.clone()._polygons),i=new oy(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),ay._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new oy(this._polygons),i=new oy(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new oy(this.clone()._polygons),i=new oy(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),ay._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new oy(this._polygons),i=new oy(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map((e=>{e.flip()}))}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const s=this._polygons,r=[],n=[],o=[];let a=null,l=null;const h=de.Zero(),c=de.Zero(),u=ue.Zero(),d=new Ee(0,0,0,0),_=[0,0,0],p={};let f;for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId)),this.toVertexData((e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),a=o[e.shared.meshId][e.shared.subMeshId]}),(()=>{a.indexStart=Math.min(n,a.indexStart),a.indexEnd=Math.max(n,a.indexEnd),n++})).applyToMesh(s),i){let e,t=0;s.subMeshes=[];for(const i in o){e=-1;for(const r in o[i])a=o[i][r],ln.CreateFromIndices(a.materialIndex+t,a.indexStart,a.indexEnd-a.indexStart+1,s),e=Math.max(a.materialIndex,e);t+=++e}}return s}toMesh(e,t=null,i,s){const r=this.buildMeshGeometry(e,i,s);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r}}bi.ShadersStore.meshUVSpaceRendererVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}";bi.ShadersStore.meshUVSpaceRendererPixelShader="precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";bi.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";bi.ShadersStore.meshUVSpaceRendererMaskerPixelShader="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";bi.ShadersStore.meshUVSpaceRendererFinaliserPixelShader="precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";bi.ShadersStore.meshUVSpaceRendererFinaliserVertexShader="precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}\n";class ly{static _GetShader(e){if(!e._meshUVSpaceRendererShader){const t=new Yu("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererShader?.dispose(),e._meshUVSpaceRendererShader=null})),e._meshUVSpaceRendererShader=t}return e._meshUVSpaceRendererShader}static _GetMaskShader(e){if(!e._meshUVSpaceRendererMaskShader){const t=new Yu("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"]});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererMaskShader?.dispose(),e._meshUVSpaceRendererMaskShader=null})),e._meshUVSpaceRendererMaskShader=t}return e._meshUVSpaceRendererMaskShader}static _IsRenderTargetTexture(e){return void 0!==e.renderList}constructor(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this.clearColor=new Ee(0,0,0,0),this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1,...i}}isReady(){this.texture||this._createDiffuseRTT();const e=ly._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=this._maskTexture?.isReadyForRendering()??!0,i=this._finalPostProcess?.isReady()??!0;return e&&t&&i}renderTexture(e,t,i,s,r=0){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),ly._IsRenderTargetTexture(this.texture)){const n=this._createProjectionMatrix(t,i,s,r),o=ly._GetShader(this._scene);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",n),this.texture.render()}}clear(){if(ly._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const e=this._scene.getEngine();e.bindFramebuffer(this.texture.renderTarget),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this.texture.renderTarget)}if(this._finalPostProcess?.inputTexture){const e=this._scene.getEngine();e.bindFramebuffer(this._finalPostProcess?.inputTexture),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this._finalPostProcess?.inputTexture)}}dispose(){this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,this._maskTexture?.dispose(),this._maskTexture=null,this._finalPostProcess?.dispose(),this._finalPostProcess=null}_configureUserCreatedRTT(){this._configureUserCreatedTexture=!1,ly._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,ly._GetShader(this._scene)),this.texture.onClearObservable.add((()=>{})),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,ly._GetShader(this._scene)),this.texture=e,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),e.addPostProcess(this._finalPostProcess))}_createMaskTexture(){this._maskTexture||(this._maskTexture=new pl(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,0,!1,2,void 0,void 0,void 0,6),this._maskTexture.clearColor=new Ee(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,ly._GetMaskShader(this._scene)),this._maskTexture.refreshRate=pl.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new qa(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,1,this._scene.getEngine(),!1,null,this._options.textureType),this._finalPostProcess.onApplyObservable.add((e=>{e.setTexture("maskTextureSampler",this._maskTexture),e.setFloat2("textureSize",this._options.width,this._options.height)})))}_createRenderTargetTexture(e,t){const i=new pl(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.renderParticles=!1,i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce((()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add((()=>{}))})),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,s=0){const r=-Math.atan2(t.z,t.x)-Math.PI/2,n=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,n),a=e.add(t.scale(.5*i.z)),l=fe.RotationYawPitchRoll(r,o,s).multiply(fe.Translation(a.x,a.y,a.z)),h=fe.Invert(l),c=fe.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),u=fe.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return h.multiply(c).multiply(u)}}bo._TrailMeshParser=(e,t)=>hy.Parse(e,t);class hy extends bo{constructor(e,t,i,s=1,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=s,this._length=r,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<=this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=de.Zero(),this._sectionNormalVectors[e]=de.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new cn,t=[],i=[],s=[],r=[];let n=de.Zero();n=this._generator instanceof Sn&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<=this._sectionPolygonPointsCount;e++){const i=e!==this._sectionPolygonPointsCount?e*o:0;t.push(n.x+Math.cos(i)*this.diameter,n.y+Math.sin(i)*this.diameter,n.z),r.push(e/this._sectionPolygonPointsCount,0)}for(let e=1;e<=this._length;e++){for(let i=0;i<=this._sectionPolygonPointsCount;i++){const s=i!==this._sectionPolygonPointsCount?i*o:0;t.push(n.x+Math.cos(s)*this.diameter,n.y+Math.sin(s)*this.diameter,n.z),r.push(i/this._sectionPolygonPointsCount,e/this._length)}const i=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let e=0;e<=this._sectionPolygonPointsCount;e++)s.push(i+e,i+e+this._sectionPolygonPointsCount,i+e+this._sectionPolygonPointsCount+1),s.push(i+e,i+e+this._sectionPolygonPointsCount+1,i+e+1)}cn.ComputeNormals(t,s,i),e.positions=t,e.normals=i,e.indices=s,e.uvs=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(ys.PositionKind),t=this.getVerticesData(ys.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*(this._sectionPolygonPointsCount+1);i{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,s)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,s()}))};us.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,dy.QUADRATIC,new wy(e.mesh)}}var dy,_y,py,fy,my,gy,vy,xy,by,Ty,yy,Sy,Cy,Ey,Ay,Py,Ry;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(dy||(dy={}));class Iy{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class My{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new Oy,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class Oy{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,s,r,n,o,a,l){return this.data[e]*this.data[r]*this.data[l]+this.data[i]*this.data[s]*this.data[a]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[a]-this.data[t]*this.data[s]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new Oy;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new Oy(Oy.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class Dy{constructor(e,t){this.vertexId=e,this.triangleId=t}}class wy{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=K}simplify(e,t){this._initDecimatedMesh(),us.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),s=this._triangles[t];if(s&&!(s.error[3]>i||s.deleted||s.isDirty))for(let e=0;e<3;++e)if(s.error[e]{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)continue;n.q=o.q.add(n.q),n.updatePosition(a);const c=this._references.length;r=this._updateTriangles(n,n,t,r),r=this._updateTriangles(n,o,i,r);const u=this._references.length-c;if(u<=n.triangleCount){if(u)for(let e=0;en-r<=s))}),0)};us.Run(this.decimationIterations,(e=>{n-r<=s?e.breakLoop():o(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(ys.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=e=>{if(i)for(let t=0;t{if(!s)return;const t=e+n.verticesStart,i=de.FromArray(s,3*t),r=o(i)||new My(i,this._vertices.length);r.originalOffsets.push(t),r.id===this._vertices.length&&this._vertices.push(r),a.push(r.id)}),(()=>{us.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,(e=>{if(!r)return;const t=3*(n.indexStart/3+e),i=r[t+0],s=r[t+1],o=r[t+2],l=this._vertices[a[i-n.verticesStart]],h=this._vertices[a[s-n.verticesStart]],c=this._vertices[a[o-n.verticesStart]],u=new Iy([l,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){us.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=de.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(Oy.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-de.Dot(t.normal,t._vertices[0].position)))}),(()=>{us.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,s,r;for(i=0;i{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const _=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[s.originalOffset+e];let i=s._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(s._vertices[e].id+i+p)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(ys.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(ys.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(ys.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(ys.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach((e=>{ln.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),ln.AddToMesh(v.materialIndex,p,d,_,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new bo(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,s,r){for(let n=0;n.999)return!0;const d=de.Cross(c,u).normalize();if(s[n]=!1,de.Dot(d,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let s=0;sBy.Parse(e,t);class By extends Fy{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(BT.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach((t=>{for(let i=0;i{i+=2*e.length,s+=2*(e.length-3),r+=4*e.length/3,n+=8*e.length/3}));const o=new Float32Array(i),a=i>65535?new Uint32Array(s):new Uint16Array(s),l=new Float32Array(r),h=new Float32Array(n),c=new Float32Array(n);let u=0,d=0,_=0,p=0,f=0;e.forEach((e=>{const i=BT.GetLineLengthArray(e),s=i[i.length-1];for(let i=0,s=0;s>1]/s;if(this._options.uvs)for(let e=0;eLy.Parse(e,t);class Ly extends Fy{constructor(e,t,i,s){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(BT.ConvertPoints(i.points),i,!!s)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const r=Ly._ConvertToRibbonPath(e,n.ribbonOptions,this._scene.useRightHandedSystem,i?i[t]:i);s=this._preprocess(r,s,n)}))}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const s=[],r=[],n=e[0];for(let t=0;t2)for(let e=0;e0&&(o[0]+=1,o[1]+=1),r.push(o[1]+(e%2!=0?i:0),o[0],o[2]),a&&r.push(o[0],o[1]+(e%2!=0?i:0),o[2])}else for(let e=0;ee.y&&e.x>e.z?i?Ly._RightHandedForwardReadOnlyQuaternion:Ly._LeftHandedForwardReadOnlyQuaternion:Ly._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(o,o,o),r.push(c.add(h)),n.push(c.subtract(h))}s||(r.push(a[a.length-1].add(h)),n.push(a[a.length-1].subtract(h)))}return[r,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&1!==i?.x?e.y===t.y?Ly.DIRECTION_XZ:e.z===t.z?Ly.DIRECTION_XY:Ly.DIRECTION_XZ:Ly.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];Xe.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),Xe.DeepCopy(i,s,["instance"],void 0,!0);const n=new Ly(e,this._scene,s,r);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,s=e.name,r=e.pathOptions;return new Ly(s,t,i,r)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let s=0;s{o+=e.length/3}));const a=Uy(o,t.widths??[],t.widthDistribution),l=i?.colors?Gy(o,i.colors,i.colorDistribution,i.color??FT.DEFAULT_COLOR):void 0,h={points:n,updatable:t.updatable,widths:a,lazy:t.lazy,ribbonOptions:t.ribbonOptions,uvs:t.uvs,colorPointers:t.colorPointers};if(h.ribbonOptions&&h.ribbonOptions.pointsMode===_y.POINTS_MODE_POINTS&&(h.ribbonOptions.width=i.width??h.ribbonOptions.width??FT.DEFAULT_WIDTH),t.instance)if(r=t.instance,r instanceof Ly)r.addPoints(n,h);else{const e=r.widths;if(e){const t=e.slice();for(const e of a)t.push(e);r.widths=t}else r.widths=a;if(r.addPoints(n),t.uvs){const e=r.uvs;if(e){const i=new Float32Array(e.length+t.uvs.length);i.set(e,0),i.set(t.uvs,e.length),r.uvs=i}else r.uvs=t.uvs}}else if(r=h.ribbonOptions?new Ly(e,s,h):new By(e,s,h),i){const n={materialType:i.materialType,dashCount:i.dashCount,dashOffset:i.dashOffset,dashRatio:i.dashRatio,resolution:i.resolution,sizeAttenuation:i.sizeAttenuation,useColors:i.useColors,useDash:i.useDash,visibility:i.visibility,width:i.width,color:i.color,colorMode:i.colorMode,colorsSampling:i.colorsSampling,colorDistributionType:i.colorDistributionType,colors:l,cameraFacing:!t.ribbonOptions,colorsTexture:i.colorsTexture};if(i.createAndAssignMaterial){const i=ky(e,n,s);r.material=i,t.ribbonOptions?.facesMode===py.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING&&(i.backFaceCulling=!1)}}if(l&&t.instance&&t.instance.greasedLineMaterial){const e=t.instance.greasedLineMaterial.colors;if(e){const i=e.concat(l);t.instance.greasedLineMaterial.setColors(i,r.isLazy())}}return r}function Uy(e,t,i,s=1,r=1){const n=e-t.length/2,o=[];if(n<0)return t.slice(0,2*e);if(n>0){if(t.length%2!=0&&t.push(s),i===gy.WIDTH_DISTRIBUTION_START_END){const e=Math.floor(t.length/2);for(let i=0,s=0;i0){if(i===my.COLOR_DISTRIBUTION_START_END){const e=Math.floor(t.length/2);for(let i=0;i=this._thinInstanceDataStorage.instancesCount)return!1;const s=this._thinInstanceDataStorage.matrixData;return t.copyToArray(s,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},bo.prototype.thinInstanceSetAttributeAt=function(e,t,i,s=!0){return e===ys.ColorKind&&(e=ys.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),s&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(bo.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),bo.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const s=new Ts(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(s.createVertexBuffer(e+t,4*t,4));return s},bo.prototype.thinInstanceSetBuffer=function(e,t,i=0,s=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,s),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,s))):(e===ys.ColorKind&&(e=ys.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new ys(this.getEngine(),t,e,!s,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},bo.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===ys.ColorKind&&(e=ys.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},bo.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===ys.ColorKind&&(e=ys.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},bo.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){return this.isConnected?this._connectedPoint?._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=vy.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new X,this.onDisconnectionObservable=new X,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===xy.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==vy.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?xy.Compatible:xy.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return xy.TypeIncompatible;let s=i,r=t;return this.direction===by.Input&&(s=t,r=i),s.isAnAncestorOf(r)?xy.HierarchyIssue:xy.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t0){if(!this._outputs.some((e=>e.hasEndpoints))&&!this.isDebug)return!1;this.outputs.forEach((e=>e._resetCounters()))}this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&we.Log(`Building ${this.name} [${this.getClassName()}]`);const t=zt.Now;this._buildBlock(e),this._buildExecutionTime=zt.Now-t;for(const t of this._outputs)for(const i of t.endpoints){const t=i.ownerBlock;t&&t.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((e=>{const t=this.inputs.find((t=>t.name===e.name));if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)t.value=e.value;else{const i=te(e.valueType);i&&(t.value=i.FromArray(e.value))}})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`);const r=this.getClassName();if("GeometryInputBlock"===r){const e=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e});\n`}else s+=`var ${this._codeVariableName} = new BABYLON.${r}("${this.name}");\n`;s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=te(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}qe([st("comment")],Wy.prototype,"comments",void 0);class Hy extends Wy{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",vy.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}ee("BABYLON.GeometryOutputBlock",Hy),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(Ty||(Ty={}));class Xy{constructor(){this._rotationMatrix=new fe,this._scalingMatrix=new fe,this._positionMatrix=new fe,this._scalingRotationMatrix=new fe,this._transformMatrix=new fe,this._tempVector3=new de,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case Ty.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?de.FromArray(this.geometryContext.positions,3*i):de.Zero();case Ty.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?de.FromArray(this.geometryContext.normals,3*i):de.Zero();case Ty.Colors:return this.geometryContext&&this.geometryContext.colors?_e.FromArray(this.geometryContext.colors,4*i):_e.Zero();case Ty.Tangents:return this.geometryContext&&this.geometryContext.tangents?_e.FromArray(this.geometryContext.tangents,4*i):_e.Zero();case Ty.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?ue.FromArray(this.geometryContext.uvs,2*i):ue.Zero();case Ty.UV2:return this.geometryContext&&this.geometryContext.uvs2?ue.FromArray(this.geometryContext.uvs2,2*i):ue.Zero();case Ty.UV3:return this.geometryContext&&this.geometryContext.uvs3?ue.FromArray(this.geometryContext.uvs3,2*i):ue.Zero();case Ty.UV4:return this.geometryContext&&this.geometryContext.uvs4?ue.FromArray(this.geometryContext.uvs4,2*i):ue.Zero();case Ty.UV5:return this.geometryContext&&this.geometryContext.uvs5?ue.FromArray(this.geometryContext.uvs5,2*i):ue.Zero();case Ty.UV6:return this.geometryContext&&this.geometryContext.uvs6?ue.FromArray(this.geometryContext.uvs6,2*i):ue.Zero();case Ty.VertexID:return i;case Ty.FaceID:return this.executionContext.getExecutionFaceIndex();case Ty.LoopID:return this.executionContext.getExecutionLoopIndex();case Ty.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Ty.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Ty.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case vy.Vector2:return new ue(i,i);case vy.Vector3:return new de(i,i,i);case vy.Vector4:return new _e(i,i,i,i)}return null}adaptInput(e,t,i){if(!e.isConnected)return e.value||i;const s=e.getConnectedValue(this);if(e._connectedPoint?.type===t)return s;switch(t){case vy.Vector2:return new ue(s,s);case vy.Vector3:return new de(s,s,s);case vy.Vector4:return new _e(s,s,s,s)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;for(const t of this.noContextualData)e+=`Contextual input ${Ty[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,s,r){fe.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),fe.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),fe.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${Ty[this._contextualSource]};\n`;const t=[];let i="";switch(this.type){case vy.Float:case vy.Int:i=`${this.value}`;break;case vy.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case vy.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case vy.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),this.type!==vy.Float&&this.type!==vy.Int||t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=te(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}ee("BABYLON.GeometryInputBlock",Yy);class Qy extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",vy.Float,!0,1),this.registerInput("width",vy.Float,!0,0),this.registerInput("height",vy.Float,!0,0),this.registerInput("depth",vy.Float,!0,0),this.registerInput("subdivisions",vy.Int,!0,1),this.registerInput("subdivisionsX",vy.Int,!0,0),this.registerInput("subdivisionsY",vy.Int,!0,0),this.registerInput("subdivisionsZ",vy.Int,!0,0),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new Yy("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new Yy("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new Yy("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),s=this.subdivisionsX.getConnectedValue(e),r=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),s&&(t.widthSegments=s),r&&(t.heightSegments=r),n&&(t.depthSegments=n),Tu(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Qy.prototype,"evaluateContext",void 0),ee("BABYLON.BoxBlock",Qy);class jy{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=jy._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new X,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return hs.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise((t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){const i=e&&e.editorURL?e.editorURL:jy.EditorURL;hs.LoadBabylonScript(i,(()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const s=zt.Now;this._initializeBlock(this.outputBlock,i);const r=new Xy;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=jy._BuildIdGenerator++),this._buildExecutionTime=zt.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new bo(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const t of e.blocks){const e=te(t.customType);if(e){const s=new e;s._deserialize(t),i[t.id]=s,this.attachedBlocks.push(s)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,s=t._tempEntryPointUniqueId;if(s){const e=i[s];e&&e.attachToEndpoint(t)}}for(let s=0;se.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const e of s)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const e in i)r[e]=i[e].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+="// Connections\n",s+=this.outputBlock._dumpCodeForOutputConnections(e),s+="// Output nodes\n",s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`,s+="nodeGeometry.build();\n"),s}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new Qy("Box");e.autoConfigure();const t=new Hy("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=yt.Clone((()=>new jy(e)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:yt.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new jy(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=yt.Parse((()=>new jy(e.name)),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(jy.CreateDefault("blank")):new Promise(((s,r)=>{const n=new At;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(o.nodeGeometry);t||(t=yt.Parse((()=>new jy(e)),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),s(t)}catch(e){r(e)}}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}jy._BuildIdGenerator=0,jy.EditorURL=`${hs._DefaultCdnUrl}/v${gn.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,jy.SnippetUrl="https://snippet.babylonjs.com",qe([st()],jy.prototype,"name",void 0),qe([st("comment")],jy.prototype,"comment",void 0);class Ky extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=K,this.registerInput("geometry",vy.Geometry),this.registerOutput("output",vy.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e),i=[],s={};for(let e=0;es[e])),r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Ky.prototype,"evaluateContext",void 0),qe([Ba("Epsilon",Sa.Float,"ADVANCED",{notifiers:{rebuild:!0}})],Ky.prototype,"epsilon",void 0),ee("BABYLON.GeometryOptimizeBlock",Ky);class $y extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",vy.Float,!0,1),this.registerInput("width",vy.Float,!0,0),this.registerInput("height",vy.Float,!0,0),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new Yy("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new Yy("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),ea(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],$y.prototype,"evaluateContext",void 0),ee("BABYLON.PlaneBlock",$y);class qy extends Wy{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",vy.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh)return void(this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null);const e=cn.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=cn.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=cn.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}qe([Ba("Serialize cached data",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],qy.prototype,"serializedCachedData",void 0),ee("BABYLON.MeshBlock",qy);class Zy extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",vy.Float,!0,1),this.registerInput("radiusX",vy.Float,!0,0),this.registerInput("radiusY",vy.Float,!0,0),this.registerInput("radiusZ",vy.Float,!0,0),this.registerInput("subdivisions",vy.Int,!0,4),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new Yy("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),yl(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Zy.prototype,"evaluateContext",void 0),ee("BABYLON.IcoSphereBlock",Zy);class Jy extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",vy.Int,!0,32),this.registerInput("diameter",vy.Float,!0,1),this.registerInput("diameterX",vy.Float,!0,0),this.registerInput("diameterY",vy.Float,!0,0),this.registerInput("diameterZ",vy.Float,!0,0),this.registerInput("arc",vy.Float,!0,1),this.registerInput("slice",vy.Float,!0,1),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Yy("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),Cu(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Jy.prototype,"evaluateContext",void 0),ee("BABYLON.SphereBlock",Jy);class eS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",vy.Float,!0,1),this.registerInput("height",vy.Float,!0,1),this.registerInput("subdivisions",vy.Int,!0,1),this.registerInput("subdivisionsX",vy.Int,!0,0),this.registerInput("subdivisionsY",vy.Int,!0,0),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new Yy("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),Lc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],eS.prototype,"evaluateContext",void 0),ee("BABYLON.GridBlock",eS);class tS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",vy.Float,!0,1),this.registerInput("thickness",vy.Float,!0,.5),this.registerInput("tessellation",vy.Int,!0,16),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Yy("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),Hc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],tS.prototype,"evaluateContext",void 0),ee("BABYLON.TorusBlock",tS);class iS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",vy.Float,!0,25),this.registerInput("diameter",vy.Float,!0,1),this.registerInput("diameterTop",vy.Float,!0,-1),this.registerInput("diameterBottom",vy.Float,!0,-1),this.registerInput("subdivisions",vy.Int,!0,1),this.registerInput("tessellation",vy.Int,!0,24),this.registerInput("arc",vy.Float,!0,1),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new Yy("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),au(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],iS.prototype,"evaluateContext",void 0),ee("BABYLON.CylinderBlock",iS);class sS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",vy.Float,!0,1),this.registerInput("radius",vy.Float,!0,.25),this.registerInput("tessellation",vy.Int,!0,16),this.registerInput("subdivisions",vy.Int,!0,2),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new Yy("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new Yy("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),Pu(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],sS.prototype,"evaluateContext",void 0),ee("BABYLON.CapsuleBlock",sS);class rS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",vy.Float,!0,.5),this.registerInput("tessellation",vy.Int,!0,64),this.registerInput("arc",vy.Float,!0,1),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new Yy("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),wu(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],rS.prototype,"evaluateContext",void 0),ee("BABYLON.DiscBlock",rS);class nS extends Wy{constructor(e){super(e),this.registerOutput("geometry",vy.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}ee("BABYLON.NullBlock",nS);class oS extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("positions",vy.Vector3),this.registerOutput("output",vy.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.normals||(this._vertexData.normals=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);const t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.colors||(this._vertexData.colors=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.tangents||(this._vertexData.tangents=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndexthis._updateInputOutputTypes())),this.left.onDisconnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onDisconnectionObservable.add((()=>this._updateInputOutputTypes()))]}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;const t=this.left,i=this.right;if(!t.isConnected||!i.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const s=t.type===vy.Float||t.type===vy.Int,r=i.type===vy.Float||i.type===vy.Int,n=s&&r;switch(this.operation){case yy.Add:e=n?e=>t.getConnectedValue(e)+i.getConnectedValue(e):s?e=>e.adapt(t,i.type).add(i.getConnectedValue(e)):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case yy.Subtract:e=n?e=>t.getConnectedValue(e)-i.getConnectedValue(e):s?e=>e.adapt(t,i.type).subtract(i.getConnectedValue(e)):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case yy.Multiply:e=n?e=>t.getConnectedValue(e)*i.getConnectedValue(e):s?e=>e.adapt(t,i.type).multiply(i.getConnectedValue(e)):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case yy.Divide:e=n?e=>t.getConnectedValue(e)/i.getConnectedValue(e):s?e=>e.adapt(t,i.type).divide(i.getConnectedValue(e)):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case yy.Min:if(n)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else{const[r,n]=s?[i,t]:[t,i];switch(r.type){case vy.Vector2:e=e=>ue.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case vy.Vector3:e=e=>de.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case vy.Vector4:e=e=>_e.Minimize(r.getConnectedValue(e),e.adapt(n,r.type))}}break;case yy.Max:if(!n){const[r,n]=s?[i,t]:[t,i];switch(r.type){case vy.Vector2:e=e=>ue.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case vy.Vector3:e=e=>de.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case vy.Vector4:e=e=>_e.Maximize(r.getConnectedValue(e),e.adapt(n,r.type))}break}e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e))}this.output._storedFunction=i=>t.type===vy.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${yy[this.operation]};\n`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===vy.Int||this.left.type===vy.Float&&this.right.type!==vy.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[vy.Int,vy.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==vy.Int&&t.type!==vy.Float||e.acceptedConnectionPointTypes.push(vy.Vector2,vy.Vector3,vy.Vector4))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}qe([Ba("Operation",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:yy.Add},{label:"Subtract",value:yy.Subtract},{label:"Multiply",value:yy.Multiply},{label:"Divide",value:yy.Divide},{label:"Max",value:yy.Max},{label:"Min",value:yy.Min}]})],uS.prototype,"operation",void 0),ee("BABYLON.MathBlock",uS);class dS extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("fromMin",vy.Float,!0,0),this.registerInput("fromMax",vy.Float,!0,1),this.registerInput("toMin",vy.Float,!0,0),this.registerInput("toMax",vy.Float,!0,1),this.registerOutput("output",vy.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(vy.Vector2),this._inputs[0].excludedConnectionPointTypes.push(vy.Vector3),this._inputs[0].excludedConnectionPointTypes.push(vy.Vector4),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=(t-i)/(s-i)*(this.toMax.getConnectedValue(e)-r)+r;return this.output.type===vy.Int?Math.floor(n):n}}}ee("BABYLON.MapRangeBlock",dS),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(Sy||(Sy={}));class _S extends Wy{constructor(e){super(e),this.test=Sy.Equal,this.registerInput("left",vy.Float),this.registerInput("right",vy.Float,!0,0),this.registerInput("ifTrue",vy.AutoDetect,!0,1),this.registerInput("ifFalse",vy.AutoDetect,!0,0),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=vy.Float,this._inputs[0].acceptedConnectionPointTypes.push(vy.Int),this._inputs[1].acceptedConnectionPointTypes.push(vy.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);let s=!1;switch(this.test){case Sy.Equal:s=xe.WithinEpsilon(t,i,K);break;case Sy.NotEqual:s=t!==i;break;case Sy.LessThan:s=ti;break;case Sy.LessOrEqual:s=t<=i;break;case Sy.GreaterOrEqual:s=t>=i;break;case Sy.Xor:s=!!t&&!i||!t&&!!i;break;case Sy.Or:s=!!t||!!i;break;case Sy.And:s=!!t&&!!i}return s};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${Sy[this.test]};\n`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}qe([Ba("Test",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:Sy.Equal},{label:"NotEqual",value:Sy.NotEqual},{label:"LessThan",value:Sy.LessThan},{label:"GreaterThan",value:Sy.GreaterThan},{label:"LessOrEqual",value:Sy.LessOrEqual},{label:"GreaterOrEqual",value:Sy.GreaterOrEqual},{label:"Xor",value:Sy.Xor},{label:"Or",value:Sy.Or},{label:"And",value:Sy.And}]})],_S.prototype,"test",void 0),ee("BABYLON.ConditionBlock",_S),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(Cy||(Cy={}));class pS extends Wy{constructor(e){super(e),this._currentLockId=-1,this.lockMode=Cy.None,this.registerInput("min",vy.AutoDetect),this.registerInput("max",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[1].excludedConnectionPointTypes.push(vy.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new Yy("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new Yy("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case vy.Int:case vy.Float:e=e=>{const t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case vy.Vector2:e=e=>{const t=this.min.getConnectedValue(e)||ue.Zero(),i=this.max.getConnectedValue(e)||ue.Zero();return new ue(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case vy.Vector3:e=e=>{const t=this.min.getConnectedValue(e)||de.Zero(),i=this.max.getConnectedValue(e)||de.Zero();return new de(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case vy.Vector4:e=e=>{const t=this.min.getConnectedValue(e)||_e.Zero(),i=this.max.getConnectedValue(e)||_e.Zero();return new _e(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==Cy.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case Cy.InstanceID:i=t.getContextualValue(Ty.InstanceID,!0)||0;break;case Cy.LoopID:i=t.getContextualValue(Ty.LoopID,!0)||0}return this._currentLockId===i&&this.lockMode!==Cy.None||(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${Cy[this.lockMode]};\n`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}qe([Ba("LockMode",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:Cy.None},{label:"LoopID",value:Cy.LoopID},{label:"InstanceID",value:Cy.InstanceID}]})],pS.prototype,"lockMode",void 0),ee("BABYLON.RandomBlock",pS);class fS extends Wy{constructor(e){super(e),this.registerInput("offset",vy.Vector3,!0,de.Zero()),this.registerInput("scale",vy.Float,!0,1),this.registerInput("octaves",vy.Float,!0,2,0,16),this.registerInput("roughness",vy.Float,!0,.5,0,1),this.registerOutput("output",vy.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,s){const r=15&e,n=r<8?t:i,o=r<4?i:12===r||14==r?t:s;return this._negateIf(n,r&n)+this._negateIf(o,2&r)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,a,l,h,c){const u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+s*l))+c*(d*(r*u+n*l)+h*(o*u+a*l))}_perlinNoise(e){const t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),s=(0|e.z)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,a=this._fade(r),l=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),a,l,h)}_perlinSigned(e){return.982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new de(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,a=1,l=0,h=0;const c=0|(e=xe.Clamp(e,0,15));for(let e=0;e<=c;e++)h+=this._perlin(n.scale(o))*a,l+=a,a*=xe.Clamp(t,0,1),o*=2;const u=e-Math.floor(e);if(0==u)return h/l;let d=h+this._perlin(n.scale(o))*a;return h/=l,d/=l+a,(1-u)*h+u*d}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Ty.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}}ee("BABYLON.NoiseBlock",fS);class mS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",vy.Geometry),this.registerInput("geometry1",vy.Geometry,!0),this.registerInput("geometry2",vy.Geometry,!0),this.registerInput("geometry3",vy.Geometry,!0),this.registerInput("geometry4",vy.Geometry,!0),this.registerOutput("output",vy.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{let t=this.geometry0.getConnectedValue(e);const i=[];if(!t)return null;if(t=t.clone(),this.geometry1.isConnected){const t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){const t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){const t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){const t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mS.prototype,"evaluateContext",void 0),ee("BABYLON.MergeGeometryBlock",mS);class gS extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",vy.Geometry,!0),this.registerInput("geometry1",vy.Geometry,!0),this.registerInput("geometry2",vy.Geometry,!0),this.registerInput("geometry3",vy.Geometry,!0),this.registerInput("geometry4",vy.Geometry,!0),this.registerInput("geometry5",vy.Geometry,!0),this.registerInput("geometry6",vy.Geometry,!0),this.registerInput("geometry7",vy.Geometry,!0),this.registerInput("geometry8",vy.Geometry,!0),this.registerInput("geometry9",vy.Geometry,!0),this.registerOutput("output",vy.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,s){if(e.isConnected){const r=e.getConnectedValue(t);if(!r)return;r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=e=>{const t=[];return this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],gS.prototype,"evaluateContext",void 0),ee("BABYLON.GeometryCollectionBlock",gS);class vS extends Wy{constructor(e){super(e),this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}ee("BABYLON.GeometryElbowBlock",vS);class xS extends Wy{constructor(e){super(e),this.registerInput("geometry",vy.Geometry),this.registerOutput("output",vy.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),cn.ComputeNormals(t.positions,t.indices,t.normals),t}}}ee("BABYLON.ComputeNormalsBlock",xS);class bS extends Wy{constructor(e){super(e),this.registerInput("xyzw ",vy.Vector4,!0),this.registerInput("xyz ",vy.Vector3,!0),this.registerInput("xy ",vy.Vector2,!0),this.registerInput("zw ",vy.Vector2,!0),this.registerInput("x ",vy.Float,!0),this.registerInput("y ",vy.Float,!0),this.registerInput("z ",vy.Float,!0),this.registerInput("w ",vy.Float,!0),this.registerOutput("xyzw",vy.Vector4),this.registerOutput("xyz",vy.Vector3),this.registerOutput("xy",vy.Vector2),this.registerOutput("zw",vy.Vector2),this.registerOutput("x",vy.Float),this.registerOutput("y",vy.Float),this.registerOutput("z",vy.Float),this.registerOutput("w",vy.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,_=this.xOut,p=this.yOut,f=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),s.isConnected&&(u=s.getConnectedValue(e)),r.isConnected&&(d=r.getConnectedValue(e)),n.isConnected){const t=n.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(o.isConnected){const t=o.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(a.isConnected){const t=a.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new _e(h,c,u,d)};h._storedFunction=e=>g(e),c._storedFunction=e=>{const t=g(e);return new de(t.x,t.y,t.z)},u._storedFunction=e=>{const t=g(e);return new ue(t.x,t.y)},d._storedFunction=e=>{const t=g(e);return new ue(t.z,t.w)},_._storedFunction=e=>g(e).x,p._storedFunction=e=>g(e).y,f._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}ee("BABYLON.VectorConverterBlock",bS);class TS extends Wy{constructor(e){super(e),this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize():this.output._storedValue=null}}ee("BABYLON.NormalizeVectorBlock",TS);class yS extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("id",vy.Int,!0,0),this.registerOutput("output",vy.Geometry),this.id.acceptedConnectionPointTypes.push(vy.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;const i=new hn;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],yS.prototype,"evaluateContext",void 0),ee("BABYLON.SetMaterialIDBlock",yS),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians",e[e.Fract=19]="Fract",e[e.Exp2=20]="Exp2"}(Ey||(Ey={}));class SS extends Wy{constructor(e){super(e),this.operation=Ey.Cos,this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case Ey.Cos:t=e=>Math.cos(e);break;case Ey.Sin:t=e=>Math.sin(e);break;case Ey.Abs:t=e=>Math.abs(e);break;case Ey.Exp:t=e=>Math.exp(e);break;case Ey.Exp2:t=e=>Math.pow(2,e);break;case Ey.Round:t=e=>Math.round(e);break;case Ey.Floor:t=e=>Math.floor(e);break;case Ey.Ceiling:t=e=>Math.ceil(e);break;case Ey.Sqrt:t=e=>Math.sqrt(e);break;case Ey.Log:t=e=>Math.log(e);break;case Ey.Tan:t=e=>Math.tan(e);break;case Ey.ArcTan:t=e=>Math.atan(e);break;case Ey.ArcCos:t=e=>Math.acos(e);break;case Ey.ArcSin:t=e=>Math.asin(e);break;case Ey.Sign:t=e=>Math.sign(e);break;case Ey.Negate:t=e=>-e;break;case Ey.OneMinus:t=e=>1-e;break;case Ey.Reciprocal:t=e=>1/e;break;case Ey.ToRadians:t=e=>e*Math.PI/180;break;case Ey.ToDegrees:t=e=>180*e/Math.PI;break;case Ey.Fract:t=e=>e>=0?e-Math.floor(e):e-Math.ceil(e)}if(!t)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case vy.Int:case vy.Float:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return t(i)};break;case vy.Vector2:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new ue(t(i.x),t(i.y))};break;case vy.Vector3:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new de(t(i.x),t(i.y),t(i.z))};break;case vy.Vector4:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new _e(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${Ey[this.operation]};\n`}}qe([Ba("Operation",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Ey.Cos},{label:"Sin",value:Ey.Sin},{label:"Abs",value:Ey.Abs},{label:"Exp",value:Ey.Exp},{label:"Exp2",value:Ey.Exp2},{label:"Round",value:Ey.Round},{label:"Floor",value:Ey.Floor},{label:"Ceiling",value:Ey.Ceiling},{label:"Sqrt",value:Ey.Sqrt},{label:"Log",value:Ey.Log},{label:"Tan",value:Ey.Tan},{label:"ArcTan",value:Ey.ArcTan},{label:"ArcCos",value:Ey.ArcCos},{label:"ArcSin",value:Ey.ArcSin},{label:"Sign",value:Ey.Sign},{label:"Negate",value:Ey.Negate},{label:"OneMinus",value:Ey.OneMinus},{label:"Reciprocal",value:Ey.Reciprocal},{label:"ToDegrees",value:Ey.ToDegrees},{label:"ToRadians",value:Ey.ToRadians},{label:"Fract",value:Ey.Fract}]})],SS.prototype,"operation",void 0),ee("BABYLON.GeometryTrigonometryBlock",SS);class CS extends Wy{constructor(e){super(e),this._rotationMatrix=new fe,this._scalingMatrix=new fe,this._translationMatrix=new fe,this._scalingRotationMatrix=new fe,this._transformMatrix=new fe,this.evaluateContext=!0,this.registerInput("value",vy.AutoDetect),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("translation",vy.Vector3,!0,de.Zero()),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.value.getConnectedValue(e);if(!t)return null;let i;if(this.matrix.isConnected)i=this.matrix.getConnectedValue(e);else{const t=this.scaling.getConnectedValue(e),s=this.rotation.getConnectedValue(e),r=this.translation.getConnectedValue(e);fe.ScalingToRef(t.x,t.y,t.z,this._scalingMatrix),fe.RotationYawPitchRollToRef(s.y,s.x,s.z,this._rotationMatrix),fe.TranslationToRef(r.x,r.y,r.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),i=this._transformMatrix}switch(this.value.type){case vy.Geometry:{const e=t.clone();return e.transform(i),e}case vy.Vector2:return ue.Transform(t,i);case vy.Vector3:return de.TransformCoordinates(t,i);case vy.Vector4:return _e.TransformCoordinates(t,i)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CS.prototype,"evaluateContext",void 0),ee("BABYLON.GeometryTransformBlock",CS);class ES extends Wy{constructor(e){super(e),this.registerInput("angle",vy.Float,!1,0),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Yy("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>fe.RotationX(this.angle.getConnectedValue(e))}}ee("BABYLON.RotationXBlock",ES);class AS extends Wy{constructor(e){super(e),this.registerInput("angle",vy.Float,!1,0),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Yy("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>fe.RotationY(this.angle.getConnectedValue(e))}}ee("BABYLON.RotationYBlock",AS);class PS extends Wy{constructor(e){super(e),this.registerInput("angle",vy.Float,!1,0),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new Yy("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>fe.RotationZ(this.angle.getConnectedValue(e))}}ee("BABYLON.RotationZBlock",PS);class RS extends Wy{constructor(e){super(e),this.registerInput("scale",vy.Vector3,!1,de.One()),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new Yy("Scale");e.value=new de(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.scale.getConnectedValue(e);return fe.Scaling(t.x,t.y,t.z)}}}ee("BABYLON.ScalingBlock",RS);class IS extends Wy{constructor(e){super(e),this.registerInput("source",vy.Vector3,!0,de.Up()),this.registerInput("target",vy.Vector3,!0,de.Left()),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),s=new fe;return t.normalize(),i.normalize(),fe.RotationAlignToRef(t,i,s,!0),s}}}ee("BABYLON.AlignBlock",IS);class MS extends Wy{constructor(e){super(e),this.registerInput("translation",vy.Vector3,!1,de.Zero()),this.registerOutput("matrix",vy.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new Yy("Translation");e.value=new de(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.translation.getConnectedValue(e);return fe.Translation(t.x,t.y,t.z)}}}ee("BABYLON.TranslationBlock",MS);class OS extends Wy{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("instance",vy.Geometry,!0),this.registerInput("density",vy.Float,!0,1,0,1),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.scaling.acceptedConnectionPointTypes.push(vy.Float),this.registerOutput("output",vy.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=this._vertexData.positions.length/3;const i=[],s=new de,r=[];let n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexr)continue;s.fromArray(n,3*this._currentIndex);const o=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(o,s,t,i)}else{const t=e.adaptInput(this.scaling,vy.Vector3,de.OneReadOnly),r=this.rotation.getConnectedValue(e)||de.ZeroReadOnly;e._instantiate(o,s,r,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{const e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"};\n`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],OS.prototype,"evaluateContext",void 0),qe([Ba("Remove duplicated positions",Sa.Boolean,"ADVANCED",{notifiers:{update:!0}})],OS.prototype,"removeDuplicatedPositions",void 0),ee("BABYLON.InstantiateOnVerticesBlock",OS);class DS extends Wy{constructor(e){super(e),this._currentPosition=new de,this._currentUV=new ue,this._vertex0=new de,this._vertex1=new de,this._vertex2=new de,this._tempVector0=new de,this._tempVector1=new de,this._uv0=new ue,this._uv1=new ue,this._uv2=new ue,this.evaluateContext=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("instance",vy.Geometry,!0),this.registerInput("count",vy.Int,!0,256),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.scaling.acceptedConnectionPointTypes.push(vy.Float),this.registerOutput("output",vy.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),de.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=this._vertexData.indices.length/3,r=i/s;let n=0;const o=[];let a=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),s=Math.random();if(i>s){const e=i;i=s,s=e}const l=i,h=s-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length){n-=r;continue}const u=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,o)}else{const t=e.adaptInput(this.scaling,vy.Vector3,de.OneReadOnly),i=this.rotation.getConnectedValue(e)||de.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,o)}a++,this._currentLoopIndex++}}if(o.length)if(1===o.length)this._vertexData=o[0];else{const e=o.splice(0,1)[0];this._vertexData=e.merge(o,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],DS.prototype,"evaluateContext",void 0),ee("BABYLON.InstantiateOnFacesBlock",DS);class wS extends Wy{constructor(e){super(e),this._currentPosition=new de,this._vertex0=new de,this._vertex1=new de,this._vertex2=new de,this.evaluateContext=!0,this.registerInput("geometry",vy.Geometry),this.registerInput("instance",vy.Geometry,!0),this.registerInput("count",vy.Int,!0,256),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.scaling.acceptedConnectionPointTypes.push(vy.Float),this.registerOutput("output",vy.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=[],r=an(this._vertexData.positions,0,this._vertexData.positions.length/3),n=r.minimum,o=r.maximum,a=new de(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let r=0;r0&&h++}if(h%2==0){r--;continue}if(t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length)continue;const c=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,s)}else{const t=e.adaptInput(this.scaling,vy.Vector3,de.OneReadOnly),i=this.rotation.getConnectedValue(e)||de.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,s)}this._currentLoopIndex++}if(s.length)if(1===s.length)this._vertexData=s[0];else{const e=s.splice(0,1)[0];this._vertexData=e.merge(s,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],wS.prototype,"evaluateContext",void 0),ee("BABYLON.InstantiateOnVolumeBlock",wS);class NS extends Wy{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",vy.Geometry,!0),this.registerInput("count",vy.Int,!0,1),this.registerOutput("output",vy.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],NS.prototype,"evaluateContext",void 0);class FS extends NS{constructor(e){super(e),this.registerInput("matrix",vy.Matrix,!0),this.registerInput("position",vy.Vector3,!0,de.Zero()),this.registerInput("rotation",vy.Vector3,!0,de.Zero()),this.registerInput("scaling",vy.Vector3,!0,de.One()),this.scaling.acceptedConnectionPointTypes.push(vy.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=fe.Identity(),r=de.Zero(),n=de.Zero(),o=de.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=fe.Identity(),r=fe.Identity(),n=fe.Identity(),o=de.Zero(),a=de.Zero(),l=de.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}ee("BABYLON.IntFloatConverterBlock",kS);class VS extends Wy{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];const t=e=>{const t=this.input.getConnectedValue(e);if(null==t)return this.log.push(["null",""]),t;switch(this.input.type){case vy.Vector2:this.log.push([KT(t,4),t.toString()]);break;case vy.Vector3:this.log.push([$T(t,4),t.toString()]);break;case vy.Vector4:this.log.push([qT(t,4),t.toString()]);break;default:this.log.push([t.toString(),t.toString()])}return t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}ee("BABYLON.DebugBlock",VS);class US extends Wy{constructor(e){super(e),this.registerInput("geometry",vy.Geometry),this.registerOutput("output",vy.Geometry),this.registerOutput("id",vy.Int),this.registerOutput("collectionId",vy.Int),this.registerOutput("verticesCount",vy.Int),this.registerOutput("facesCount",vy.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected)return this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,void(this.output._storedFunction=null);this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}ee("BABYLON.GeometryInfoBlock",US),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(Ay||(Ay={}));class GS extends Wy{constructor(e){super(e),this.mapping=Ay.Spherical,this.registerInput("position",vy.Vector3),this.registerInput("normal",vy.Vector3),this.registerInput("center",vy.Vector3,!0,de.Zero()),this.registerOutput("uv",vy.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected)return this.uv._storedFunction=null,void(this.uv._storedValue=null);const e=de.Zero(),t=t=>{const i=this.position.getConnectedValue(t)||de.Zero(),s=this.normal.getConnectedValue(t)||de.Zero(),r=this.center.getConnectedValue(t),n=ue.Zero();switch(this.mapping){case Ay.Spherical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,0===e.x&&0===e.z||(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case Ay.Cylindrical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case Ay.Cubic:{const e=Math.abs(s.x),t=Math.abs(s.y),o=Math.abs(s.z),a=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));let l=0,h=0;e>=t&&e>=o?(l=i.y/a-r.y,h=i.z/a-r.z):t>=e&&t>=o?(l=i.x/a-r.x,h=i.z/a-r.z):(l=i.x/a-r.x,h=i.y/a-r.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${Ay[this.mapping]};\n`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}qe([Ba("Mapping",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:Ay.Spherical},{label:"Cylindrical",value:Ay.Cylindrical},{label:"Cubic",value:Ay.Cubic}]})],GS.prototype,"mapping",void 0),ee("BABYLON.MappingBlock",GS);class zS extends Wy{constructor(e){super(e),this.registerInput("matrix0",vy.Matrix),this.registerInput("matrix1",vy.Matrix),this.registerOutput("output",vy.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}}ee("BABYLON.MatrixComposeBlock",zS);class WS extends Wy{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",vy.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}ee("BABYLON.TeleportInBlock",WS);class HS extends Wy{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",vy.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}ee("BABYLON.TeleportOutBlock",HS);class XS extends Wy{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",vy.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise(((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const e=n.getImageData(0,0,s.width,s.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},s.src=e}))}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise(((t,i)=>{if(!e.isReady())return void e.onLoadObservable.addOnce((()=>this.extractFromTextureAsync(e).then(t).catch(i)));const s=e.getSize();g_.GetTextureDataAsync(e,s.width,s.height).then((async e=>{const i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=e=>{const t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;const i=this.coordinates.getConnectedValue(e);if(!i)return null;const s=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),r=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(s*(t.width-1)),o=Math.floor(r*(t.height-1)),a=n+t.width*o;return _e.FromArray(t.data,4*a)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};\n`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}qe([Ba("Clamp Coordinates",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],YS.prototype,"clampCoordinates",void 0),ee("BABYLON.GeometryTextureFetchBlock",YS);class QS extends Wy{constructor(e){super(e),this.registerInput("geometry",vy.Geometry),this.registerOutput("min",vy.Vector3),this.registerOutput("max",vy.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?an(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?an(t.positions,0,t.positions.length/3).maximum:null}}}ee("BABYLON.BoundingBlock",QS),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(Py||(Py={}));class jS extends Wy{constructor(e){super(e),this.evaluateContext=!1,this.operation=Py.Intersect,this.registerInput("geometry0",vy.Geometry),this.registerInput("geometry1",vy.Geometry),this.registerOutput("output",vy.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{const t=this.geometry0.getConnectedValue(e),i=this.geometry1.getConnectedValue(e);if(!t||!i)return null;const s=t.positions.length/3;!t.normals&&i.normals&&(t.normals=new Array(t.positions.length)),!i.normals&&t.normals&&(i.normals=new Array(i.positions.length)),!t.uvs&&i.uvs&&(t.uvs=new Array(2*s)),!i.uvs&&t.uvs&&(i.uvs=new Array(2*s)),!t.colors&&i.colors&&(t.colors=new Array(4*s)),!i.colors&&t.colors&&(i.colors=new Array(4*s));const r=ay.FromVertexData(t),n=ay.FromVertexData(i);let o;switch(this.operation){case Py.Intersect:o=r.intersect(n);break;case Py.Subtract:o=r.subtract(n);break;case Py.Union:o=r.union(n)}return o.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${Py[this.operation]};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}qe([Ba("Evaluate context",Sa.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],jS.prototype,"evaluateContext",void 0),qe([Ba("Operation",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:Py.Intersect},{label:"Subtract",value:Py.Subtract},{label:"Union",value:Py.Union}]})],jS.prototype,"operation",void 0),ee("BABYLON.BooleanGeometryBlock",jS);class KS extends Wy{constructor(e){super(e),this.registerInput("x",vy.AutoDetect),this.registerInput("y",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.atan2(e,t);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),s=this.y.getConnectedValue(t);switch(this.x.type){case vy.Int:case vy.Float:return e(i,s);case vy.Vector2:return new ue(e(i.x,s.x),e(i.y,s.y));case vy.Vector3:return new de(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case vy.Vector4:return new _e(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0}}}ee("BABYLON.GeometryArcTan2Block",KS);class $S extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerInput("gradient",vy.Float),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case vy.Int:case vy.Float:return e(r,i,s);case vy.Vector2:return new ue(e(r,i.x,s.x),e(r,i.y,s.y));case vy.Vector3:return new de(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));case vy.Vector4:return new _e(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w))}return 0},this}}ee("BABYLON.GeometryLerpBlock",$S);class qS extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerInput("gradient",vy.Float),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case vy.Int:case vy.Float:return e(r,i,s);case vy.Vector2:{const t=new ue(e(r,i.x,s.x),e(r,i.y,s.y));return t.normalize(),t}case vy.Vector3:{const t=new de(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));return t.normalize(),t}case vy.Vector4:{const t=new _e(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w));return t.normalize(),t}}return 0},this}}ee("BABYLON.GeometryNLerpBlock",qS);class ZS extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("edge",vy.Float),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e{const i=this.value.getConnectedValue(t),s=this.edge.getConnectedValue(t);switch(this.value.type){case vy.Int:case vy.Float:return e(i,s);case vy.Vector2:return new ue(e(i.x,s),e(i.y,s));case vy.Vector3:return new de(e(i.x,s),e(i.y,s),e(i.z,s));case vy.Vector4:return new _e(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}ee("BABYLON.GeometryStepBlock",ZS);class JS extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("edge0",vy.Float),this.registerInput("edge1",vy.Float),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>{const s=Math.max(0,Math.min((e-t)/(i-t),1));return s*s*(3-2*s)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge0.getConnectedValue(t),r=this.edge1.getConnectedValue(t);switch(this.value.type){case vy.Int:case vy.Float:return e(i,s,r);case vy.Vector2:return new ue(e(i.x,s,r),e(i.y,s,r));case vy.Vector3:return new de(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r));case vy.Vector4:return new _e(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r),e(i.w,s,r))}return 0},this}}ee("BABYLON.GeometrySmoothStepBlock",JS);class eC extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e-Math.floor(e/t)*t;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t);switch(this.left.type){case vy.Int:case vy.Float:return e(i,s);case vy.Vector2:return new ue(e(i.x,s.x),e(i.y,s.y));case vy.Vector3:return new de(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case vy.Vector4:return new _e(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0},this}}ee("BABYLON.GeometryModBlock",eC);class tC extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("power",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.pow(e,t);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.power.getConnectedValue(t);switch(this.value.type){case vy.Int:case vy.Float:return e(i,s);case vy.Vector2:return new ue(e(i.x,s),e(i.y,s));case vy.Vector3:return new de(e(i.x,s),e(i.y,s),e(i.z,s));case vy.Vector4:return new _e(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}ee("BABYLON.GeometryPowBlock",tC);class iC extends Wy{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Geometry),this._inputs[0].excludedConnectionPointTypes.push(vy.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>Math.max(this.minimum,Math.min(e,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case vy.Int:case vy.Float:return e(i);case vy.Vector2:return new ue(e(i.x),e(i.y));case vy.Vector3:return new de(e(i.x),e(i.y),e(i.z));case vy.Vector4:return new _e(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}qe([Ba("Minimum",Sa.Float)],iC.prototype,"minimum",void 0),qe([Ba("Maximum",Sa.Float)],iC.prototype,"maximum",void 0),ee("BABYLON.GeometryClampBlock",iC);class sC extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerOutput("output",vy.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Int),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Vector2),this._inputs[1].excludedConnectionPointTypes.push(vy.Int),this._inputs[1].excludedConnectionPointTypes.push(vy.Float),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case vy.Vector3:return de.Cross(t,i);case vy.Vector4:return de.Cross(t.toVector3(),i.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryCrossBlock",sC),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(Ry||(Ry={}));class rC extends Wy{constructor(e){super(e),this.type=Ry.EaseInOutSine,this.registerInput("input",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[0].excludedConnectionPointTypes.push(vy.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);let e;switch(this.type){case Ry.EaseInSine:e=e=>1-Math.cos(3.1415*e/2);break;case Ry.EaseOutSine:e=e=>Math.sin(3.1415*e/2);break;case Ry.EaseInOutSine:e=e=>-(Math.cos(3.1415*e)-1)/2;break;case Ry.EaseInQuad:e=e=>e*e;break;case Ry.EaseOutQuad:e=e=>(1-e)*(1-e);break;case Ry.EaseInOutQuad:e=e=>e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;break;case Ry.EaseInCubic:e=e=>e*e*e;break;case Ry.EaseOutCubic:e=e=>1-Math.pow(1-e,3);break;case Ry.EaseInOutCubic:e=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;break;case Ry.EaseInQuart:e=e=>e*e*e*e;break;case Ry.EaseOutQuart:e=e=>1-Math.pow(1-e,4);break;case Ry.EaseInOutQuart:e=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;break;case Ry.EaseInQuint:e=e=>e*e*e*e*e;break;case Ry.EaseOutQuint:e=e=>1-Math.pow(1-e,5);break;case Ry.EaseInOutQuint:e=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;break;case Ry.EaseInExpo:e=e=>0===e?0:Math.pow(2,10*e-10);break;case Ry.EaseOutExpo:e=e=>1===e?1:1-Math.pow(2,-10*e);break;case Ry.EaseInOutExpo:e=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;break;case Ry.EaseInCirc:e=e=>1-Math.sqrt(1-Math.pow(e,2));break;case Ry.EaseOutCirc:e=e=>Math.sqrt(1-Math.pow(e-1,2));break;case Ry.EaseInOutCirc:e=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;break;case Ry.EaseInBack:e=e=>2.70158*e*e*e-1.70158*e*e;break;case Ry.EaseOutBack:e=e=>2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2);break;case Ry.EaseInOutBack:e=e=>e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2;break;case Ry.EaseInElastic:e=e=>0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75));break;case Ry.EaseOutElastic:e=e=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1;break;case Ry.EaseInOutElastic:e=e=>0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case vy.Float:return e(i);case vy.Vector2:return new ue(e(i.x),e(i.y));case vy.Vector3:return new de(e(i.x),e(i.y),e(i.z));case vy.Vector4:return new _e(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${Ry[this.type]};\n`}}qe([Ba("Type",Sa.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:Ry.EaseInSine},{label:"EaseOutSine",value:Ry.EaseOutSine},{label:"EaseInOutSine",value:Ry.EaseInOutSine},{label:"EaseInQuad",value:Ry.EaseInQuad},{label:"EaseOutQuad",value:Ry.EaseOutQuad},{label:"EaseInOutQuad",value:Ry.EaseInOutQuad},{label:"EaseInCubic",value:Ry.EaseInCubic},{label:"EaseOutCubic",value:Ry.EaseOutCubic},{label:"EaseInOutCubic",value:Ry.EaseInOutCubic},{label:"EaseInQuart",value:Ry.EaseInQuart},{label:"EaseOutQuart",value:Ry.EaseOutQuart},{label:"EaseInOutQuart",value:Ry.EaseInOutQuart},{label:"EaseInQuint",value:Ry.EaseInQuint},{label:"EaseOutQuint",value:Ry.EaseOutQuint},{label:"EaseInOutQuint",value:Ry.EaseInOutQuint},{label:"EaseInExpo",value:Ry.EaseInExpo},{label:"EaseOutExpo",value:Ry.EaseOutExpo},{label:"EaseInOutExpo",value:Ry.EaseInOutExpo},{label:"EaseInCirc",value:Ry.EaseInCirc},{label:"EaseOutCirc",value:Ry.EaseOutCirc},{label:"EaseInOutCirc",value:Ry.EaseInOutCirc},{label:"EaseInBack",value:Ry.EaseInBack},{label:"EaseOutBack",value:Ry.EaseOutBack},{label:"EaseInOutBack",value:Ry.EaseInOutBack},{label:"EaseInElastic",value:Ry.EaseInElastic},{label:"EaseOutElastic",value:Ry.EaseOutElastic},{label:"EaseInOutElastic",value:Ry.EaseInOutElastic}]})],rC.prototype,"type",void 0),ee("BABYLON.GeometryCurveBlock",rC);class nC extends Wy{constructor(e){super(e),this.registerInput("color",vy.Vector3),this.registerInput("level",vy.Float,!0,0),this.registerOutput("output",vy.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.color.isConnected?(this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),s=.5*(Math.min(t.x,t.y,t.z)+Math.max(t.x,t.y,t.z));return new de(t.x*(1-i)+s*i,t.y*(1-i)+s*i,t.z*(1-i)+s*i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryDesaturateBlock",nC);class oC extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("steps",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(vy.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let s=i;if(this.steps.type===vy.Float)switch(this.value.type){case vy.Vector2:s=new ue(i,i);break;case vy.Vector3:s=new de(i,i,i);break;case vy.Vector4:s=new _e(i,i,i,i)}switch(this.value.type){case vy.Vector2:return new ue(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y));case vy.Vector3:return new de(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z));case vy.Vector4:return new _e(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z),t.w/(1/s.w)*(1/s.w));default:return Math.floor(t/(1/i)*(1/i))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryPosterizeBlock",oC);class aC extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerInput("reference",vy.AutoDetect),this.registerInput("distance",vy.Float),this.registerInput("replacement",vy.AutoDetect),this.registerOutput("output",vy.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Float),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[3].excludedConnectionPointTypes.push(vy.Float),this._inputs[3].excludedConnectionPointTypes.push(vy.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),s=this.distance.getConnectedValue(e),r=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryDistanceBlock",lC);class hC extends Wy{constructor(e){super(e),this.registerInput("left",vy.AutoDetect),this.registerInput("right",vy.AutoDetect),this.registerOutput("output",vy.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(vy.Int),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix),this._inputs[1].excludedConnectionPointTypes.push(vy.Float),this._inputs[1].excludedConnectionPointTypes.push(vy.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryDotBlock",hC);class cC extends Wy{constructor(e){super(e),this.registerInput("value",vy.AutoDetect),this.registerOutput("output",vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Int),this._inputs[0].excludedConnectionPointTypes.push(vy.Float),this._inputs[0].excludedConnectionPointTypes.push(vy.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected?(this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryLengthBlock",cC);class uC extends Wy{constructor(e){super(e),this.registerInput("input",vy.Vector2),this.registerInput("angle",vy.Float),this.registerOutput("output",vy.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new ue(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}ee("BABYLON.GeometryRotate2dBlock",uC);class dC extends bo{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=fe.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const s=new cn;s.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],s.indices=[0,1,2,0,2,3],s.applyToMesh(this),this.subMeshes=[],new ln(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new XT(this.name+"_material",this._scene),this.material=this._material);const s=this.getScene().getFrameId();if(s!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const e=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(e-1)>=.01&&(this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),s=i.indexOf("end_header\n");if(s<0||!i)return e;const r=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let n=0;const o={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},a=[],l=i.slice(0,s).split("\n").filter((e=>e.startsWith("property ")));for(const e of l){const[,t,i]=e.split(" ");if(a.push({name:i,type:t,offset:n}),!o[t])return we.Error(`Unsupported property type: ${t}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0);n+=o[t]}const h=.28209479177387814,c=new DataView(e,s+11),u=new ArrayBuffer(32*r),d=new pe;for(let e=0;e{this._loadData(dC.ConvertPLYToSplat(e))}))}dispose(e){this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._material?.dispose(!1,!0),this._material=null,this._worker?.terminate(),this._worker=null,super.dispose(e)}_loadData(e){if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),s=t.length/32;this._vertexCount=s;const r=this._getTextureSize(s),n=r.x*r.y,o=new Float32Array(3*n),a=new Float32Array(3*n),l=new Float32Array(3*n),h=ge.Matrix[0],c=ge.Matrix[1],u=ge.Quaternion[0],d=new de(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),_=new de(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let e=0;enew Wo(e,t,i,s,this._scene,!1,!1,2,1),g=e=>{const t=e.length/3,i=new Float32Array(4*t);for(let s=0;s{this._depthMix=e.data.depthMix;const t=new Uint32Array(e.data.depthMix.buffer);for(let e=0;ei&&(we.Error("GaussianSplatting texture size: ("+i+", "+s+"), maxTextureSize: "+i),s=i),new ue(i,s)}}dC._CreateWorker=function(e){let t,i,s,r,n=0;e.onmessage=o=>{if(o.data.positions)t=o.data.positions,n=o.data.vertexCount;else{const a=o.data.view;if(!t||!a)throw new Error("positions or view is not defined!");i=o.data.depthMix,s=new Uint32Array(i.buffer),r=new Float32Array(i.buffer);for(let e=0;e{this.update(.001*s.getEngine().getDeltaTime()*e.timeFactor)}))}addAgent(e,t,i){const s=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;s.radius=t.radius,s.height=t.height,s.maxAcceleration=t.maxAcceleration,s.maxSpeed=t.maxSpeed,s.collisionQueryRange=t.collisionQueryRange,s.pathOptimizationRange=t.pathOptimizationRange,s.separationWeight=t.separationWeight,s.updateFlags=7,s.obstacleAvoidanceType=0,s.queryFilterType=0,s.userData=0;const r=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),s);return this.transforms.push(i),this.agents.push(r),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new de(0,0,0)),r}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new de(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new de(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new de(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=K)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=K)this.recastCrowd.update(e);else{let s=Math.floor(e/t);i&&s>i&&(s=i),s<1&&(s=1);const r=e/s;for(let e=0;eo&&i.ynew fC(e,t,i);class fC{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=fC._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,fC.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,hs.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new At;navigator.onLine&&(s=!0,r=r+(null==r.match(/\?/)?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",(()=>{if(200===n.status||fC._ValidateXHRData(n,1))try{const t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&fC._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{if(s){s=!1;const e=i();n.open("GET",e),n.send()}else t()}),!1);try{n.send()}catch(t){we.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{we.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){we.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=fC._ReturnFullUrlLocation(e),s=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let r;s&&"function"==typeof URL?(r=URL.createObjectURL(s.data),t.onerror=()=>{we.Error("Error loading image from blob URL: "+r+" switching back to web url: "+e),t.src=e},t.src=r):i()};const n=r.objectStore("textures").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{we.Error("Error loading texture "+e+" from DB."),t.src=e}}else we.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const s=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(fC._IsUASupportingBlobStorage){const r=new At;r.open("GET",e),r.responseType="blob",r.addEventListener("load",(()=>{if(200===r.status&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const e=n.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{s()}}catch(i){25===i.code&&(fC._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),r.addEventListener("error",(()=>{we.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),r.send()}else t.src=e}else we.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{we.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){we.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else we.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{we.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){we.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=fC._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s,r;s=-1!==e.indexOf(".babylon")?"scenes":"textures";const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=e=>{r=e.target.result},o.onerror=()=>{we.Error("Error loading file "+e+" from DB."),i()}}else we.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new At;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&fC._ValidateXHRData(o,s?6:1))if(a=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([n],"readwrite");let s;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},s="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(n).put(s);e.onsuccess=()=>{},e.onerror=()=>{we.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&r?r(o):t()}),!1),o.addEventListener("error",(()=>{we.Error("error on XHR request."),r&&r()}),!1),o.send()}else we.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=nx(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}fC._IsUASupportingBlobStorage=!0,fC.IDBStorageEnabled=!1,fC._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},fC._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?fC._ParseURL(window.location.href)+e:e;class mC{constructor(){this.direction1=new de(0,1,0),this.direction2=new de(0,1,0),this.minEmitBox=new de(-.5,-.5,-.5),this.maxEmitBox=new de(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=ne(this.direction1.x,this.direction2.x),n=ne(this.direction1.y,this.direction2.y),o=ne(this.direction1.z,this.direction2.z);if(s)return t.x=r,t.y=n,void(t.z=o);de.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=ne(this.minEmitBox.x,this.maxEmitBox.x),n=ne(this.minEmitBox.y,this.maxEmitBox.y),o=ne(this.minEmitBox.z,this.maxEmitBox.z);if(s)return t.x=r,t.y=n,void(t.z=o);de.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new mC;return Xe.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){de.FromArrayToRef(e.direction1,0,this.direction1),de.FromArrayToRef(e.direction2,0,this.direction2),de.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),de.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class gC{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,s){s?ge.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),ge.Vector3[0]).normalize();const r=xe.RandomRange(0,this.directionRandomizer),n=xe.RandomRange(0,this.directionRandomizer),o=xe.RandomRange(0,this.directionRandomizer);t.x=ge.Vector3[0].x+r,t.y=ge.Vector3[0].y+n,t.z=ge.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=xe.RandomRange(0,2*Math.PI);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=xe.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-xe.RandomRange(0,this._radius*this.radiusRange);o*=n;const a=o*Math.sin(r),l=o*Math.cos(r),h=n*this._height;if(s)return t.x=a,t.y=h,void(t.z=l);de.TransformCoordinatesFromFloatsToRef(a,h,l,e,t)}clone(){const e=new gC(this._radius,this._angle,this.directionRandomizer);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class vC{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=de.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),de.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=xe.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);o+=xe.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s?t.copyFrom(this._tempVector):de.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=xe.RandomRange(-this.height/2,this.height/2),n=xe.RandomRange(0,2*Math.PI),o=xe.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(o)*this.radius,l=a*Math.cos(n),h=a*Math.sin(n);s?t.copyFromFloats(l,r,h):de.TransformCoordinatesFromFloatsToRef(l,r,h,e,t)}clone(){const e=new vC(this.radius,this.directionRandomizer);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class xC extends vC{constructor(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t,i,s){const r=xe.RandomRange(this.direction1.x,this.direction2.x),n=xe.RandomRange(this.direction1.y,this.direction2.y),o=xe.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):de.TransformNormalFromFloatsToRef(r,n,o,e,t)}clone(){const e=new xC(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class bC{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=xe.RandomRange(0,this.directionRandomizer),o=xe.RandomRange(0,this.directionRandomizer),a=xe.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):de.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-xe.RandomRange(0,this.radius*this.radiusRange),n=xe.RandomRange(0,1),o=xe.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,Math.abs(h),c):de.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new bC(this.radius,this.directionRandomizer);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class TC{constructor(){this.direction1=new de(0,1,0),this.direction2=new de(0,1,0)}startDirectionFunction(e,t,i,s){const r=xe.RandomRange(this.direction1.x,this.direction2.x),n=xe.RandomRange(this.direction1.y,this.direction2.y),o=xe.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):de.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){s?t.copyFromFloats(0,0,0):de.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new TC;return Xe.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){de.FromArrayToRef(e.direction1,0,this.direction1),de.FromArrayToRef(e.direction2,0,this.direction2)}}class yC{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=xe.RandomRange(0,this.directionRandomizer),o=xe.RandomRange(0,this.directionRandomizer),a=xe.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):de.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-xe.RandomRange(0,this.radius*this.radiusRange),n=xe.RandomRange(0,1),o=xe.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,h,c):de.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new yC(this.radius,this.directionRandomizer);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class SC extends yC{constructor(e=1,t=new de(0,1,0),i=new de(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=xe.RandomRange(this.direction1.x,this.direction2.x),s=xe.RandomRange(this.direction1.y,this.direction2.y),r=xe.RandomRange(this.direction1.z,this.direction2.z);de.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new SC(this.radius,this.direction1,this.direction2);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class CC{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=ge.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const e=ge.Vector3[1];r.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);s?t.copyFrom(r):de.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=ge.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s?t.copyFrom(r):de.TransformCoordinatesToRef(r,e,t)}clone(){const e=new CC;return Xe.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class EC{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(ys.PositionKind),this._normals=e.getVerticesData(ys.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=de.Zero(),this._mesh=null,this.direction1=new de(0,1,0),this.direction2=new de(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals)return void de.TransformNormalToRef(this._storedNormal,e,t);const r=xe.RandomRange(this.direction1.x,this.direction2.x),n=xe.RandomRange(this.direction1.y,this.direction2.y),o=xe.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):de.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),a=1-n-o,l=this._indices[r],h=this._indices[r+1],c=this._indices[r+2],u=ge.Vector3[0],d=ge.Vector3[1],_=ge.Vector3[2],p=ge.Vector3[3];de.FromArrayToRef(this._positions,3*l,u),de.FromArrayToRef(this._positions,3*h,d),de.FromArrayToRef(this._positions,3*c,_),p.x=n*u.x+o*d.x+a*_.x,p.y=n*u.y+o*d.y+a*_.y,p.z=n*u.z+o*d.z+a*_.z,s?t.copyFromFloats(p.x,p.y,p.z):de.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(de.FromArrayToRef(this._normals,3*l,u),de.FromArrayToRef(this._normals,3*h,d),de.FromArrayToRef(this._normals,3*c,_),this._storedNormal.x=n*u.x+o*d.x+a*_.x,this._storedNormal.y=n*u.y+o*d.y+a*_.y,this._storedNormal.z=n*u.z+o*d.z+a*_.z)}clone(){const e=new EC(this.mesh);return Xe.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=this.mesh?.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){de.FromArrayToRef(e.direction1,0,this.direction1),de.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class AC{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}bi.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";bi.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}";class PC{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){return this._updateEffect?.isReady()??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof CC&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new Ti("gpuUpdateParticles",this._updateEffectOptions,this._engine),new AC(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;ee)return void i(t[0],t[0],1);for(let s=0;s=r.gradient&&e<=n.gradient)return void i(r,n,(e-r.gradient)/(n.gradient-r.gradient))}const s=t.length-1;i(t[s],t[s],1)}}class wC{constructor(e){this.particleSystem=e,this.position=de.Zero(),this.direction=de.Zero(),this.color=new Ee(0,0,0,0),this.colorStep=new Ee(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new ue(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Ee(0,0,0,0),this._currentColor2=new Ee(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=wC._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID;let s;s=this._initialSpriteCellLoop?ae(e*t%this.lifeTime/this.lifeTime):ae(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=ge.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,ge.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(ge.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=wC._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new _e(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}wC._Count=0;bi.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.particlesVertexShader="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class NC extends rl{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Fi(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new X),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=fe.Identity(),this._inheritedVelocityOffset=new de,this.onDisposeObservable=new X,this.onStoppedObservable=new X,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Ee(0,0,0,0),this._colorDiff=new Ee(0,0,0,0),this._scaledDirection=de.Zero(),this._scaledGravity=de.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=e=>{},this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;return 0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new wC(this),this._prepareParticle(e),e},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=fe.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||se.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Fi(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new mC;let o=null;this.updateFunction=e=>{let t=null;this.noiseTexture&&(t=this.noiseTexture.getSize(),this.noiseTexture.getContent()?.then((e=>{o=e})));const i=e===this._particles;for(let s=0;sr.lifeTime){const e=r.age-a;n=(r.lifeTime-a)*n/e,r.age=r.lifeTime}const l=r.age/r.lifeTime;this._colorGradients&&this._colorGradients.length>0?DC.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==r._currentColorGradient&&(r._currentColor1.copyFrom(r._currentColor2),t.getColorToRef(r._currentColor2),r._currentColorGradient=e),Ee.LerpToRef(r._currentColor1,r._currentColor2,i,r.color)})):(r.colorStep.scaleToRef(n,this._scaledColorStep),r.color.addInPlace(this._scaledColorStep),r.color.a<0&&(r.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&DC.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==r._currentAngularSpeedGradient&&(r._currentAngularSpeed1=r._currentAngularSpeed2,r._currentAngularSpeed2=t.getFactor(),r._currentAngularSpeedGradient=e),r.angularSpeed=oe(r._currentAngularSpeed1,r._currentAngularSpeed2,i)})),r.angle+=r.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&DC.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==r._currentVelocityGradient&&(r._currentVelocity1=r._currentVelocity2,r._currentVelocity2=t.getFactor(),r._currentVelocityGradient=e),h*=oe(r._currentVelocity1,r._currentVelocity2,i)})),r.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&DC.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==r._currentLimitVelocityGradient&&(r._currentLimitVelocity1=r._currentLimitVelocity2,r._currentLimitVelocity2=t.getFactor(),r._currentLimitVelocityGradient=e);const s=oe(r._currentLimitVelocity1,r._currentLimitVelocity2,i);r.direction.length()>s&&r.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&DC.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==r._currentDragGradient&&(r._currentDrag1=r._currentDrag2,r._currentDrag2=t.getFactor(),r._currentDragGradient=e);const s=oe(r._currentDrag1,r._currentDrag2,i);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&r._localPosition?(r._localPosition.addInPlace(this._scaledDirection),de.TransformCoordinatesToRef(r._localPosition,this._emitterWorldMatrix,r.position)):r.position.addInPlace(this._scaledDirection),o&&t&&r._randomNoiseCoordinates1){const e=this._fetchR(r._randomNoiseCoordinates1.x,r._randomNoiseCoordinates1.y,t.width,t.height,o),i=this._fetchR(r._randomNoiseCoordinates1.z,r._randomNoiseCoordinates2.x,t.width,t.height,o),s=this._fetchR(r._randomNoiseCoordinates2.y,r._randomNoiseCoordinates2.z,t.width,t.height,o),a=ge.Vector3[0],l=ge.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*i-1)*this.noiseStrength.y,(2*s-1)*this.noiseStrength.z),a.scaleToRef(n,l),r.direction.addInPlace(l)}this.gravity.scaleToRef(n,this._scaledGravity),r.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&DC.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==r._currentSizeGradient&&(r._currentSize1=r._currentSize2,r._currentSize2=t.getFactor(),r._currentSizeGradient=e),r.size=oe(r._currentSize1,r._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&DC.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const s=oe(e.factor1,t.factor1,i),n=oe(e.factor2,t.factor2,i);r.remapData.x=s,r.remapData.y=n-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&DC.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const s=oe(e.factor1,t.factor1,i),n=oe(e.factor2,t.factor2,i);r.remapData.z=s,r.remapData.w=n-s}))),this._isAnimationSheetEnabled&&r.updateCellIndex(),r._inheritParticleInfoToSubEmitters(),r.age>=r.lifeTime&&(this._emitFromParticle(r),r._attachedSubEmitters&&(r._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),r._attachedSubEmitters=null),this.recycleParticle(r),i&&s--)}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,s){const r=new OC(t,i,s);e.push(r),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=Ae.Color3[0];for(let i=0;i{Ce.LerpToRef(s.color,r.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=Wo.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new MC(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const s=new IC(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,s,r){return r[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*s%s|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Ts(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(ys.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ys.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(ys.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ys.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||8===this.billboardMode||9===this.billboardMode){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Ts(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return void(this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3])));const e=[],t=[];let i=0;for(let s=0;s{this.start(0)}),e);else{if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==this.emitter?.getClassName().indexOf("Mesh")&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)8!==this.billboardMode&&9!==this.billboardMode||(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(de.TransformNormalToRef(e,this._emitterWorldMatrix,ge.Vector3[0]),e=ge.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}else{let e=t.direction;this.isLocal&&(de.TransformNormalToRef(e,this._emitterWorldMatrix,ge.Vector3[0]),e=ge.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===s?s=this._epsilon:1===s&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=fe.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=ae(this._actualFrame/this.targetStopDuration);DC.GetCurrentGradient(e,this._lifeTimeGradients,((i,s)=>{const r=i,n=s,o=r.getFactor(),a=n.getFactor(),l=(e-r.gradient)/(n.gradient-r.gradient);t.lifeTime=oe(o,a,l)}))}else t.lifeTime=ne(this.minLifeTime,this.maxLifeTime);const e=ne(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),de.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=ne(this.minSize,this.maxSize),t.scale.copyFromFloats(ne(this.minScaleX,this.maxScaleX),ne(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;DC.GetCurrentGradient(e,this._startSizeGradients,((e,i,s)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const r=oe(this._currentStartSize1,this._currentStartSize2,s);t.scale.scaleInPlace(r)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=ne(this.minAngularSpeed,this.maxAngularSpeed),t.angle=ne(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=ne(0,1);Ee.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new _e(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new de(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new de(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[ys.PositionKind,ys.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["invView","view","projection","textureMask","translationPivot","eyePosition"];return An(s),e&&s.push("particlesInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t){if(this._scene&&(Pn(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&0!==this._scene.fogMode&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===rl.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),9===this.billboardMode&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...NC._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode,this._useRampGradients)),e.push(...NC._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(gs(e,this._imageProcessingConfigurationDefines),vs(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new Fi(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join("\n");if(n.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return n}animate(e=!1){if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let t;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;DC.GetCurrentGradient(t,this._emitRateGradients,((t,i,s)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=oe(this._currentEmitRate1,this._currentEmitRate2,s)}))}t=e*this._scaledUpdateSpeed|0,this._newPartsExcess+=e*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(r.invertToRef(ge.Matrix[0]),i.setMatrix("invView",ge.Matrix[0])),void 0!==this._vertexArrayObject?this._scene?.forceWireframe?s.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&wn(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case rl.BLENDMODE_ADD:s.setAlphaMode(1);break;case rl.BLENDMODE_ONEONE:s.setAlphaMode(6);break;case rl.BLENDMODE_STANDARD:s.setAlphaMode(2);break;case rl.BLENDMODE_MULTIPLY:s.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?this._scene?.forceWireframe?s.drawElementsType(6,0,10,this._particles.length):s.drawArraysType(7,0,4,this._particles.length):this._scene?.forceWireframe?s.drawElementsType(1,0,10*this._particles.length):s.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===rl.BLENDMODE_MULTIPLYADD?this._render(rl.BLENDMODE_MULTIPLY)+this._render(rl.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var FC;!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(FC||(FC={}));class BC{constructor(e){if(this.particleSystem=e,this.type=FC.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=te("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof de?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new(te("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new de;const t=new BC(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,s=!1){throw vt("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new BC(BC._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}function LC(e,t){const i=new TC;return i.direction1=e,i.direction2=t,i}function kC(e=1,t=1){return new bC(e,t)}function VC(e=1,t=1){return new yC(e,t)}function UC(e=1,t=new de(0,1,0),i=new de(0,1,0)){return new SC(e,t,i)}function GC(e=1,t=1,i=1,s=0){return new vC(e,t,i,s)}function zC(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){return new xC(e,t,i,s,r)}function WC(e=1,t=Math.PI/4){return new gC(e,t)}class HC extends NC{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===FC.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))}}createPointEmitter(e,t){const i=LC(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=kC(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=VC(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new de(0,1,0),i=new de(0,1,0)){const s=UC(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=GC(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){const n=zC(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=WC(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new mC;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof HC?this._subEmitters.push([new BC(e)]):e instanceof BC?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===FC.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}}_onDispose(e=!1,t=!1){if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&this.particles?.forEach((e=>{if(e._attachedSubEmitters)for(let t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()})),t&&this.activeSubSystems)for(let e=this.activeSubSystems.length-1;e>=0;e-=1)this.activeSubSystems[e].dispose();if(this._subEmitters&&this._subEmitters.length){for(let e=0;e0?h.shaderOptions.defines.join("\n"):"";l=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new HC(n,r||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const s of e.subEmitters){const e=[];for(const r of s)e.push(BC.Parse(r,t,i));c.subEmitters.push(e)}}return HC._Parse(e,c,t,i),e.textureMask&&(c.textureMask=Ee.FromArray(e.textureMask)),e.worldOffset&&(c.worldOffset=de.FromArray(e.worldOffset)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),s||c.preventAutoStart||c.start(),c}serialize(e=!1){const t={};if(HC._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const s=[];for(const t of i)s.push(t.serialize(e));t.subEmitters.push(s)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,yt.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const s=t.getColorGradients();if(s){e.colorGradients=[];for(const t of s){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const t of r){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const t of n){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const _=t.getLifeTimeGradients();if(_){e.lifeTimeGradients=[];for(const t of _){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const p=t.getLimitVelocityGradients();if(p){e.limitVelocityGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){r=this.customShader;const e=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e);s[0]?s[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=HC.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}}HC.BILLBOARDMODE_Y=2,HC.BILLBOARDMODE_ALL=7,HC.BILLBOARDMODE_STRETCHED=8,HC.BILLBOARDMODE_STRETCHED_LOCAL=9,BC._ParseParticleSystem=HC.Parse;bi.IncludesShadersStore.clipPlaneFragmentDeclaration2="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";bi.ShadersStore.gpuRenderParticlesPixelShader="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;\n#include \n#include\n#include\n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include\n#include(color,gl_FragColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";bi.IncludesShadersStore.clipPlaneVertexDeclaration2="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;out float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;out float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;out float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;out float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;out float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;out float fClipDistance6;\n#endif\n";bi.ShadersStore.gpuRenderParticlesVertexShader="precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;attribute float age;attribute float life;attribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;attribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x;\n#ifdef BILLBOARD\nvec4 rotatedCorner;rotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n}";class XC extends rl{static get IsSupported(){if(!se.LastCreatedEngine)return!1;const e=se.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=LC(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=kC(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=VC(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new de(0,1,0),i=new de(0,1,0)){const s=UC(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=GC(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new de(0,1,0),r=new de(0,1,0)){const n=zC(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=WC(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new mC;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==HC.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(HC.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(HC.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((()=>{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Fi(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new X),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new IC(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){for(const e in this._drawWrappers){const t=this._drawWrappers[e];t.drawContext?.reset()}}_addFactorGradient(e,t,i){const s=new OC(t,i);e.push(s),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const s=this;s[t]&&(s[t].dispose(),s[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,s=null,r=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new X,this.onStoppedObservable=new X,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=fe.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||se.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!te("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(te("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!te("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(te("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Fi(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new Fi(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=t??{}).randomTextureSize||delete t.randomTextureSize;const n={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new mC;const a=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let l=[];for(let e=0;e0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),a=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new Ts(t,a,!1,this._attributesStrideSize),this._buffer1=new Ts(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new Ts(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let s=this._drawWrappers[e];s||(s=new Fi(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join("\n");if(s.defines!==r){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),s.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[ys.PositionKind,"age","life","size","angle"];return e||r.push(ys.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",ys.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return An(s),e&&s.push("sheetInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t=0){if(this._scene&&(Pn(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==dr.FOGMODE_NONE&&e.push("#define FOG")),t===HC.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case HC.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case HC.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case HC.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...XC._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===HC.BILLBOARDMODE_STRETCHED)),e.push(...XC._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(xs.PrepareUniforms(e,this._imageProcessingConfigurationDefines),xs.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const s=new Float32Array(this._rawTextureWidth);for(let t=0;t{s[t]=xe.Lerp(e.factor1,i.factor1,r)}))}this[t]=Wo.CreateRTexture(s,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=Ae.Color4[0];for(let i=0;i{Ee.LerpToRef(s.color1,r.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=Wo.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){const i=this._getWrapper(e),s=i.effect;this._engine.enableEffect(i);const r=this._scene?.getViewMatrix()||fe.IdentityReadOnly;if(s.setMatrix("view",r),s.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),s.setTexture("diffuseSampler",this.particleTexture),s.setVector2("translationPivot",this.translationPivot),s.setVector3("worldOffset",this.worldOffset),this.isLocal&&s.setMatrix("emitterWM",t),this._colorGradientsTexture?s.setTexture("colorGradientSampler",this._colorGradientsTexture):s.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();s.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;s.setVector3("eyePosition",e.globalPosition)}const n=s.defines;if(this._scene&&(In(s,this,this._scene),this.applyFog&&Nn(this._scene,void 0,s)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=r.clone();e.invert(),s.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&wn(n,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case HC.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case HC.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case HC.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case HC.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,s,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._scene?.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._scene?.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=ge.Matrix[0],fe.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const e=this.emitter;i=ge.Matrix[0],fe.TranslationToRef(e.x,e.y,e.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return e||t||(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),r=this.blendMode===HC.BLENDMODE_MULTIPLYADD?this._render(HC.BLENDMODE_MULTIPLY,i)+this._render(HC.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}rebuild(){const e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?(this._initialize(!0),this._rebuildingAfterContextLost=!1):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?r.shaderOptions.defines.join("\n"):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=XC.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return HC._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,a;t instanceof ki?o=t:(a=t,o=a.getEngine());const l=new XC(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",s=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(s,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),HC._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),s||l.preventAutoStart||l.start(),l}}class YC{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const s=Eu("emitterSphere",{diameter:e.diameter,segments:e.segments},i);s.renderingGroupId=t;const r=new yc("emitterSphereMaterial",i);r.emissiveColor=e.color,s.material=r;for(const e of this.systems)e.emitter=s;this._emitterNode=s}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,s){const r=new YC,n=this.BaseAssetsUrl+"/textures/";t=t||se.LastCreatedScene;for(const o of e.systems)r.systems.push(i?XC.Parse(o,t,n,!0,s):HC.Parse(o,t,n,!0,s));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&r.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:Ce.FromArray(i.color)},e.emitter.renderingGroupId,t)}return r}}YC.BaseAssetsUrl="https://assets.babylonjs.com/particles";class QC{static CreateDefault(e,t=500,i,s=!1){let r;return r=s?new XC("default system",{capacity:t},i):new HC("default system",t,i),r.emitter=e,r.particleTexture=new Vo("https://assets.babylonjs.com/textures/flare.png",r.getScene()),r.createConeEmitter(.1,Math.PI/4),r.color1=new Ee(1,1,1,1),r.color2=new Ee(1,1,1,1),r.colorDead=new Ee(1,1,1,0),r.minSize=.1,r.maxSize=.1,r.minEmitPower=2,r.maxEmitPower=2,r.updateSpeed=1/60,r.emitRate=30,r}static CreateAsync(e,t,i=!1,s){t||(t=se.LastCreatedScene);const r={};return t.addPendingData(r),new Promise(((n,o)=>{if(i&&!XC.IsSupported)return t.removePendingData(r),o("Particle system with GPU is not supported.");hs.LoadFile(`${QC.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(r);const o=JSON.parse(e.toString());return n(YC.Parse(o,t,i,s))}),void 0,void 0,void 0,(()=>(t.removePendingData(r),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new YC;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,s=!1,r="",n){return new Promise(((o,a)=>{const l=new At;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=s?XC.Parse(t,i,r,!1,n):HC.Parse(t,i,r,!1,n),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,s="",r){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((n,o)=>{const a=new At;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?XC.Parse(l,t,s,!1,r):HC.Parse(l,t,s,!1,r),h.snippetId=e,n(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}QC.BaseAssetsUrl=YC.BaseAssetsUrl,QC.SnippetUrl="https://snippet.babylonjs.com",QC.CreateFromSnippetAsync=QC.ParseFromSnippetAsync,G.AddParser(Rs.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=G.GetIndividualParser(Rs.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;ne.activeParticleCount?XC.Parse(e,t,i):HC.Parse(e,t,i))),gn.prototype.createEffectForParticles=function(e,t=[],i=[],s="",r,n,o,a){let l=[],h=[];const c=[];return a?a.fillUniformsAttributesAndSamplerNames(h,l,c):(l=HC._GetAttributeNamesOrOptions(),h=HC._GetEffectCreationOptions()),-1===s.indexOf(" BILLBOARD")&&(s+="\n#define BILLBOARD\n"),a?.isAnimationSheetEnabled&&-1===s.indexOf(" ANIMATESHEET")&&(s+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:a?.vertexShaderName??"particles",fragmentElement:e},l,h.concat(t),c.concat(i),s,r,n,o)},bo.prototype.getEmittedParticleSystems=function(){const e=[];for(let t=0;tt.sqDistance-e.sqDistance,this._materialSortFunction=(e,t)=>e.materialIndex-t.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||se.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=!!i?.computeBoundingBox&&i.computeBoundingBox,this._autoFixFaceOrientation=!!i?.autoFixFaceOrientation&&i.autoFixFaceOrientation,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new _o(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new qC}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){const e=Nu("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const e=new bo(this.name,this._scene);this.mesh=e}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&cn.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new cn;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,ys.PositionKind),e.set(this._normals32,ys.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,ys.UVKind),this._colors32.length>0&&e.set(this._colors32,ys.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let e=0;for(let t=0;td?d:s,i=Math.round(d/s),r=0):i=i>d?d:i;const _=[],p=[],f=[],m=[],g=[],v=de.Zero(),x=i;for(;ud-i&&(i=d-u),_.length=0,p.length=0,f.length=0,m.length=0,g.length=0;let t=0;for(let e=3*u;e<3*(u+i);e++){f.push(t);const i=o[e],s=3*i;if(_.push(n[s],n[s+1],n[s+2]),p.push(h[s],h[s+1],h[s+2]),a){const e=2*i;m.push(a[e],a[e+1])}if(l){const e=4*i;g.push(l[e],l[e+1],l[e+2],l[e+3])}t++}let s=this.nbParticles;const b=this._posToShape(_),T=this._uvsToShapeUV(m),y=f.slice(),S=g.slice(),C=p.slice();let E;for(v.copyFromFloats(0,0,0),E=0;E65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const e=null!==b.materialIndex?b.materialIndex:0;this.depthSortedParticles.push(new $C(d,t,r.length,e))}return b}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const s=this.particles,r=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh.getBoundingInfo();e&&(v.copyFrom(e.minimum),x.copyFrom(e.maximum))}A=this.particles[e]._pos;const D=A/3|0;R=4*D,M=2*D;for(let i=e;i<=t;i++){const e=this.particles[i];this.updateParticle(e);const t=e._model._shape,r=e._model._shapeUV,c=e._rotationMatrix,u=e.position,D=e.rotation,w=e.scaling,N=e._globalPosition;if(_){const t=this.depthSortedParticles[i];t.idx=e.idx,t.ind=e._ind,t.indicesLength=e._model._indicesLength,t.sqDistance=de.DistanceSquared(e.position,b)}if(e.alive&&(!e._stillInvisible||e.isVisible||this._recomputeInvisibles)){if(e.isVisible){e._stillInvisible=!1;const i=p[12];if(e.pivot.multiplyToRef(w,i),this.billboard&&(D.x=0,D.y=0),(this._computeParticleRotation||this.billboard)&&e.getRotationMatrix(s),null!==e.parentId){const t=this.getParticleById(e.parentId);if(t){const e=t._rotationMatrix,i=t._globalPosition,r=u.x*e[1]+u.y*e[4]+u.z*e[7],n=u.x*e[0]+u.y*e[3]+u.z*e[6],o=u.x*e[2]+u.y*e[5]+u.z*e[8];if(N.x=i.x+n,N.y=i.y+r,N.z=i.z+o,this._computeParticleRotation||this.billboard){const t=s.m;c[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],c[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],c[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],c[3]=t[4]*e[0]+t[5]*e[3]+t[6]*e[6],c[4]=t[4]*e[1]+t[5]*e[4]+t[6]*e[7],c[5]=t[4]*e[2]+t[5]*e[5]+t[6]*e[8],c[6]=t[8]*e[0]+t[9]*e[3]+t[10]*e[6],c[7]=t[8]*e[1]+t[9]*e[4]+t[10]*e[7],c[8]=t[8]*e[2]+t[9]*e[5]+t[10]*e[8]}}else e.parentId=null}else if(N.x=u.x,N.y=u.y,N.z=u.z,this._computeParticleRotation||this.billboard){const e=s.m;c[0]=e[0],c[1]=e[1],c[2]=e[2],c[3]=e[4],c[4]=e[5],c[5]=e[6],c[6]=e[8],c[7]=e[9],c[8]=e[10]}const n=p[11];for(e.translateFromPivot?n.setAll(0):n.copyFrom(i),O=0;O0)for(let t=0;t(this._isReady=!0,this._buildMesh(e))))}_buildMesh(e){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new cn;t.set(this._positions32,ys.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,ys.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,ys.ColorKind));const s=new bo(this.name,this._scene);t.applyToMesh(s,this._updatable),this.mesh=s,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let r=e;return r||(r=new yc("point cloud material",this._scene),r.emissiveColor=new Ce(i,i,i),r.disableLighting=!0,r.pointsCloud=!0,r.pointSize=this._size),s.material=r,new Promise((e=>e(s)))}_addParticle(e,t,i,s){const r=new JC(e,t,i,s,this);return this.particles.push(r),r}_randomUnitVector(e){e.position=new de(Math.random(),Math.random(),Math.random()),e.color=new Ee(1,1,1,1)}_getColorIndicesForCoord(e,t,i,s){const r=e._groupImageData,n=i*(4*s)+4*t,o=[n,n+1,n+2,n+3],a=o[1],l=o[2],h=o[3],c=r[o[0]],u=r[a],d=r[l],_=r[h];return new Ee(c/255,u/255,d/255,_)}_setPointsColorOrUV(e,t,i,s,r,n,o,a){a=a??0,i&&e.updateFacetData();const l=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(ys.PositionKind);const c=e.getIndices(),u=e.getVerticesData(ys.UVKind+(a?a+1:"")),d=e.getVerticesData(ys.ColorKind),_=de.Zero();e.computeWorldMatrix();const p=e.getWorldMatrix();if(!p.isIdentity()){h=h.slice(0);for(let e=0;e1&&(Ie=1),Me<0&&(Me=0),Me>1&&(Me=1),Ce.HSVtoRGBToRef(Re,Ie,Me,we),pe.set(we.r,we.g,we.b,1)):pe=ie.set(Math.random(),Math.random(),Math.random(),1),Fe.color=new Ee(pe.x,pe.y,pe.z,pe.w),this._colors.push(pe.x,pe.y,pe.z,pe.w))}}_colorFromTexture(e,t,i){if(null===e.material)return we.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const s=e.material.getActiveTextures();if(0===s.length)return we.Warn(e.name+"has no usable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const r=e.clone();r.setEnabled(!1),this._promises.push(new Promise((e=>{No.WhenAllReady(s,(()=>{let n=t._textureNb;n<0&&(n=0),n>s.length-1&&(n=s.length-1);const o=()=>{t._groupImgWidth=s[n].getSize().width,t._groupImgHeight=s[n].getSize().height,this._setPointsColorOrUV(r,t,i,!0,!0,void 0,void 0,s[n].coordinatesIndex),r.dispose(),e()};t._groupImageData=null;const a=s[n].readPixels();a?a.then((e=>{t._groupImageData=e,o()})):o()}))})))}_calculateDensity(e,t,i){let s,r,n,o,a,l,h,c,u,d,_,p;const f=de.Zero(),m=de.Zero(),g=de.Zero(),v=de.Zero(),x=de.Zero(),b=de.Zero();let T;const y=[];let S=0;const C=i.length/3;for(let e=0;e0;e--){const t=y[e];if(0===t)E[e]=0;else{const i=(t-y[e-1])/t*A,s=Math.floor(i),r=i-s,n=s+Number(Math.random()3)&&(n=tE.Random);const o=e.getVerticesData(ys.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new eE(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),n===tE.Color?l._textureNb=s||0:s=s||new Ee(1,1,1,1),n){case tE.Color:this._colorFromTexture(e,l,!1);break;case tE.UV:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case tE.Random:this._setPointsColorOrUV(e,l,!1);break;case tE.Stated:this._setPointsColorOrUV(e,l,!1,void 0,void 0,s,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,s,r){let n=i||tE.Random;(isNaN(n)||n<0||n>3)&&(n=tE.Random);const o=e.getVerticesData(ys.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new eE(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),n===tE.Color?l._textureNb=s||0:s=s||new Ee(1,1,1,1),n){case tE.Color:this._colorFromTexture(e,l,!0);break;case tE.UV:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case tE.Random:this._setPointsColorOrUV(e,l,!0);break;case tE.Stated:this._setPointsColorOrUV(e,l,!0,void 0,void 0,s,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const s=ge.Matrix[0],r=this.mesh,n=this._colors32,o=this._positions32,a=this._uvs32,l=ge.Vector3,h=l[5].copyFromFloats(1,0,0),c=l[6].copyFromFloats(0,1,0),u=l[7].copyFromFloats(0,0,1),d=l[8].setAll(Number.MAX_VALUE),_=l[9].setAll(-Number.MAX_VALUE);fe.IdentityToRef(s);let p=0;if(this.mesh?.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh?.getBoundingInfo();e&&(d.copyFrom(e.minimum),_.copyFrom(e.maximum))}p=0;let f=0,m=0,g=0;for(let i=e;i<=t;i++){const e=this.particles[i];p=e.idx,f=3*p,m=4*p,g=2*p,this.updateParticle(e);const t=e._rotationMatrix,r=e.position,n=e._globalPosition;if(this._computeParticleRotation&&e.getRotationMatrix(s),null!==e.parentId){const i=this.particles[e.parentId],o=i._rotationMatrix,a=i._globalPosition,l=r.x*o[1]+r.y*o[4]+r.z*o[7],h=r.x*o[0]+r.y*o[3]+r.z*o[6],c=r.x*o[2]+r.y*o[5]+r.z*o[8];if(n.x=a.x+h,n.y=a.y+l,n.z=a.z+c,this._computeParticleRotation){const e=s.m;t[0]=e[0]*o[0]+e[1]*o[3]+e[2]*o[6],t[1]=e[0]*o[1]+e[1]*o[4]+e[2]*o[7],t[2]=e[0]*o[2]+e[1]*o[5]+e[2]*o[8],t[3]=e[4]*o[0]+e[5]*o[3]+e[6]*o[6],t[4]=e[4]*o[1]+e[5]*o[4]+e[6]*o[7],t[5]=e[4]*o[2]+e[5]*o[5]+e[6]*o[8],t[6]=e[8]*o[0]+e[9]*o[3]+e[10]*o[6],t[7]=e[8]*o[1]+e[9]*o[4]+e[10]*o[7],t[8]=e[8]*o[2]+e[9]*o[5]+e[10]*o[8]}}else if(n.x=0,n.y=0,n.z=0,this._computeParticleRotation){const e=s.m;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10]}const a=l[11];e.translateFromPivot?a.setAll(0):a.copyFrom(e.pivot);const v=l[0];v.copyFrom(e.position);const x=v.x-e.pivot.x,b=v.y-e.pivot.y,T=v.z-e.pivot.z;let y=x*t[0]+b*t[3]+T*t[6],S=x*t[1]+b*t[4]+T*t[7],C=x*t[2]+b*t[5]+T*t[8];y+=a.x,S+=a.y,C+=a.z;const E=o[f]=n.x+h.x*y+c.x*S+u.x*C,A=o[f+1]=n.y+h.y*y+c.y*S+u.y*C,P=o[f+2]=n.z+h.z*y+c.z*S+u.z*C;if(this._computeBoundingBox&&(d.minimizeInPlaceFromFloats(E,A,P),_.maximizeInPlaceFromFloats(E,A,P)),this._computeParticleColor&&e.color){const t=e.color,i=this._colors32;i[m]=t.r,i[m+1]=t.g,i[m+2]=t.b,i[m+3]=t.a}if(this._computeParticleTexture&&e.uv){const t=e.uv,i=this._uvs32;i[g]=t.x,i[g+1]=t.y}}return r&&(i&&(this._computeParticleColor&&r.updateVerticesData(ys.ColorKind,n,!1,!1),this._computeParticleTexture&&r.updateVerticesData(ys.UVKind,a,!1,!1),r.updateVerticesData(ys.PositionKind,o,!1,!1)),this._computeBoundingBox&&(r.hasBoundingInfo?r.getBoundingInfo().reConstruct(d,_,r._worldMatrix):r.buildBoundingInfo(d,_,r._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){this.mesh?.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){return this._isVisibilityBoxLocked||this.mesh?.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new de(-t,-t,-t),new de(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}Object.defineProperty(Sn.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),Sn.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Sn.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Sn.prototype.setPhysicsLinkWith=function(e,t,i,s){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,da.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:s}),this):this};class pE{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw vt("")}constructor(e,t=pE.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new de(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new mv;return this._physicsPlugin.raycast(e,t,s,i),s}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(iE||(iE={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(sE||(sE={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(rE||(rE={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(nE||(nE={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(oE||(oE={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(aE||(aE={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(lE||(lE={})),function(e){e[e.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",e[e.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",e[e.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"}(hE||(hE={}));class fE{constructor(e,t,i,s){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disablePreStep=!0,this.disableSync=!1,this._isDisposed=!1,this._shape=null,!s)return;const r=s.getPhysicsEngine();if(!r)throw new Error("No Physics Engine available.");if(this._physicsEngine=r,2!=r.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const n=r.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");this._physicsPlugin=n,e.rotationQuaternion||(e.rotationQuaternion=pe.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=t!=lE.DYNAMIC;const o=e;o.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,o):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,r.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}getClassName(){return"PhysicsBody"}clone(e){const t=new fE(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t.setMassProperties(this.getMassProperties()),t.setLinearDamping(this.getLinearDamping()),t.setAngularDamping(this.getAngularDamping()),t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}get motionType(){return this._motionType}set shape(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)}get shape(){return this._shape}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this.disableSync=e!=lE.DYNAMIC,this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new de;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new de;return this.getAngularVelocityToRef(t,e),t}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyAngularImpulse(e,t){this._physicsPlugin.applyAngularImpulse(this,e,t)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}getCollisionEndedObservable(){return this._physicsPlugin.getCollisionEndedObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}setCollisionEndedCallbackEnabled(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new de;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){if(this._pluginDataInstances?.length>0){const i=t||0,s=this.transformNode._thinInstanceDataStorage.matrixData;s&&e.set(s[16*i+12],s[16*i+13],s[16*i+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,s){this._physicsPlugin.addConstraint(this,e,t,i,s)}syncWithBone(e,t,i,s,r,n){const o=this.transformNode;if(o.rotationQuaternion)if(r){const i=ge.Quaternion[0];e.getRotationQuaternionToRef(lr.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(lr.WORLD,t,o.rotationQuaternion);const a=ge.Vector3[0],l=ge.Vector3[1];n||((n=ge.Vector3[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}iterateOverAllInstances(e){if(this._pluginDataInstances?.length>0)for(let t=0;t{this.dispose()}))}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new qr(new de(-.5,-.5,-.5),new de(.5,.5,.5))}_hasVertices(e){return e?.getTotalVertices()>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=ge.Vector3[0];t.copyFrom(e.extendSize),t.scaleInPlace(2),t.multiplyInPlace(this.transformNode.scaling),t.x=Math.abs(t.x),t.y=Math.abs(t.y),t.z=Math.abs(t.z);const i=ge.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.scaling),!this._options.center){const t=new de;t.copyFrom(e.center),t.multiplyInPlace(this.transformNode.scaling),this._options.center=t}switch(this.type){case nE.SPHERE:!this._options.radius&&xe.WithinEpsilon(t.x,t.y,1e-4)&&xe.WithinEpsilon(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(we.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(t.x,t.y,t.z)/2);break;case nE.CAPSULE:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new de(0,i.y+e,0),this._options.pointB=this._options.pointB??new de(0,i.y+t.y-e,0)}break;case nE.CYLINDER:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new de(0,i.y,0),this._options.pointB=this._options.pointB??new de(0,i.y+t.y,0)}break;case nE.MESH:case nE.CONVEX_HULL:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case nE.BOX:this._options.extents=this._options.extents??new de(t.x,t.y,t.z),this._options.rotation=this._options.rotation??pe.Identity()}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class FE{}class BE{constructor(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=rE.HINGE,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=rE.HINGE,this._init()}getAggregate(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]}_createColliders(){this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);const e=this._config;for(let t=0;t{this._syncBonesAndBoxes()})),this._syncBonesToPhysics())}ragdoll(){this._ragdollMode=!0,this._skeleton.bones.forEach((e=>{e.linkTransformNode(null)}));for(let e=0;e{e.dispose()}))}}class LE{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=ge.Matrix[0];if(fe.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof bo?this._addMesh(e,i):e instanceof To&&this._addMesh(e.sourceMesh,i),t){const t=ge.Matrix[1];e.computeWorldMatrix().invertToRef(t);const s=ge.Matrix[2];t.multiplyToRef(i,s),e.getChildMeshes(!1).filter((e=>!e.physicsBody)).forEach((e=>{const t=e.computeWorldMatrix(),i=ge.Matrix[3];t.multiplyToRef(s,i),e instanceof bo?this._addMesh(e,i):e instanceof To&&this._addMesh(e.sourceMesh,i)}))}}_addMesh(e,t){const i=e.getVerticesData(ys.PositionKind)||[],s=i.length/3,r=this._vertices.length;for(let e=0;e0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._bodies.delete(t.hpBodyId[0]);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))}initBodyInstances(e,t,i){const s=i._thinInstanceDataStorage?.instancesCount??0,r=i._thinInstanceDataStorage.matrixData;r&&(this._createOrUpdateBodyInstances(e,t,r,0,s,!1),e._pluginDataInstances.forEach(((t,i)=>{this._bodies.set(t.hpBodyId[0],{body:e,index:i})})))}_createOrUpdateBodyInstances(e,t,i,s,r,n){const o=ge.Quaternion[0],a=fe.Identity();for(let l=s;lr){this._createOrUpdateBodyInstances(e,n,s,r,i,!1);const t=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];t[0]||(t[0]=e.shape?._pluginData[0]);for(let s=r;s{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t)}),i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:de.FromArray(e[0]),mass:e[1],inertia:de.FromArray(e[2]),inertiaOrientation:pe.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),null!=i.mass&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case lE.STATIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case lE.ANIMATED:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case lE.DYNAMIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC)}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._internalSetMotionType(e,t)}),i)}getMotionType(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(s){case this._hknp.MotionType.STATIC:return lE.STATIC;case this._hknp.MotionType.KINEMATIC:return lE.ANIMATED;case this._hknp.MotionType.DYNAMIC:return lE.DYNAMIC}throw new Error("Unknown motion type: "+s)}setActivationControl(e,t){switch(t){case hE.ALWAYS_ACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case hE.ALWAYS_INACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case hE.SIMULATION_CONTROLLED:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED)}}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const e=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(e[0]==this._hknp.Result.RESULT_OK)return e[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(s)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,(e=>{e.userMassProps=t,this._internalUpdateMassProperties(e)}),i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(s)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearDamping(e.hpBodyId,t)}),i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularDamping(e.hpBodyId,t)}),i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getLinearVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetLinearVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}_applyToBodyOrInstances(e,t,i){if(e._pluginDataInstances?.length>0&&void 0===i)for(let i=0;i{this._hknp.HP_Body_ApplyImpulse(e.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))}),s)}applyAngularImpulse(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_ApplyAngularImpulse(e.hpBodyId,this._bVecToV3(t))}),i)}applyForce(e,t,i,s){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,s)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getAngularVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetAngularVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}setPhysicsBodyTransformation(e,t){const i=e.transformNode;if(e.numInstances>0){const t=i._thinInstanceDataStorage.matrixData;if(!t)return;const s=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),t,0,s,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}setTargetTransform(e,t,i,s){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetTargetQTransform(e.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])}),s)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetGravityFactor(e.hpBodyId,t)}),i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}initShape(e,t,i){switch(t){case nE.SPHERE:{const t=i.radius||1,s=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateSphere(s,t)[1]}break;case nE.BOX:{const t=i.rotation?this._bQuatToV4(i.rotation):[0,0,0,1],s=i.extents?this._bVecToV3(i.extents):[1,1,1],r=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateBox(r,t,s)[1]}break;case nE.CAPSULE:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCapsule(t,s,r)[1]}break;case nE.CONTAINER:e._pluginData=this._hknp.HP_Shape_CreateContainer()[1];break;case nE.CYLINDER:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCylinder(t,s,r)[1]}break;case nE.CONVEX_HULL:case nE.MESH:{const s=i.mesh;if(!s)throw new Error("No mesh provided to create physics shape.");{const r=!!i.includeChildMeshes,n=t!=nE.CONVEX_HULL,o=new LE(s,n,s?.getScene());o.addNodeMeshes(s,r);const a=o.getVertices(this._hknp),l=a.numObjects/3;if(t==nE.CONVEX_HULL)e._pluginData=this._hknp.HP_Shape_CreateConvexHull(a.offset,l)[1];else{const t=o.getTriangles(this._hknp),i=t.numObjects/3;e._pluginData=this._hknp.HP_Shape_CreateMesh(a.offset,l,t.offset,i)[1],o.freeBuffer(this._hknp,t)}o.freeBuffer(this._hknp,a)}}break;case nE.HEIGHTFIELD:if(!(i.numHeightFieldSamplesX&&i.numHeightFieldSamplesZ&&i.heightFieldSizeX&&i.heightFieldSizeZ&&i.heightFieldData))throw new Error("Missing required heightfield parameters");{const t=i.numHeightFieldSamplesX*i.numHeightFieldSamplesZ,s=4*t,r=this._hknp._malloc(s),n=new Float32Array(this._hknp.HEAPU8.buffer,r,t);for(let e=0;e0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],s=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(s[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const r=this._hknp.HP_DebugGeometry_GetInfo(s[1])[1],n=new Float32Array(this._hknp.HEAPU8.buffer,r[0],3*r[1]),o=new Uint32Array(this._hknp.HEAPU8.buffer,r[2],3*r[3]),a=n.slice(0),l=o.slice(0);return this._hknp.HP_DebugGeometry_Release(s[1]),{positions:a,indices:l}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,s,r){const n=e.type,o=e.options;if(!n||!o)return void we.Warn("No constraint type or options. Constraint is invalid.");if(t._pluginDataInstances.length>0&&void 0===s||i._pluginDataInstances.length>0&&void 0===r)return void we.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");e._pluginData=e._pluginData??[];const a=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(a);const l=this._getPluginReference(t,s).hpBodyId,h=this._getPluginReference(i,r).hpBodyId;this._hknp.HP_Constraint_SetParentBody(a,l),this._hknp.HP_Constraint_SetChildBody(a,h),this._constraintToBodyIdPair.set(a[0],[l[0],h[0]]);const c=o.pivotA?this._bVecToV3(o.pivotA):this._bVecToV3(de.Zero()),u=o.axisA??new de(1,0,0),d=this._tmpVec3[0];o.perpAxisA?d.copyFrom(o.perpAxisA):u.getNormalToRef(d),this._hknp.HP_Constraint_SetAnchorInParent(a,c,this._bVecToV3(u),this._bVecToV3(d));const _=o.pivotB?this._bVecToV3(o.pivotB):this._bVecToV3(de.Zero()),p=o.axisB??new de(1,0,0),f=this._tmpVec3[0];if(o.perpAxisB?f.copyFrom(o.perpAxisB):p.getNormalToRef(f),this._hknp.HP_Constraint_SetAnchorInChild(a,_,this._bVecToV3(p),this._bVecToV3(f)),e._initOptions||(e._initOptions={axisA:u.clone(),axisB:p.clone(),perpAxisA:d.clone(),perpAxisB:f.clone(),pivotA:new de(c[0],c[1],c[2]),pivotB:new de(_[0],_[1],_[2])}),n==rE.LOCK)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==rE.DISTANCE){const e=o.maxDistance||0,t=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e)}else if(n==rE.HINGE)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==rE.PRISMATIC)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==rE.SLIDER)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==rE.BALL_AND_SOCKET)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else{if(n!=rE.SIX_DOF)throw new Error("Unsupported Constraint Type.");{const t=e;for(const e of t.limits){const t=this._constraintAxisToNative(e.axis);0==(e.minLimit??-1)&&0==(e.maxLimit??-1)?this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LOCKED):(null!=e.minLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e.minLimit)),null!=e.maxLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e.maxLimit))),e.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(a,t,e.stiffness),e.damping&&this._hknp.HP_Constraint_SetAxisDamping(a,t,e.damping)}}}const m=!!o.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(a,m),this._hknp.HP_Constraint_SetEnabled(a,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const e=this._constraintToBodyIdPair.get(i[0]);if(e){const i=this._bodies.get(e[0]),s=this._bodies.get(e[1]);i&&s&&t.push({parentBody:i.body,parentBodyIndex:i.index,childBody:s.body,childBodyIndex:s.index})}}return t}addConstraint(e,t,i,s,r){this.initConstraint(i,e,t,s,r)}setEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetEnabled(i,t)}getEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetEnabled(t)[1]}setCollisionsEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetCollisionsEnabled(i,t)}getCollisionsEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]}setAxisFriction(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(s,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null}setAxisMode(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(s,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const e=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(e)}return null}setAxisMinLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(s,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMaxLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(s,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMotorType(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(s,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null}setAxisMotorTarget(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(s,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null}setAxisMotorMaxForce(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(s,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null}disposeConstraint(e){for(const t of e._pluginData)this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t);e._pluginData.length=0}_populateHitData(e,t){const i=this._bodies.get(e[0][0]);t.body=i?.body,t.bodyIndex=i?.index;const s=this._shapes.get(e[1][0]);t.shape=s;const r=e[3],n=e[4],o=e[5];t.setHitData({x:n[0],y:n[1],z:n[2]},{x:r[0],y:r[1],z:r[2]},o)}raycast(e,t,i,s){const r=s?.membership??-1,n=s?.collideWith??-1;i.reset(e,t);const o=[BigInt(0)],a=[this._bVecToV3(e),this._bVecToV3(t),[r,n],!1,o];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[,e]=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1];this._populateHitData(e,i),i.calculateHitDistance()}}pointProximity(e,t){const i=e?.collisionFilter?.membership??-1,s=e?.collisionFilter?.collideWith??-1;t.reset();const r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[this._bVecToV3(e.position),e.maxDistance,[i,s],e.shouldHitTriggers,r];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,i]=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1];this._populateHitData(i,t),t.setHitDistance(e)}}shapeProximity(e,t,i){t.reset(),i.reset();const s=e.shape._pluginData,r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[s,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,r];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,s,r]=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1];this._populateHitData(s,t),this._populateHitData(r,i),t.setHitDistance(e),i.setHitDistance(e)}}shapeCast(e,t,i){t.reset(),i.reset();const s=e.shape._pluginData,r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[s,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,r];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,s,r]=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1];this._populateHitData(s,t),this._populateHitData(r,i),t.setHitFraction(e),i.setHitFraction(e)}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new X,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new X,this._bodyCollisionEndedObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t?i:0)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}setCollisionEndedCallbackEnabled(e,t){const i=this._getPluginReference(e);let s=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];s=t?s|this._hknp.EventType.COLLISION_FINISHED.value:s&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,s)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,s)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new GE;for(;e;){GE.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),s=this._bodies.get(t.bodyIdB);if(i&&s){const e={collider:i.body,colliderIndex:i.index,collidedAgainst:s.body,collidedAgainstIndex:s.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(e)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new UE,i=Number(this.world);for(;e;){UE.readToRef(this._hknp.HEAPU8.buffer,e,t);const s=this._bodies.get(t.contactOnA.bodyId),r=this._bodies.get(t.contactOnB.bodyId);if(s&&r){const e={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeCollisionValueToCollisionType(t.type)};if(e.type===aE.COLLISION_FINISHED)this.onCollisionEndedObservable.notifyObservers(e);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const i=de.Dot(this._tmpVec3[0],t.contactOnA.normal);e.point=t.contactOnA.position,e.distance=i,e.impulse=t.impulseApplied,e.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(e)}if(this._bodyCollisionObservable.size&&e.type!==aE.COLLISION_FINISHED){const i=this._bodyCollisionObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionObservable.get(t.contactOnB.bodyId);i?i.notifyObservers(e):n&&(e.collider=r.body,e.colliderIndex=r.index,e.collidedAgainst=s.body,e.collidedAgainstIndex=s.index,e.normal=t.contactOnB.normal,n.notifyObservers(e))}else if(this._bodyCollisionEndedObservable.size){const i=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);i?i.notifyObservers(e):n&&(e.collider=r.body,e.colliderIndex=r.index,e.collidedAgainst=s.body,e.collidedAgainstIndex=s.index,e.normal=t.contactOnB.normal,n.notifyObservers(e))}}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=BigInt(0),this._hknp.HP_World_Release(this.world),this.world=void 0}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case oE.POSITION:return this._hknp.ConstraintMotorType.POSITION;case oE.VELOCITY:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return oE.POSITION;case this._hknp.ConstraintMotorType.VELOCITY:return oE.VELOCITY}return oE.NONE}_materialCombineToNative(e){switch(e){case cE.GEOMETRIC_MEAN:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case cE.MINIMUM:return this._hknp.MaterialCombine.MINIMUM;case cE.MAXIMUM:return this._hknp.MaterialCombine.MAXIMUM;case cE.ARITHMETIC_MEAN:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case cE.MULTIPLY:return this._hknp.MaterialCombine.MULTIPLY}}_nativeToMaterialCombine(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return cE.GEOMETRIC_MEAN;case this._hknp.MaterialCombine.MINIMUM:return cE.MINIMUM;case this._hknp.MaterialCombine.MAXIMUM:return cE.MAXIMUM;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return cE.ARITHMETIC_MEAN;case this._hknp.MaterialCombine.MULTIPLY:return cE.MULTIPLY;default:return}}_constraintAxisToNative(e){switch(e){case sE.LINEAR_X:return this._hknp.ConstraintAxis.LINEAR_X;case sE.LINEAR_Y:return this._hknp.ConstraintAxis.LINEAR_Y;case sE.LINEAR_Z:return this._hknp.ConstraintAxis.LINEAR_Z;case sE.ANGULAR_X:return this._hknp.ConstraintAxis.ANGULAR_X;case sE.ANGULAR_Y:return this._hknp.ConstraintAxis.ANGULAR_Y;case sE.ANGULAR_Z:return this._hknp.ConstraintAxis.ANGULAR_Z;case sE.LINEAR_DISTANCE:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return iE.FREE;case this._hknp.ConstraintAxisLimitMode.LIMITED:return iE.LIMITED;case this._hknp.ConstraintAxisLimitMode.LOCKED:return iE.LOCKED}return iE.FREE}_limitModeToNative(e){switch(e){case iE.FREE:return this._hknp.ConstraintAxisLimitMode.FREE;case iE.LIMITED:return this._hknp.ConstraintAxisLimitMode.LIMITED;case iE.LOCKED:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return aE.COLLISION_STARTED;case this._hknp.EventType.COLLISION_FINISHED.value:return aE.COLLISION_FINISHED;case this._hknp.EventType.COLLISION_CONTINUED.value:return aE.COLLISION_CONTINUED}return aE.COLLISION_STARTED}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return aE.TRIGGER_ENTERED;case 16:return aE.TRIGGER_EXITED}return aE.TRIGGER_ENTERED}}dr.prototype.getPhysicsEngine=function(){return this._physicsEngine},dr.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(Rs.NAME_PHYSICSENGINE);i||(i=new WE(this),this._addComponent(i));try{if(t&&1!==t?.getPluginVersion()){if(2!==t?.getPluginVersion())throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new pE(e,t)}else this._physicsEngine=new gv(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return we.Error(e.message),!1}},dr.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},dr.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},dr.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},dr.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class WE{constructor(e){this.name=Rs.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new X,this.scene.onAfterPhysicsObservable=new X,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(xn.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),xn.prototype.getPhysicsBody=function(){return this.physicsBody},xn.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},xn.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};class HE{static GetContactPointToRef(e,t,i,s,r){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(1===o){const r=new Zo(t,i).intersectsMesh(e);if(r.hit&&r.pickedPoint)return s.copyFrom(r.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(s,r),!0;return!1}static HasAppliedForces(e,t){return e.getMotionType(t)===lE.STATIC||0===(e.getMassProperties(t)?.mass??0)||0===e.transformNode?.getTotalVertices()}static IsInsideCylinder(e,t,i,s){const r=ge.Vector3[0];return e.subtractToRef(t,r),Math.abs(r.x)<=i&&Math.abs(r.z)<=i&&r.y>=0&&r.y<=s}}class XE{constructor(e){this._hitData={force:new de,contactPoint:new de,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||we.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}applyRadialExplosionImpulse(e,t,i,s){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let r=!1;if("number"==typeof t){const e=t;(t=new $E).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new YE(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyImpulse(o.force,o.contactPoint),r&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,r,((e,t)=>{e.applyImpulse(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}applyRadialExplosionForce(e,t,i,s){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let r=!1;if("number"==typeof t){const e=t;(t=new $E).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new YE(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyForce(o.force,o.contactPoint),r&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,r,((e,t)=>{e.applyForce(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}_applicationForBodies(e,t,i,s,r){const n=Array(),o=this._physicsEngine.getBodies();for(const a of o)a.iterateOverAllInstances(((o,a)=>{e.getBodyHitData(o,t,i,a)&&(r(o,i),s&&n.push({body:o,hitData:this._copyPhysicsHitData(i)}))}));e.triggerAffectedBodiesCallback(n)}gravitationalField(e,t,i,s){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new $E).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}const r=new QE(this,this._scene,e,t);return r.dispose(!1),r}updraft(e,t,i,s,r){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new qE).radius=e,t.strength=i??t.strength,t.height=s??t.height,t.updraftMode=r??t.updraftMode}const n=new jE(this._scene,e,t);return n.dispose(!1),n}vortex(e,t,i,s){if(!this._physicsEngine)return we.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new ZE).radius=e,t.strength=i??t.strength,t.height=s??t.height}const r=new KE(this._scene,e,t);return r.dispose(!1),r}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class YE{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new $E,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,s){const r=ge.Vector3[0];r.copyFrom(t).subtractInPlace(i);const n=ge.Vector3[1];if(!HE.GetContactPointToRef(e,i,r,n,s.instanceIndex))return!1;const o=de.Distance(i,n);if(o>this._options.radius)return!1;const a=this._options.falloff===uE.Constant?this._options.strength:this._options.strength*(1-o/this._options.radius);return r.scaleInPlace(a),s.force.copyFrom(r),s.contactPoint.copyFrom(n),s.distanceFromOrigin=o,!0}getBodyHitData(e,t,i,s){if(HE.HasAppliedForces(e,s))return!1;const r=e.transformNode,n=e.getObjectCenterWorld(s);return i.instanceIndex=s,this._getHitData(r,n,t,i)}getImpostorHitData(e,t,i){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const s=e.object;if(!this._intersectsWithSphere(s,t,this._options.radius))return!1;const r=e.getObjectCenter();return this._getHitData(s,r,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_prepareSphere(){this._sphere||(this._sphere=Eu("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class QE{constructor(e,t,i,s){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=s,this._dataFetched=!1,this._options={...new $E,...this._options},this._tickCallback=()=>this._tick(),this._options.strength=-1*this._options.strength}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_tick(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);e&&(this._sphere=e.getData().sphere?.clone("radialExplosionEventSphereClone"))}}}class jE{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=de.Zero(),this._originDirection=de.Zero(),this._cylinderPosition=de.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new qE,...this._options},this._origin.addToRef(new de(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new de(0,this._options.height,0),this._originTop),this._options.updraftMode===dE.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===dE.Perpendicular?this._originDirection:e.subtract(this._originTop);const s=de.Distance(this._origin,e),r=-1*this._options.strength,n=i.multiplyByFloats(r,r,r);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=s}_getBodyHitData(e,t,i){if(HE.HasAppliedForces(e))return!1;const s=e.getObjectCenterWorld(i);return!!HE.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(s,t),!0}_tick(){const e=jE._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=lu("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}jE._HitData={force:new de,contactPoint:new de,distanceFromOrigin:0};class KE{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=de.Zero(),this._cylinderPosition=de.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new ZE,...this._options},this._origin.addToRef(new de(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new de(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const s=KE._OriginOnPlane;s.set(this._origin.x,t.y,this._origin.z);const r=ge.Vector3[0];t.subtractToRef(s,r);const n=ge.Vector3[1];if(!HE.GetContactPointToRef(e,s,r,n,i.instanceIndex))return!1;const o=de.Distance(n,s)/this._options.radius,a=ge.Vector3[2];let l,h,c;if(n.normalizeToRef(a),o>this._options.centripetalForceThreshold&&a.negateInPlace(),o>this._options.centripetalForceThreshold)l=a.x*this._options.centripetalForceMultiplier,h=a.y*this._options.updraftForceMultiplier,c=a.z*this._options.centripetalForceMultiplier;else{const e=de.Cross(s,t).normalize();l=(e.x+a.x)*this._options.centrifugalForceMultiplier,h=this._originTop.y*this._options.updraftForceMultiplier,c=(e.z+a.z)*this._options.centrifugalForceMultiplier}const u=ge.Vector3[3];return u.set(l,h,c),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=o,!0}_getBodyHitData(e,t,i){if(HE.HasAppliedForces(e,i))return!1;const s=e.transformNode,r=e.getObjectCenterWorld(i);return!!HE.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,r,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(i,s,t),!0}_tick(){const e=KE._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=lu("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}KE._OriginOnPlane=de.Zero(),KE._HitData={force:new de,contactPoint:new de,distanceFromOrigin:0};class $E{constructor(){this.radius=5,this.strength=10,this.falloff=uE.Constant,this.sphere={segments:32,diameter:1}}}class qE{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=dE.Center}}class ZE{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(uE||(uE={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(dE||(dE={}));class JE extends fv{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class eA extends fv{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}bi.ShadersStore.blackAndWhitePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";class tA extends qa{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,s){return yt.Parse((()=>new tA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([st()],tA.prototype,"degree",void 0),ee("BABYLON.BlackAndWhitePostProcess",tA);class iA{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=s.attachPostProcess(e);this._indicesForCamera[r].push(t)})),this._cameras[r]||(this._cameras[r]=s)}}_detachCameras(e){const t=hs.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=hs.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}bi.ShadersStore.extractHighlightsPixelShader="#include\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";class sA extends qa{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,Y)),e.setFloat("exposure",this._exposure)}))}}qe([st()],sA.prototype,"threshold",void 0),ee("BABYLON.ExtractHighlightsPostProcess",sA);bi.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";class rA extends qa{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}qe([st()],rA.prototype,"weight",void 0),ee("BABYLON.BloomMergePostProcess",rA);class nA extends iA{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new sA("highlights",1,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new pm("horizontal blur",new ue(1,0),10,t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new pm("vertical blur",new ue(0,1),10,t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new rA("bloomMerge",this._downscale,this._blurY,i,t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,s){return yt.Parse((()=>new oA(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}qe([st()],oA.prototype,"aberrationAmount",void 0),qe([st()],oA.prototype,"radialIntensity",void 0),qe([st()],oA.prototype,"direction",void 0),qe([st()],oA.prototype,"centerPosition",void 0),qe([st()],oA.prototype,"screenWidth",void 0),qe([st()],oA.prototype,"screenHeight",void 0),ee("BABYLON.ChromaticAberrationPostProcess",oA);bi.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";class aA extends qa{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void we.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}qe([st()],aA.prototype,"lensSize",void 0),qe([st()],aA.prototype,"fStop",void 0),qe([st()],aA.prototype,"focusDistance",void 0),qe([st()],aA.prototype,"focalLength",void 0),ee("BABYLON.CircleOfConfusionPostProcess",aA);bi.ShadersStore.colorCorrectionPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";class lA extends qa{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const a=s?.getScene()||null;this._colorTableTexture=new Vo(t,a,!0,!1,Vo.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Vo.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Vo.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return yt.Parse((()=>new lA(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([st()],lA.prototype,"colorTableUrl",void 0),ee("BABYLON.ColorCorrectionPostProcess",lA);bi.ShadersStore.convolutionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";class hA extends qa{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return yt.Parse((()=>new hA(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,s)}}hA.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],hA.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],hA.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],hA.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],hA.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],hA.GaussianKernel=[0,1,0,1,1,1,0,1,0],qe([st()],hA.prototype,"kernel",void 0),ee("BABYLON.ConvolutionPostProcess",hA);class cA extends pm{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=null,l=Vo.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,_=5){super(e,i,s,r,n,2,h,c,u,"#define DOF 1\n",d,_),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}qe([st()],cA.prototype,"direction",void 0),ee("BABYLON.DepthOfFieldBlurPostProcess",cA);bi.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";class uA extends qa{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,a,l,null,h,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(s.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,s,r,n)}}var dA;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(dA||(dA={}));class _A extends iA{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=dA.Low,s=0,r=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new aA("circleOfConfusion",t,1,null,Vo.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let a=1,l=15;switch(i){case dA.High:a=3,l=51;break;case dA.Medium:a=2,l=31;break;default:l=15,a=1}const h=l/Math.pow(2,a-1);let c=1;for(let t=0;tnew pA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ee("BABYLON.DisplayPassPostProcess",pA);bi.ShadersStore.filterPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";class fA extends qa{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return yt.Parse((()=>new fA(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([pt()],fA.prototype,"kernelMatrix",void 0),ee("BABYLON.FilterPostProcess",fA);bi.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();if(!e)return null;const t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,s){return yt.Parse((()=>new mA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ee("BABYLON.FxaaPostProcess",mA);bi.ShadersStore.grainPixelShader="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";class gA extends qa{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,s){return yt.Parse((()=>new gA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([st()],gA.prototype,"intensity",void 0),qe([st()],gA.prototype,"animated",void 0),ee("BABYLON.GrainPostProcess",gA);bi.ShadersStore.highlightsPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }";class vA extends qa{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0){super(e,"highlights",null,null,t,i,s,r,n,null,o)}}bi.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";class xA extends qa{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=se.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new xs}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,o=0,a){super(e,"imageProcessing",[],[],t,i,s,r,n,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines)this._defines[t]&&(e+=`#define ${t};\n`);const t=["textureSampler"],i=["scale"];xs&&(xs.PrepareSamplers(t,this._defines),xs.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}qe([st()],xA.prototype,"_fromLinearSpace",void 0);bi.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";bi.ShadersStore.geometryPixelShader="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[RENDER_TARGET_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";bi.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";bi.IncludesShadersStore.geometryUboDeclaration="#include\n";bi.ShadersStore.geometryVertexShader="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;vNormalW=normalUpdated;\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";const bA=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];An(bA);class TA{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((()=>{})))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===TA.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===TA.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===TA.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===TA.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===TA.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case TA.POSITION_TEXTURE_TYPE:return this._positionIndex;case TA.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case TA.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case TA.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case TA.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}constructor(e,t=1,i=15,s){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Ee(0,0,0,0),this._clearDepthColor=new Ee(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=s||{},TA._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[ys.PositionKind,ys.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&lc.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&s.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&s.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&s.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&s.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&s.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&s.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&s.push("#define REFLECTIVITYCOLOR"))}e&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(ys.UVKind)&&(r.push(ys.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(ys.UV2Kind)&&(r.push(ys.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),-1!==this._depthIndex&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&s.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&s.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(ys.MatricesIndicesKind),r.push(ys.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(ys.MatricesIndicesExtraKind),r.push(ys.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),s.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(s.push("#define NUM_BONE_INFLUENCERS 0"),s.push("#define BONETEXTURE false"),s.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let a=0;o&&(a=o.numMaxInfluencers||o.numInfluencers,a>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Fn(r,n,a))),t&&(s.push("#define INSTANCES"),Ln(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),Pn(i,this._scene,s);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=s.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:r,uniformsNames:bA,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),u),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[TA.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[TA.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[TA.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[TA.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[TA.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,s]=this._assignRenderTargetIndices();let r=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2);const n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],a=[];for(const e of s)e?(o.push(e.textureType),a.push(e.textureFormat)):(o.push(r),a.push(5));if(this._normalsAreUnsigned=11===o[TA.NORMAL_TEXTURE_TYPE]||13===o[TA.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new Ex("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:a,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Vo.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Vo.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],c=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:u),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(_),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(u)})),this._resizeObserver=e.onResizeObservable.add((()=>{if(this._multiRenderTarget){const t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}}));const p=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:fe.Identity(),viewProjection:s.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=r.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,a)){const h=e._getDrawWrapper();if(!h)return;const c=h.effect;let u;r.enableEffect(h),a||t._bind(e,c,n.fillMode),this._useUbo?(Vn(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",s.getTransformMatrix()),c.setMatrix("view",s.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!n.backFaceCulling&&null===t.overrideMaterialSideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=t.overrideMaterialSideOrientation,null===u&&(u=n.sideOrientation),e<0&&(u=u===uo.ClockWiseSideOrientation?uo.CounterClockWiseSideOrientation:uo.ClockWiseSideOrientation)}if(n._preBind(h,u),n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.bumpTexture&&s.getEngine().getCaps().standardDerivatives&&lc.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),In(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){const i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}kn(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),a&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,s)=>{if((s||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(r.length){for(e.setColorWrite(!1),n=0;n{throw vt("GeometryBufferRendererSceneComponent")};class yA{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(dr.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),dr.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new TA(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},dr.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class SA{constructor(e){this.name=Rs.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Rs.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}TA._SceneComponentInitialization=e=>{let t=e._getComponent(Rs.NAME_GEOMETRYBUFFERRENDERER);t||(t=new SA(e),e._addComponent(t))};bi.ShadersStore.motionBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";class CA extends qa{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new yA)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return we.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=fe.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new ue(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(TA.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=ge.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new ue(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(TA.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,s){return yt.Parse((()=>new CA(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}qe([st()],CA.prototype,"motionStrength",void 0),qe([st()],CA.prototype,"motionBlurSamples",null),qe([st()],CA.prototype,"isObjectBased",null),ee("BABYLON.MotionBlurPostProcess",CA);bi.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class EA extends qa{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,s,r,n,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Vo(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,s){return yt.Parse((()=>new EA(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}qe([st()],EA.prototype,"color",void 0),qe([st()],EA.prototype,"depth",void 0),qe([st()],EA.prototype,"colorLevel",void 0),qe([st()],EA.prototype,"refractionTextureUrl",void 0),ee("BABYLON.RefractionPostProcess",EA);bi.ShadersStore.sharpenPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";class AA extends qa{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return yt.Parse((()=>new AA(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}qe([st()],AA.prototype,"colorAmount",void 0),qe([st()],AA.prototype,"edgeAmount",void 0),ee("BABYLON.SharpenPostProcess",AA);class PA{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(hs.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(hs.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=hs.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}qe([st()],PA.prototype,"_name",void 0);class RA{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(dr.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(Rs.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new IA(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new RA}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class IA{constructor(e){this.name=Rs.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Rs.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class MA extends PA{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new nA(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen),!0),this.depthOfField=new _A(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add((()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new nA(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new oA("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,Vo.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new iA(o,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new gA("Grain",1,null,Vo.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new iA(o,this.GrainPostProcessId,(()=>this.grain),!0);let a=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,a?hs.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),a=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new xA("imageProcessing",1,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new iA(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new mA("fxaa",1,null,Vo.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new iA(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&we.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew MA(e._name,e._name._hdr,t)),e,t,i)}}qe([st()],MA.prototype,"sharpenEnabled",null),qe([st()],MA.prototype,"bloomKernel",null),qe([st()],MA.prototype,"_bloomWeight",void 0),qe([st()],MA.prototype,"_bloomThreshold",void 0),qe([st()],MA.prototype,"_hdr",void 0),qe([st()],MA.prototype,"bloomWeight",null),qe([st()],MA.prototype,"bloomThreshold",null),qe([st()],MA.prototype,"bloomScale",null),qe([st()],MA.prototype,"bloomEnabled",null),qe([st()],MA.prototype,"depthOfFieldEnabled",null),qe([st()],MA.prototype,"depthOfFieldBlurLevel",null),qe([st()],MA.prototype,"fxaaEnabled",null),qe([st()],MA.prototype,"samples",null),qe([st()],MA.prototype,"imageProcessingEnabled",null),qe([st()],MA.prototype,"glowLayerEnabled",null),qe([st()],MA.prototype,"chromaticAberrationEnabled",null),qe([st()],MA.prototype,"grainEnabled",null),ee("BABYLON.DefaultRenderingPipeline",MA);bi.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";bi.ShadersStore.depthOfFieldPixelShader="uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}\nif (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}\nif (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}\n";class OA extends PA{constructor(e,t,i,s=1,r){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=void 0!==t.dof_gain?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=void 0!==t.dof_focus_distance?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=void 0===t.dof_pentagon||t.dof_pentagon,this._blurNoise=void 0===t.blur_noise||t.blur_noise,this._createChromaticAberrationPostProcess(s),this._createHighlightsPostProcess(s),this._createDepthOfFieldPostProcess(s/4),this.addEffect(new iA(i.getEngine(),this.LensChromaticAberrationEffect,(()=>this._chromaticAberrationPostProcess),!0)),this.addEffect(new iA(i.getEngine(),this.HighlightsEnhancingEffect,(()=>this._highlightsPostProcess),!0)),this.addEffect(new iA(i.getEngine(),this.LensDepthOfFieldEffect,(()=>this._depthOfFieldPostProcess),!0)),-1===this._highlightsGain&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),r&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new qa("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,Vo.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=e=>{e.setFloat("chromatic_aberration",this._chromaticAberration),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new qa("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,Vo.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=e=>{e.setFloat("gain",this._highlightsGain),e.setFloat("threshold",this._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new qa("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,Vo.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=e=>{e.setTexture("depthSampler",this._depthTexture),e.setTexture("grainSampler",this._grainTexture),e.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),e.setFloat("grain_amount",this._grainAmount),e.setBool("blur_noise",this._blurNoise),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("distortion",this._distortion),e.setBool("dof_enabled",-1!==this._dofDistance),e.setFloat("screen_distance",1/(.1-1/this._dofDistance)),e.setFloat("aperture",this._dofAperture),e.setFloat("darken",this._dofDarken),e.setFloat("edge_blur",this._edgeBlur),e.setBool("highlights",-1!==this._highlightsGain),this._scene.activeCamera&&(e.setFloat("near",this._scene.activeCamera.minZ),e.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){const e=new Uint8Array(1048576);for(let t=0;t1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;const t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,s=1-.85*e,r=Math.sqrt(1-s*s);return new de(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===Kr.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",wA.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const t=this._scene.getEngine().getRenderWidth()/2,i=this._scene.getEngine().getRenderHeight()/2,s=this._scene.activeCamera.orthoLeft??-t,r=this._scene.activeCamera.orthoRight??t,n=this._scene.activeCamera.orthoBottom??-i,o=this._scene.activeCamera.orthoTop??i;e.setMatrix3x3("depthProjection",wA.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(r-s)),e.setFloat("yViewport",.5*(o-n))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new DA)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new qa("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",ge.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const e=new Uint8Array(65536),t=ue.Zero();for(let i=0;inew wA(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}wA.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],wA.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],qe([st()],wA.prototype,"totalStrength",void 0),qe([st()],wA.prototype,"maxZ",void 0),qe([st()],wA.prototype,"minZAspect",void 0),qe([st("epsilon")],wA.prototype,"_epsilon",void 0),qe([st("samples")],wA.prototype,"_samples",void 0),qe([st("textureSamples")],wA.prototype,"_textureSamples",void 0),qe([st()],wA.prototype,"_forceGeometryBuffer",void 0),qe([st()],wA.prototype,"_ratio",void 0),qe([st()],wA.prototype,"_textureType",void 0),qe([st()],wA.prototype,"radius",void 0),qe([st()],wA.prototype,"base",void 0),qe([st("bypassBlur")],wA.prototype,"_bypassBlur",void 0),qe([st("expensiveBlur")],wA.prototype,"_expensiveBlur",void 0),qe([st()],wA.prototype,"bilateralSamples",void 0),qe([st()],wA.prototype,"bilateralSoften",void 0),qe([st()],wA.prototype,"bilateralTolerance",void 0),ee("BABYLON.SSAO2RenderingPipeline",wA);bi.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)\n{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}\nvoid main()\n{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new iA(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new qa("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new qa("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Vo.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",ge.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const e=new Uint8Array(1048576);for(let t=0;t0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const i=this._geometryBufferRenderer,s=this._prePassRenderer;if(!s&&!i)return;if(i){const t=i.getTextureIndex(TA.POSITION_TEXTURE_TYPE),s=i.getTextureIndex(TA.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[s])}else if(s){const t=s.getIndex(1),i=s.getIndex(3),r=s.getIndex(6);e.setTexture("normalSampler",s.getRenderTarget().textures[r]),e.setTexture("positionSampler",s.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",s.getRenderTarget().textures[i])}const r=t.activeCamera;if(!r)return;const n=r.getViewMatrix(!0),o=r.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,s){return yt.Parse((()=>new BA(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}qe([st()],BA.prototype,"threshold",void 0),qe([st()],BA.prototype,"strength",void 0),qe([st()],BA.prototype,"reflectionSpecularFalloffExponent",void 0),qe([st()],BA.prototype,"step",void 0),qe([st()],BA.prototype,"roughnessFactor",void 0),qe([st()],BA.prototype,"enableSmoothReflections",null),qe([st()],BA.prototype,"reflectionSamples",null),qe([st()],BA.prototype,"smoothSteps",null),ee("BABYLON.ScreenSpaceReflectionPostProcess",BA);bi.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}\nvec3 pattern(vec2 uv)\n{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";class LA extends PA{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer())return void we.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,s=null,r){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new BA("HDRPass",t,e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new iA(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new qa("HDRPass","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.originalPostProcess})),this.addEffect(new iA(t.getEngine(),"HDRPassPostProcess",(()=>this.originalPostProcess),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new qa("HDRDepthOfFieldSource","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new iA(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new qa("HDRVLSFinal","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new iA(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new qa("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new iA(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new qa("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new iA(t.getEngine(),"HDRPostHDReDepthOfFieldSource",(()=>this.hdrFinalPostProcess),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new mA("fxaa",1,null,Vo.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new iA(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&we.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new qa("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const s=this.downSampleX4PostProcess.width,r=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/s),i[t+1]=(n+.5)*(1/r),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new iA(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new qa("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,s=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*s,i[2]=.5*t,i[3]=.5*s,i[4]=-.5*t,i[5]=-.5*s,i[6]=.5*t,i[7]=-.5*s,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new iA(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new pm("HDRBlurH_"+i,new ue(1,0),this[s],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new pm("HDRBlurV_"+i,new ue(0,1),this[s],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add((()=>{const e=n.width/r.getRenderWidth();n.kernel=this[s]*e})),o.onActivateObservable.add((()=>{const e=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*e:this[s]*e})),this.addEffect(new iA(e.getEngine(),"HDRBlurH"+i,(()=>n),!0)),this.addEffect(new iA(e.getEngine(),"HDRBlurV"+i,(()=>o),!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new qa("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new iA(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new qa("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const r=ue.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",s.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",r)}},this.addEffect(new iA(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new qa("HDRVLSMerge","standard",[],["originalSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new iA(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,LA.LuminanceSteps);this.luminancePostProcess=new qa("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;s[0]=-.5*t,s[1]=.5*i,s[2]=.5*t,s[3]=.5*i,s[4]=-.5*t,s[5]=-.5*i,s[6]=.5*t,s[7]=-.5*i,e.setArray2("lumOffsets",s)},this.addEffect(new iA(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let s=LA.LuminanceSteps-1;s>=0;s--){i=Math.pow(3,s);let r="#define LUMINANCE_DOWN_SAMPLE\n";0===s&&(r+="#define FINAL_DOWN_SAMPLER");const n=new qa("HDRLuminanceDownSample"+s,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,t);this.luminanceDownSamplePostProcesses.push(n)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const s=new Array(18);t.onApply=e=>{if(!r)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)s[n]=e/r.width,s[n+1]=t/r.height,n+=2;e.setArray2("dsOffsets",s),e.setFloat("halfDestPixelSize",.5/r.width),r=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new _e(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new iA(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new qa("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const e=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*e?s-=this.hdrIncreaseRate*e:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=xe.Clamp(s,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new iA(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new qa("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new iA(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new qa("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new iA(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new ue(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=fe.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=fe.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let n=de.Dot(t.toVector3(),new de(1,0,0))+de.Dot(i.toVector3(),new de(0,0,1));n*=4;const o=fe.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),a=r.multiply(o).multiply(s);e.setMatrix("lensStarMatrix",a),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new qa("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new iA(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new CA("HDRMotionBlur",e,t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new qa("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Vo.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,s=fe.Identity();const r=fe.Identity();let n=fe.Identity();const o=ue.Zero();this.motionBlurPostProcess.onApply=t=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),t.setMatrix("inverseViewProjection",r),t.setMatrix("prevViewProjection",s),s=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",o),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new iA(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew LA(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&yt.Parse((()=>s.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),s}}LA.LuminanceSteps=6,qe([st()],LA.prototype,"brightThreshold",void 0),qe([st()],LA.prototype,"blurWidth",void 0),qe([st()],LA.prototype,"horizontalBlur",void 0),qe([st()],LA.prototype,"exposure",null),qe([rt("lensTexture")],LA.prototype,"lensTexture",void 0),qe([st()],LA.prototype,"volumetricLightCoefficient",void 0),qe([st()],LA.prototype,"volumetricLightPower",void 0),qe([st()],LA.prototype,"volumetricLightBlurScale",void 0),qe([st()],LA.prototype,"hdrMinimumLuminance",void 0),qe([st()],LA.prototype,"hdrDecreaseRate",void 0),qe([st()],LA.prototype,"hdrIncreaseRate",void 0),qe([st()],LA.prototype,"hdrAutoExposure",null),qe([rt("lensColorTexture")],LA.prototype,"lensColorTexture",void 0),qe([st()],LA.prototype,"lensFlareStrength",void 0),qe([st()],LA.prototype,"lensFlareGhostDispersal",void 0),qe([st()],LA.prototype,"lensFlareHaloWidth",void 0),qe([st()],LA.prototype,"lensFlareDistortionStrength",void 0),qe([st()],LA.prototype,"lensFlareBlurWidth",void 0),qe([rt("lensStarTexture")],LA.prototype,"lensStarTexture",void 0),qe([rt("lensFlareDirtTexture")],LA.prototype,"lensFlareDirtTexture",void 0),qe([st()],LA.prototype,"depthOfFieldDistance",void 0),qe([st()],LA.prototype,"depthOfFieldBlurWidth",void 0),qe([st()],LA.prototype,"motionStrength",null),qe([st()],LA.prototype,"objectBasedMotionBlur",null),qe([st()],LA.prototype,"_ratio",void 0),qe([st()],LA.prototype,"BloomEnabled",null),qe([st()],LA.prototype,"DepthOfFieldEnabled",null),qe([st()],LA.prototype,"LensFlareEnabled",null),qe([st()],LA.prototype,"HDREnabled",null),qe([st()],LA.prototype,"VLSEnabled",null),qe([st()],LA.prototype,"MotionBlurEnabled",null),qe([st()],LA.prototype,"fxaaEnabled",null),qe([st()],LA.prototype,"screenSpaceReflectionsEnabled",null),qe([st()],LA.prototype,"volumetricLightStepsCount",null),qe([st()],LA.prototype,"motionBlurSamples",null),qe([st()],LA.prototype,"samples",null),ee("BABYLON.StandardRenderingPipeline",LA);class kA{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}bi.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nndc.z=-projection[2].z-projection[3].z/depth;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n";bi.ShadersStore.screenSpaceReflection2PixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";bi.ShadersStore.screenSpaceReflection2BlurPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}\n";bi.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";const VA=fe.Compose(new de(.5,.5,.5),pe.Identity(),new de(.5,.5,.5)),UA=fe.Compose(new de(.5,.5,1),pe.Identity(),new de(.5,.5,0));class GA extends PA{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,s=!1,r=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const e=t.getRenderTarget();e&&e.textures&&(i=e.textures[t.getIndex(4)].getSize())}else this._ssrPostProcess?.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(this._geometryBufferRenderer?.generateNormalsInWorldSpace??this._prePassRenderer?.generateNormalsInWorldSpace)&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),this._geometryBufferRenderer?.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL"),this._ssrPostProcess?.updateEffect(e.join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const e=this._cameras?.[0];e&&(this._depthRendererCamera=e,this._depthRenderer=new $g(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),e.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new iA(e,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new iA(e,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new iA(e,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===s||this._depthRenderer.getDepthMap().resize({width:i,height:s})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;-1!==e&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){for(let e=0;e{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(TA.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),s=i.getIndex(3),r=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[r]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[s])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(),n=s.getProjectionMatrix();n.invertToRef(ge.Matrix[0]),r.invertToRef(ge.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",ge.Matrix[1]),e.setMatrix("invProjectionMatrix",ge.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();fe.ScalingToRef(o.width,o.height,1,ge.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?UA:VA,ge.Matrix[3]),ge.Matrix[3].multiplyToRef(ge.Matrix[2],ge.Matrix[4]),e.setMatrix("projectionPixel",ge.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new kA)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new qa("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{const t=this._blurPostProcessX?.inputTexture.width??this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/t,0)})),this._blurPostProcessY=new qa("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{const t=this._blurPostProcessY?.inputTexture.height??this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/t)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(s+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(s+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(s+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new qa("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(i||t){if(i&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const t=i.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[i.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(t){const i=t.getTextureIndex(TA.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this.useFresnel&&(e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("depthSampler",t.getGBuffer().textures[0]))}else if(i){const t=i.getIndex(3);if(e.setTexture("reflectivitySampler",i.getRenderTarget().textures[t]),this.useFresnel){const t=i.getIndex(5),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(ge.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",ge.Matrix[0])}}}}))}serialize(){const e=yt.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return yt.Parse((()=>new GA(e._name,t,e._ratio)),e,t,i)}}qe([st()],GA.prototype,"samples",null),qe([st()],GA.prototype,"maxDistance",void 0),qe([st()],GA.prototype,"step",void 0),qe([st()],GA.prototype,"thickness",void 0),qe([st()],GA.prototype,"strength",void 0),qe([st()],GA.prototype,"reflectionSpecularFalloffExponent",void 0),qe([st()],GA.prototype,"maxSteps",void 0),qe([st()],GA.prototype,"roughnessFactor",void 0),qe([st()],GA.prototype,"selfCollisionNumSkip",void 0),qe([st()],GA.prototype,"_reflectivityThreshold",void 0),qe([st("_ssrDownsample")],GA.prototype,"_ssrDownsample",void 0),qe([st()],GA.prototype,"ssrDownsample",null),qe([st("blurDispersionStrength")],GA.prototype,"_blurDispersionStrength",void 0),qe([st("blurDownsample")],GA.prototype,"_blurDownsample",void 0),qe([st("enableSmoothReflections")],GA.prototype,"_enableSmoothReflections",void 0),qe([st("environmentTexture")],GA.prototype,"_environmentTexture",void 0),qe([st("environmentTextureIsProbe")],GA.prototype,"_environmentTextureIsProbe",void 0),qe([st("attenuateScreenBorders")],GA.prototype,"_attenuateScreenBorders",void 0),qe([st("attenuateIntersectionDistance")],GA.prototype,"_attenuateIntersectionDistance",void 0),qe([st("attenuateIntersectionIterations")],GA.prototype,"_attenuateIntersectionIterations",void 0),qe([st("attenuateFacingCamera")],GA.prototype,"_attenuateFacingCamera",void 0),qe([st("attenuateBackfaceReflection")],GA.prototype,"_attenuateBackfaceReflection",void 0),qe([st("clipToFrustum")],GA.prototype,"_clipToFrustum",void 0),qe([st("useFresnel")],GA.prototype,"_useFresnel",void 0),qe([st("enableAutomaticThicknessComputation")],GA.prototype,"_enableAutomaticThicknessComputation",void 0),qe([st("backfaceDepthTextureDownsample")],GA.prototype,"_backfaceDepthTextureDownsample",void 0),qe([st("backfaceForceDepthWriteTransparentMeshes")],GA.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),qe([st("isEnabled")],GA.prototype,"_isEnabled",void 0),qe([st("inputTextureColorIsInGammaSpace")],GA.prototype,"_inputTextureColorIsInGammaSpace",void 0),qe([st("generateOutputInGammaSpace")],GA.prototype,"_generateOutputInGammaSpace",void 0),qe([st("debug")],GA.prototype,"_debug",void 0),ee("BABYLON.SSRRenderingPipeline",GA);bi.ShadersStore.taaPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}\n";class zA extends PA{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,s=0){const r=t.getEngine();super(r,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._hs=new jT(this.samples),this.isSupported&&(this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){const i=this._scene.getEngine();this._ping?.dispose(),this._pong?.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){this._taaPostProcess?.updateEffect([].join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new iA(e,this.TAARenderEffect,(()=>this._taaPostProcess),!0)),this._createPassPostProcess(),this.addEffect(new iA(e,this.TAAPassEffect,(()=>this._passPostProcess),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){for(let e=0;e{const e=this._scene.activeCamera;if(this._taaPostProcess?.width!==this._ping.width||this._taaPostProcess?.height!==this._ping.height){const e=this._scene.getEngine();this._createPingPongTextures(e.getRenderWidth(),e.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===Kr.PERSPECTIVE_CAMERA){const t=e.getProjectionMatrix();t.setRowFromFloats(2,this._hs.x,this._hs.y,t.m[10],t.m[11])}else{const t=e.getProjectionMatrix(!0);t.setRowFromFloats(3,this._hs.x+t.m[12],this._hs.y+t.m[13],t.m[14],t.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=1^this._pingpong,this._hs.next()})),this._taaPostProcess.onApplyObservable.add((e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t?.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1}))}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new Nh("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=yt.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return yt.Parse((()=>new zA(e._name,t,e._ratio)),e,t,i)}}qe([st("samples")],zA.prototype,"_samples",void 0),qe([st("msaaSamples")],zA.prototype,"_msaaSamples",void 0),qe([st()],zA.prototype,"factor",void 0),qe([st()],zA.prototype,"disableOnCameraMove",void 0),qe([st("isEnabled")],zA.prototype,"_isEnabled",void 0),ee("BABYLON.TAARenderingPipeline",zA);var WA;bi.ShadersStore.tonemapPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}",function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(WA||(WA={}));class HA extends qa{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,s,r=2,n,o=0,a){super(e,"tonemap",["_ExposureAdjustment"],null,1,s,r,n,a,null,o),this._operator=t,this.exposureAdjustment=i;let l="#define ";this._operator===WA.Hable?l+="HABLE_TONEMAPPING":this._operator===WA.Reinhard?l+="REINHARD_TONEMAPPING":this._operator===WA.HejiDawson?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===WA.Photographic&&(l+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(l),this.onApply=e=>{e.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}}bi.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const s=i._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(i,e,t);const r=[],n=[ys.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&r.push("#define ALPHATEST"),i.isVerticesDataPresent(ys.UVKind)&&(n.push(ys.UVKind),r.push("#define UV1")),i.isVerticesDataPresent(ys.UV2Kind)&&(n.push(ys.UV2Kind),r.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(n.push(ys.MatricesIndicesKind),n.push(ys.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),r.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),Ln(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const a=e._getDrawWrapper(void 0,!0),l=a.defines,h=r.join("\n");return l!==h&&a.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),h),a.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new pl("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Vo.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Vo.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh();if(this._meshExcluded(t))return;i._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=t.getScene(),n=r.getEngine();n.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances);if(this._isReady(e,a)){const l=i._internalAbstractMeshDataInfo._materialForRenderPass?.[n.currentRenderPassId];let h=e._getDrawWrapper();if(t!==this.mesh||h||(h=s._getDrawWrapper()),!h)return;const c=h.effect;if(n.enableEffect(h),a||t._bind(e,c,s.fillMode),t===this.mesh)s.bind(i.getWorldMatrix(),t);else if(l)l.bindForSubMesh(i.getWorldMatrix(),i,e);else{if(c.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&c.setMatrices("mBones",t.skeleton.getTransformMatrices(t))}a&&t.hasThinInstances&&c.setMatrix("world",i.getWorldMatrix()),t._processRendering(i,e,c,uo.TriangleFillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}};let n;const o=new Ee(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{n=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=n})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,s)=>{if((s||0===t)&&e.subMeshes)for(let t=0;t{const o=e.getEngine();let a;if(n.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):we.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=se.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,s){return yt.Parse((()=>new YA(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}qe([st()],YA.prototype,"ridge",void 0),qe([st()],YA.prototype,"valley",void 0),ee("BABYLON.ScreenSpaceCurvaturePostProcess",YA);bi.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n";bi.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n";bi.ShadersStore.boundingBoxRendererPixelShader="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";bi.ShadersStore.boundingBoxRendererVertexShader="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n",Object.defineProperty(dr.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),dr.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new QA(this)),this._boundingBoxRenderer},Object.defineProperty(Sn.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class QA{constructor(e){this.name=Rs.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Ce(1,1,1),this.backColor=new Ce(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new X,this.onAfterBoxRenderingObservable=new X,this.onResourcesReadyObservable=new X,this.enabled=!0,this.renderList=new ds(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new bs(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new bs(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(Rs.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Rs.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Rs.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Rs.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new Yu("colorShader",this.scene,"boundingBoxRenderer",{attributes:[ys.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new Yu("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[ys.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=bu({size:1});this._vertexBuffers[ys.PositionKind]=new ys(e,t.positions,ys.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[ys.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let s=0;s{let t=e._getComponent(Rs.NAME_DEPTHRENDERER);t||(t=new jA(e),e._addComponent(t))};bi.ShadersStore.oitFinalPixelShader="precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";bi.ShadersStore.oitBackBlendPixelShader="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";class KA{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class $A{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new ds(10),this._excludedSubMeshes=new ds(10),this._excludedMeshes=[],this._colorCache=[new Ee($A._DEPTH_CLEAR_VALUE,$A._DEPTH_CLEAR_VALUE,0,0),new Ee(-$A._MIN_DEPTH,$A._MAX_DEPTH,0,0),new Ee(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.lineVertexShader="#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",Sn.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Sn.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new JA(this,e,t,!0,i),this},Object.defineProperty(Sn.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),Qu.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new eP(this,e,t),this},ju.prototype.enableEdgesRendering=function(e=.95,t=!1){return Qu.prototype.enableEdgesRendering.apply(this,arguments),this};class ZA{constructor(){this.edges=[],this.edgesConnectedCount=0}}class JA{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new Yu("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,r){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new ds(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Fi(e.getEngine())),this._prepareRessources(),s&&(r?.useAlternateEdgeFinder??1?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add((()=>{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=JA._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[ys.PositionKind];e&&e._rebuild(),e=this._buffers[ys.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[ys.PositionKind];e&&(e.dispose(),this._buffers[ys.PositionKind]=null),e=this._buffers[ys.NormalKind],e&&(e.dispose(),this._buffers[ys.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),this._drawWrapper?.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){const n=1e-10;return e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(s,n)||e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(i,n)?0:e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(r,n)||e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(s,n)?1:e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(i,n)||e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(r,n)?2:-1}_checkEdge(e,t,i,s,r){let n;n=void 0===t||de.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort(((e,t)=>e[1]t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--o)r(e[o%3],a,o!==n+2?s[i[t+(o+1)%3]]:-1);const h=a.length;i.push(s[i[t+n]],o[0],a[0]),i.push(s[i[t+(n+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,_=c?l-1:h-1,p=c?0:1;let f=l+h-2,m=0,g=0;const v=c?o:a,x=c?a:o;let b=0;for(;f-- >0;){let e;p?i.push(v[m],x[g]):i.push(x[g],v[m]),b+=u,b>=d&&m<_?(e=v[++m],b-=d):e=x[++g],i.push(e)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){const e=this._source.getVerticesData(ys.PositionKind);let t=this._source.getIndices();if(!t||!e)return;Array.isArray(t)||(t=Array.from(t));const i=this._options?.useFastVertexMerger??!0,s=i?Math.round(-Math.log(this._options?.epsilonVertexMerge??1e-6)/Math.log(10)):this._options?.epsilonVertexMerge??1e-6,r=[],n=[];if(i){const t={};for(let i=0;il){const e=a;a=l,l=e}const c=a+"_"+l,u=o[c];u?u.done||(de.Dot(s,u.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let r=0;if(s)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(r=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[r]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(s)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw vt("PrePassRendererSceneComponent")},iP.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(dr.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),dr.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new iP(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,we.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},dr.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class sP{constructor(e){this.name=Rs.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(Rs.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Rs.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Rs.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Rs.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Rs.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Rs.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Rs.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Rs.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}iP._SceneComponentInitialization=e=>{let t=e._getComponent(Rs.NAME_PREPASSRENDERER);t||(t=new sP(e),e._addComponent(t))};bi.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}";bi.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";bi.ShadersStore.subSurfaceScatteringPixelShader="#include\n#include\n#include\n#include\nvarying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void we.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class nP{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=Rs.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Ce(1,1,1)),this._scene=e,nP._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return we.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw vt("SubSurfaceSceneComponent")},G.AddParser(Rs.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,s=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(Rs.NAME_SUBSURFACE);t||(t=new oP(e),e._addComponent(t))};bi.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n",dr.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new aP(this)),this._outlineRenderer},Object.defineProperty(bo.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(bo.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class aP{constructor(e){this.name=Rs.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(Rs.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Rs.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{_.setMatrix("world",t)})),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[ys.PositionKind,ys.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(ys.UVKind)&&(r.push(ys.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(ys.UV2Kind)&&(r.push(ys.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),Pn(o,a,s),n.useBones&&n.computeBonesUsingShaders?(r.push(ys.MatricesIndicesKind),r.push(ys.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(ys.MatricesIndicesExtraKind),r.push(ys.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const l=n.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Fn(r,n,h))),t&&(s.push("#define INSTANCES"),Ln(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),u=c.defines,d=s.join("\n");if(u!==d){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];An(e),c.setEffect(this.scene.getEngine().createEffect("outline",r,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(aP._StencilReference),this._engine.setStencilFunctionReference(aP._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),s=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=s}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}aP._StencilReference=4;class lP{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){return!!this.vertexBuffers?.velocity}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new X,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new ll({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new ll({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){this._depthEffectWrapper?.dispose(),this._thicknessEffectWrapper?.dispose()}}class hP extends lP{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((()=>{this._engine.setAlphaMode(2)}))))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class cP{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,s,r,n,o=1,a=6,l=1,h=6,c=!1,u=null,d=!0,_=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new X,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=s,this._blurTextureSizeX=r,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=a,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=_,this._postProcessRunningIndex=0,this.enableBlur=0!==r&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Vo(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Vo.CLAMP_ADDRESSMODE,this._texture.wrapV=Vo.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,s,r,n=!1){const o=this._scene.getEngine(),a=new ue(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),l=1===t&&o.getCaps().textureFloatLinearFiltering||2===t&&o.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:a.x,height:a.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${r}`}),c=h.texture;c.incrementReferences();const u=new Vo(null,this._scene);if(u.name="rttBlurred"+r,u._texture=c,u.wrapU=Vo.CLAMP_ADDRESSMODE,u.wrapV=Vo.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,n){const s=new qa("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Vo.CLAMP_ADDRESSMODE,e.texture.wrapV=Vo.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new qa("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Vo.CLAMP_ADDRESSMODE,e.texture.wrapV=Vo.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?r:s;return[h,u,n]}{const s=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],r=new qa("BilateralBlurX","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Vo.CLAMP_ADDRESSMODE,e.texture.wrapV=Vo.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r);const n=new qa("BilateralBlurY","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Vo.CLAMP_ADDRESSMODE,e.texture.wrapV=Vo.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n),r.autoClear=!1,n.autoClear=!1;const a=[];for(let e=0;e<2*this._blurNumIterations;++e)a[e]=1&e?n:r;return[h,u,a]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((this._camera?.fov??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),this._rt?.dispose(),this._rt=null,this._texture?.dispose(),this._texture=null,this._rtBlur?.dispose(),this._rtBlur=null,this._textureBlurred?.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var uP;!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(uP||(uP={}));class dP{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Ce(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new de(-2,-1,1).normalize(),this._debugFeature=uP.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new X,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new fe,this._depthClearColor=new Ee(1e6,1e6,1e6,1),this._thicknessClearColor=new Ee(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new cP("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=this._diffuseMapSize??this._engine.getRenderWidth(),t=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new cP("Diffuse",this._scene,e,t,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),s=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new cP("Thickness",this._scene,i,s,i,s,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new ue(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===uP.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===uP.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),this._debugFeature!==uP.DepthTexture&&this._debugFeature!==uP.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new qa("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add((t=>{if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),e.isWebGPU&&t.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(t.setTexture("depthSampler",this._depthRenderTarget.textureBlur),e.isWebGPU&&t.setTextureSampler("depthSamplerSampler",this._depthRenderTarget.textureBlur?.getInternalTexture()??null)):(t.setTexture("depthSampler",this._depthRenderTarget.texture),e.isWebGPU&&t.setTextureSampler("depthSamplerSampler",this._depthRenderTarget.texture?.getInternalTexture()??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(t.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),e.isWebGPU&&t.setTextureSampler("diffuseSamplerSampler",this._diffuseRenderTarget.textureBlur?.getInternalTexture()??null)):(t.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),e.isWebGPU&&t.setTextureSampler("diffuseSamplerSampler",this._diffuseRenderTarget.texture?.getInternalTexture()??null)):t.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(t.setFloat("thickness",this.minimumThickness),t._bindTexture("bgDepthSampler",this._bgDepthTexture),e.isWebGPU&&t.setTextureSampler("bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(t.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),e.isWebGPU&&t.setTextureSampler("thicknessSamplerSampler",this._thicknessRenderTarget.textureBlur?.getInternalTexture()??null)):(t.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),e.isWebGPU&&t.setTextureSampler("thicknessSamplerSampler",this._thicknessRenderTarget.texture?.getInternalTexture()??null)),t.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const i=this._environmentMap??this._scene.environmentTexture;i&&(t.setTexture("reflectionSampler",i),e.isWebGPU&&t.setTextureSampler("reflectionSamplerSampler",i?.getInternalTexture()??null))}if(t.setMatrix("viewMatrix",this._scene.getViewMatrix()),t.setMatrix("invProjectionMatrix",this._invProjectionMatrix),t.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),t.setVector2("texelSize",n),t.setFloat("density",this.density),t.setFloat("refractionStrength",this.refractionStrength),t.setFloat("fresnelClamp",this.fresnelClamp),t.setFloat("specularPower",this.specularPower),t.setVector3("dirLight",this.dirLight),t.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case uP.DepthTexture:i=this._depthRenderTarget.texture;break;case uP.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case uP.ThicknessTexture:i=this._thicknessRenderTarget?.texture??null;break;case uP.ThicknessBlurredTexture:i=this._thicknessRenderTarget?.enableBlur?this._thicknessRenderTarget?.textureBlur??null:this._thicknessRenderTarget?.texture??null;break;case uP.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==uP.Normals&&(t.setTexture("debugSampler",i),e.isWebGPU&&t.setTextureSampler("debugSamplerSampler",i?.getInternalTexture()??null))}}))}_clearTargets(){this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),this._depthRenderTarget?.applyBlurPostProcesses(),this._diffuseRenderTarget?.applyBlurPostProcesses(),this._thicknessRenderTarget?.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){e||(this._depthRenderTarget?.dispose(),this._depthRenderTarget=null,this._diffuseRenderTarget?.dispose(),this._diffuseRenderTarget=null,this._thicknessRenderTarget?.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),this._renderPostProcess?.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class _P extends lP{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1}this._vertexBuffers[t]=new ys(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new ll({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){return this._vertexBuffers.offset||(this._vertexBuffers.offset=new ys(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(this._diffuseEffectWrapper?.effect.isReady()??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){super.dispose(),this._diffuseEffectWrapper?.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}var pP;bi.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(pP||(pP={}));class fP{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new al(e),this._effectWrapper=new ll({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=pP.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class mP{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new fP(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${s}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}bi.ShadersStore.fluidRenderingParticleDepthVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";bi.ShadersStore.fluidRenderingParticleDepthPixelShader="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";bi.ShadersStore.fluidRenderingParticleThicknessVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}\n";bi.ShadersStore.fluidRenderingParticleThicknessPixelShader="uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}\n";bi.ShadersStore.fluidRenderingParticleDiffuseVertexShader="attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}\n";bi.ShadersStore.fluidRenderingParticleDiffusePixelShader="uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}\n";bi.ShadersStore.fluidRenderingBilateralBlurPixelShader="uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";bi.ShadersStore.fluidRenderingStandardBlurPixelShader="uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}\nfloat sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";function gP(e){return!!e.particleSystem}function vP(e){return!!e.addBuffers}bi.ShadersStore.fluidRenderingRenderPixelShader="/* disable_uniformity_analysis */\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\nglFragColor=backColor;return;}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n",Object.defineProperty(dr.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),dr.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new bP(this)),this._fluidRenderer},dr.prototype.disableFluidRenderer=function(){this._fluidRenderer?.dispose(),this._fluidRenderer=null};class xP{constructor(e){this.name=Rs.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Rs.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(Rs.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){this.scene.fluidRenderer?._prepareRendering()}_afterCameraDraw(e){this.scene.fluidRenderer?._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{e._rebuild()}))}dispose(){this.scene.disableFluidRenderer()}}class bP{static _SceneComponentInitialization(e){let t=e._getComponent(Rs.NAME_FLUIDRENDERER);t||(t=new xP(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,bP._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,s){const r=new hP(this._scene,e);r.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),i||(i=new dP(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==t&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new _P(this._scene,e,t);n.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),s||(s=new dP(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==i&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priorityt.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let t=0;t{r.inputTexture.depthStencilTexture||r.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${r.name}`);for(const e of n){const t=e._thicknessRenderTarget?.renderTarget,i=t?.texture;if(t&&i){const e=i.width+"_"+i.height;let s=o[e];s||(s=o[e]=new mP(this._engine,i.width,i.height)),s.depthRTWrapper.shareDepth(t)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,s=this._cameras.get(t)[1],r=e.get(t);if(r)for(const e in s)r[1][e]||s[e].dispose();else for(const e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){for(let t=0;t{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class TP{get enable(){return this._enable}set enable(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))}get positionWorldTexture(){return this._mrt.textures[0]}get normalWorldTexture(){return this._mrt.textures[1]}get fluxTexture(){return this._mrt.textures[2]}get renderList(){return this._mrt.renderList}get light(){return this._light}constructor(e,t,i={width:512,height:512}){this._lightTransformMatrix=fe.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}setTextureDimensions(e){const t=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),t?.forEach((e=>{this._addMeshToMRT(e)}))}addMesh(e){e?this._addMeshToMRT(e):this._scene.meshes.forEach((e=>{this._addMeshToMRT(e)})),this._recomputeLightTransformationMatrix()}updateLightParameters(){this._recomputeLightTransformationMatrix()}get lightTransformationMatrix(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix}get countersGPU(){return this._counters}dispose(){this._disposeMultiRenderTarget()}_createMultiRenderTarget(){const e=this._light.name,t=this._scene.getEngine().getCaps(),i=t.rg11b10ufColorRenderable?13:2,s=t.rg11b10ufColorRenderable?4:5;let r,n;this._mrt=new Ex("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,s]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new Ee(0,0,0,1),this._mrt.noPrePassRenderer=!0;const o=this._scene.getEngine().supportsUniformBuffers;let a;o&&(r=this._scene.createSceneUniformBuffer(`Scene for RSM (light "${e}")`)),this._mrt.onBeforeBindObservable.add((()=>{n=this._scene.getSceneUniformBuffer(),a=this._light.shadowEnabled,this._light.shadowEnabled=!1})),this._mrt.onBeforeRenderObservable.add((e=>{r&&this._scene.setSceneUniformBuffer(r);const t=this._light.getViewMatrix(e),i=this._light.getProjectionMatrix(t||void 0,this._mrt.renderList||void 0);t&&i&&this._scene.setTransformMatrix(t,i),o&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._mrt.onAfterUnbindObservable.add((()=>{r&&this._scene.setSceneUniformBuffer(n),this._scene.updateTransformMatrix(),this._light.shadowEnabled=a,this._counters[0].value=this._mrt.renderTarget.gpuTimeInFrame?.counter.lastSecAverage??0})),this._customRenderTarget(!0)}_customRenderTarget(e){const t=this._scene.customRenderTargets.indexOf(this._mrt);e?-1===t&&this._scene.customRenderTargets.push(this._mrt):-1!==t&&this._scene.customRenderTargets.splice(t,1)}_recomputeLightTransformationMatrix(){const e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)}_addMeshToMRT(e){this._mrt.renderList?.push(e);const t=e.material;if(0===e.getTotalVertices()||!t)return;let i=this._regularMatToMatWithPlugin.get(t);if(!i&&(i=t.clone("RSMCreate_"+t.name)||void 0,i)){Object.defineProperty(i,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),i.disableLighting=!0;const e=new SP(i);e.isEnabled=!0,e.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class yP extends Oa{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class SP extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,SP.Name,300,new yP),this._lightColor=new Ce,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Vm?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===yo.LIGHTTYPEID_SPOTLIGHT;if(t){const e=this.light;this._hasProjectionTexture=!!e.projectionTexture&&e.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #endif"}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===yo.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=ge.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(.5*t.angle))}}getCustomCode(e){return"vertex"===e?null:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n `}}}SP.Name="RSMCreate",qe([st()],SP.prototype,"light",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],SP.prototype,"isEnabled",void 0),ee("BABYLON.RSMCreatePluginMaterial",SP);class CP{constructor(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}dispose(){this.rsm.dispose()}}bi.ShadersStore.bilateralBlurPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nglFragColor=vec4(sum/wsum,1.);}\n";bi.ShadersStore.bilateralBlurQualityPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nglFragColor=vec4(sum/wsum,1.);}\n";bi.ShadersStore.rsmGlobalIlluminationPixelShader="/**\n* The implementation is an application of the formula found in http:\n* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";bi.ShadersStore.rsmFullGlobalIlluminationPixelShader="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{t.pluginManager&&(t.pluginManager.getPlugin(PP.Name).isEnabled=e)})),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{e.getTotalVertices()>0&&e.isEnabled()&&e.material&&this._addGISupportToMaterial(e.material)}))}get countersGPU(){return this._counters}recreateResources(e=!1){this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()}generateSampleTexture(e){this._sampleTexture?.dispose(),this._maxSamples=e;const t=new Float32Array(4*this._maxSamples);for(let e=0;e{const e=this._engine._currentRenderTarget;let t=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),t=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let e=0;e{if(e.pluginManager){const t=e.pluginManager.getPlugin(PP.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}}))}_createPostProcesses(){if(!this._enable)return;const e=13===this._giTextureType?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=this._scene.geometryBufferRenderer?.enablePosition??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,15,EP.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,s=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let r="";i&&(r+="#define DECODE_NORMAL\n"),s||(r+="#define TRANSFORM_NORMAL\n");for(let i=0;i{e.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(TA.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",o.positionWorldTexture),e.setTexture("rsmNormalW",o.normalWorldTexture),e.setTexture("rsmFlux",o.fluxTexture),e.setMatrix("rsmLightMatrix",o.lightTransformationMatrix),n.useFullTexture?e.setFloat4("rsmInfo",o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height,n.intensity,n.edgeArtifactCorrection):(e.setTexture("rsmSamples",this._sampleTexture),e.setFloat4("rsmInfo",n.numSamples,n.radius,n.intensity,n.edgeArtifactCorrection),e.setFloat4("rsmInfo2",n.noiseFactor,n.rotateSample?1:0,o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height)),s||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),e.setMatrix("invView",this._tempMatrix))}))}for(const e of this._ppGlobalIllumination)e.inputTexture||e.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const s=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new pl("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const r=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(r),this._blurXPostprocess=new qa(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurXPostprocess.onApplyObservable.add((e=>{e._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(TA.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new qa("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(TA.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",0,1/this._giTextureDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurYPostprocess.resize(s.width,s.height),r.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)r.push(this._blurRTT.renderTarget);else{const n=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(n),this._upsamplingXPostprocess=new qa(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(TA.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(s.width,s.height),r.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new qa("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(TA.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(TA.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",0,1/this._outputDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),n.push(this._upsamplingYPostprocess.inputTexture)),n.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}this._debugLayer.texture?.dispose(),this._debugLayer.texture=new No(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){if(e.pluginManager?.getPlugin(PP.Name))return;const t=new PP(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}EP.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class AP extends Oa{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class PP extends gc{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,PP.Name,310,new AP),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Vm}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e){const t={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n "),"vertex"===e?null:t}}PP.Name="GIRSMRender",qe([st()],PP.prototype,"textureGIContrib",void 0),qe([st()],PP.prototype,"outputTextureWidth",void 0),qe([st()],PP.prototype,"outputTextureHeight",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],PP.prototype,"isEnabled",void 0),ee("BABYLON.GIRSMRenderPluginMaterial",PP);bi.ShadersStore.spriteMapPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);}\nvoid main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}}\nmat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}\ncolor.xyz*=colorMul;gl_FragColor=color;}";bi.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \ngl_Position=worldViewProjection*p;}";class RP{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}constructor(e,t,i,s,r){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=s,s.stageSize=s.stageSize||new ue(1,1),s.outputSize=s.outputSize||s.stageSize,s.outputPosition=s.outputPosition||de.Zero(),s.outputRotation=s.outputRotation||de.Zero(),s.layerCount=s.layerCount||1,s.maxAnimationFrames=s.maxAnimationFrames||0,s.baseTile=s.baseTile||0,s.flipU=s.flipU||!1,s.colorMultiply=s.colorMultiply||new de(1,1,1),this._scene=r,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let e=0;e{this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture?this._material.setVector2("spriteMapSize",new ue(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1)):l<100&&setTimeout((()=>{l++,h()}),100)};h(),this._material.setVector3("colorMul",s.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=ta(e+":output",{size:1,updatable:!0},r),this._output.scaling.x=s.outputSize.x,this._output.scaling.y=s.outputSize.y,this.position=s.outputPosition,this.rotation=s.outputRotation,this._scene.onBeforeRenderObservable.add((()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)})),this._output.material=this._material}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||ue.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,(t=>t===e));if(!t||!t.hit||!t.getTextureCoordinates)return new ue(-1,-1);return t.getTextureCoordinates()||new ue(-1,-1)}_createFrameBuffer(){const e=[];for(let t=0;t0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const e=t.response.split("\n\r");for(let t=0;t{e.dispose()})),this._frameMap.dispose()}}class IP extends Av{constructor(e,t,i,s,r=null,n=.01,o=Vo.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,s,n,o,!0,r),this.name=e}}var MP;!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(MP||(MP={}));class OP{constructor(e){this.name=e,this._isCompleted=!1,this._taskState=MP.INIT}get isCompleted(){return this._isCompleted}get taskState(){return this._taskState}get errorObject(){return this._errorObject}_setErrorObject(e,t){this._errorObject||(this._errorObject={message:e,exception:t})}run(e,t,i){this._taskState=MP.RUNNING,this.runTask(e,(()=>{this._onDoneCallback(t,i)}),((e,t)=>{this._onErrorCallback(i,e,t)}))}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=MP.INIT}_onErrorCallback(e,t,i){this._taskState=MP.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=MP.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}}}class DP{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class wP extends OP{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){Pa.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(e=>{this.loadedContainer=e,this.loadedMeshes=e.meshes,this.loadedTransformNodes=e.transformNodes,this.loadedParticleSystems=e.particleSystems,this.loadedSkeletons=e.skeletons,this.loadedAnimationGroups=e.animationGroups,t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class NP extends OP{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){Pa.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,((e,i,s,r,n)=>{this.loadedMeshes=e,this.loadedTransformNodes=n,this.loadedParticleSystems=i,this.loadedSkeletons=s,this.loadedAnimationGroups=r,t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class FP extends OP{constructor(e,t,i,s,r){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=s,this.extension=r}runTask(e,t,i){const s=e.animatables.length,r=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],Pa.ImportAnimations(this.rootUrl,this.filename,e,!1,va.NoSync,this.targetConverter,(()=>{this.loadedAnimatables=e.animatables.slice(s),this.loadedAnimationGroups=e.animationGroups.slice(r),t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class BP extends OP{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.text=e,t()}),void 0,!1,!1,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class LP extends OP{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.data=e,t()}),void 0,!0,!0,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class kP extends OP{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const s=new Image;hs.SetCorsBehavior(this.url,s),s.onload=()=>{this.image=s,t()},s.onerror=e=>{i("Error loading image",e)},s.src=this.url}}class VP extends OP{constructor(e,t,i,s=!0,r=Vo.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=s,this.samplingMode=r}runTask(e,t,i){this.texture=new Vo(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(()=>{t()}),((e,t)=>{i(e,t)}))}}class UP extends OP{constructor(e,t,i,s,r,n){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=s,this.files=r,this.prefiltered=n}runTask(e,t,i){this.texture=new mm(this.url,e,this.extensions,this.noMipmap,this.files,(()=>{t()}),((e,t)=>{i(e,t)}),void 0,this.prefiltered)}}class GP extends OP{constructor(e,t,i,s=!1,r=!0,n=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.generateHarmonics=r,this.gammaSpace=n,this.reserved=o}runTask(e,t,i){this.texture=new uv(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(()=>{t()}),((e,t)=>{i(e,t)}))}}class zP extends OP{constructor(e,t,i,s=!1,r=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.gammaSpace=r}runTask(e,t,i){this.texture=new Xv(this.url,e,this.size,this.noMipmap,this.gammaSpace,(()=>{t()}),((e,t)=>{i(e,t)}))}}class WP{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new X,this.onTaskErrorObservable=new X,this.onTasksDoneObservable=new X,this.onProgressObservable=new X,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||se.LastCreatedScene}addContainerTask(e,t,i,s,r){const n=new wP(e,t,i,s,r);return this._tasks.push(n),n}addMeshTask(e,t,i,s,r){const n=new NP(e,t,i,s,r);return this._tasks.push(n),n}addTextFileTask(e,t){const i=new BP(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new LP(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new kP(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,s,r=Vo.TRILINEAR_SAMPLINGMODE){const n=new VP(e,t,i,s,r);return this._tasks.push(n),n}addCubeTextureTask(e,t,i,s,r,n){const o=new UP(e,t,i,s,r,n);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,s=!1,r=!0,n=!1,o=!1){const a=new GP(e,t,i,s,r,n,o);return this._tasks.push(a),a}addEquiRectangularCubeTextureAssetTask(e,t,i,s=!1,r=!0){const n=new zP(e,t,i,s,r);return this._tasks.push(n),n}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new DP(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){we.Error("Error running progress callbacks."),we.Log(e)}if(0===this._waitingTasksCount){try{const e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(const t of e)if(t.taskState===MP.DONE){const e=this._tasks.indexOf(t);e>-1&&this._tasks.splice(e,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){we.Error("Error running tasks-done callbacks."),we.Log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=(t,i)=>{e._setErrorObject(t,i),this.onTaskError?this.onTaskError(e):e.onError||we.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,(()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(e){t("Error executing task success callbacks",e)}}),t)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{this._isLoading?e():(this.onTasksDoneObservable.addOnce((i=>{i&&i.length?t(i):e()})),this.load())}))}}class HP{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class XP{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new de(1,1,1),this._newPosition=de.Zero(),this._centerPosition=de.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let e=0;e!0,this.displayLoadingUI=!0,this.loadAsync=(e,t)=>this.useAppend?Pa.AppendAsync("file:",e,this._currentScene,t):Pa.LoadAsync("file:",e,this._engine,t),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=s,this._additionalRenderLoopLogicCallback=r,this._textureLoadingCallback=n,this._startingProcessingFilesCallback=o,this._onReloadCallback=a,this._errorCallback=l}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=e=>{this._drag(e)},this._dragOverHandler=e=>{this._drag(e)},this._dropHandler=e=>{this._drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,s){const r=e.createReader(),n=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");r.readEntries((e=>{i.count+=e.length;for(const r of e)r.isFile?r.file((e=>{e.correctName=n+e.name,t.push(e),0==--i.count&&s()})):r.isDirectory&&this._traverseFolder(r,t,i,s);0==--i.count&&s()}))}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=e))&&(Pa.IsPluginForExtensionAvailable("."+s)&&(this._sceneFileToLoad=e[t]),YP.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=[],i=[],s=e.dataTransfer?e.dataTransfer.items:null;for(let e=0;e{this._processFiles(t),0===e.count&&this._processReload()}))}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){this._sceneFileToLoad?(this.useAppend||this._currentScene&&(we.errorsCount>0&&we.ClearLogCache(),this._engine.stopRenderLoop()),Pa.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then((e=>{this.useAppend?this.displayLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady((()=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop((()=>{this._renderFunction()}))}))),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)})).catch((e=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)}))):we.Error("Please provide a valid .babylon file.")}}class QP{dispose(){if(this._observers&&this._observables)for(let e=0;e{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(n=i.scope?n.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):n.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await n,e};class jP{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class KP extends jP{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let t=0;tthis.maximumSize&&(s.scale(this.step),i=!1)}return i}}class $P extends jP{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class qP extends jP{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class ZP extends jP{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class JP extends jP{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class eR extends jP{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return!this.onApply||this.onApply(e,t)}}class tR extends jP{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class iR extends jP{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class sR extends jP{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof bo))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return sR._UpdateSelectionTree}static set UpdateSelectionTree(e){sR._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const s=e.meshes.slice(0);let r=s.length;for(let e=0;e{this._sceneDisposeObserver=null,this.dispose()}))}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady((()=>{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)})))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);let i=!0,s=!0;for(let r=0;r{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)}))}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,s){const r=new nR(e,t||rR.ModerateDegradationAllowed(),!1);return i&&r.onSuccessObservable.add((()=>{i()})),s&&r.onFailureObservable.add((()=>{s()})),r.start(),r}}let oR=[];const aR=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),oR[e.id]=!0)},lR=(e,t)=>{const i={},s=e._geometry;return s&&(e.getScene().getGeometryById(s.id)||aR(s,t.geometries)),e.serialize&&e.serialize(i),i};class hR{static ClearCache(){oR=[]}static Serialize(e){return hR._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Vo.ForceSerializeBuffers&&we.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),hR.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(i.fogMode=e.fogMode,i.fogColor=e.fogColor.asArray(),i.fogStart=e.fogStart,i.fogEnd=e.fogEnd,i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let s,r,n;for(i.lights=[],s=0;s0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],s=0;st))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const s=e[i];s instanceof Promise?t.push(s.then((t=>e[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}}static SerializeMesh(e,t=!1,i=!1){const s={meshes:[],transformNodes:[],cameras:[],lights:[]};if(hR.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach((e=>{((e,t)=>{if(e._isMesh){const i=e;if(1===i.delayLoadState||0===i.delayLoadState){const e=e=>{t.materials=t.materials||[],i.material&&!t.materials.some((e=>e.id===i.material.id))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof _o){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((e=>e.id===i.material.id))){t.multiMaterials.push(i.material.serialize());for(const t of i.material.subMaterials)t&&e(t)}}else e(i.material);else i.material||e(i.getScene().defaultMaterial);const s=i._geometry;s&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),aR(s,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(lR(i,t))}}else if("TransformNode"===e.getClassName()){const i=e;t.transformNodes.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){const i=e;t.cameras.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Light")){const i=e;t.lights.push(i.serialize())}})(e,s)})),s}}class cR{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!cR.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...cR._DefaultOptions,...t};const s=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)s.addTrack(e);this._mediaRecorder=new MediaRecorder(s,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&hs.Download(e,this._fileName)}}cR._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let uR=null;function dR(e,t,i,s,r="image/png",n=!1,o){const{height:a,width:l}=gR(e,t,i);if(!a||!l)return void we.Error("Invalid 'size' parameter !");uR||(uR=document.createElement("canvas")),uR.width=l,uR.height=a;const h=uR.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const _=Math.max(0,l-u)/2,p=Math.max(0,a-d)/2;t.getScene().activeCamera!==t?fR(e,t,i,(e=>{if(n){const t=new Blob([e]);hs.DownloadBlob(t),s&&s("")}else s&&s(e)}),r,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,_,p,u,d),uR&&(n?(hs.EncodeScreenshotCanvasData(uR,void 0,r,void 0,o),s&&s("")):hs.EncodeScreenshotCanvasData(uR,s,r,void 0,o))}))}function _R(e,t,i,s="image/png",r){return new Promise(((n,o)=>{dR(e,t,i,(e=>{void 0!==e?n(e):o(new Error("Data is undefined"))}),s,void 0,r)}))}function pR(e,t,i,s,r="image/png",n){return new Promise((o=>{dR(e,t,{width:i,height:s},(()=>{o()}),r,!0,n)}))}function fR(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u,d){const{height:_,width:p,finalWidth:f,finalHeight:m}=gR(e,t,i),g={width:p,height:_};if(!_||!p)return void we.Error("Invalid 'size' parameter !");const v={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(p,_);const x=t.getScene(),b=new pl("screenShot",g,x,!1,!1,0,!1,Vo.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);b.renderList=x.meshes.slice(),b.samples=n,b.renderSprites=l,b.activeCamera=t,b.forceLayerMaskCheck=c,d?.(b);const T=()=>{b.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((()=>{f===p&&m===_?b.readPixels(void 0,void 0,void 0,!1).then((e=>{_l.DumpData(p,_,e,s,r,a,!0,void 0,u),b.dispose()})):c_("pass",b.getInternalTexture(),x,void 0,void 0,void 0,f,m).then((t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then((e=>{_l.DumpData(f,m,e,s,r,a,!0,void 0,u),t.dispose()}))}))})),b.render(!0),x.incrementRenderId(),x.resetCachedMaterial(),e.setSize(v.width,v.height),t.getProjectionMatrix(!0),x.render()):setTimeout(T,16)},y=()=>{x.incrementRenderId(),x.resetCachedMaterial(),T()};if(o){const e=new mA("antialiasing",1,x.activeCamera);b.addPostProcess(e),e.getEffect().isReady()?y():e.getEffect().onCompiled=()=>{y()}}else y()}function mR(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){return new Promise(((u,d)=>{fR(e,t,i,(e=>{void 0!==e?u(e):d(new Error("Data is undefined"))}),s,r,n,o,a,l,h,c)}))}function gR(e,t,i){let s=0,r=0,n=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(s=i.height*a,r=i.width*a):i.width&&!i.height?(r=i.width*a,s=Math.round(r/e.getAspectRatio(t))):i.height&&!i.width?(s=i.height*a,r=Math.round(s*e.getAspectRatio(t))):(r=Math.round(e.getRenderWidth()*a),s=Math.round(r/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?(n=i.finalWidth,o=Math.round(n/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,n=Math.round(o*e.getAspectRatio(t))):(n=r,o=s)}else isNaN(i)||(s=i,r=i,n=i,o=i);return r&&(r=Math.floor(r)),s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),o&&(o=Math.floor(o)),{height:0|s,width:0|r,finalWidth:0|n,finalHeight:0|o}}const vR={CreateScreenshot:dR,CreateScreenshotAsync:_R,CreateScreenshotWithResizeAsync:pR,CreateScreenshotUsingRenderTarget:fR,CreateScreenshotUsingRenderTargetAsync:mR};var xR,bR;hs.CreateScreenshot=dR,hs.CreateScreenshotAsync=_R,hs.CreateScreenshotUsingRenderTarget=fR,hs.CreateScreenshotUsingRenderTargetAsync=mR,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(xR||(xR={}));class TR{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return $t(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class yR{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}yR._Storage=yR._GetStorage();class SR{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,yt.AllowLoadingUniqueId=!0,this._savedJSON=hR.Serialize(e),yt.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=Vo.ForceSerializeBuffers;Vo.ForceSerializeBuffers=!1,yt.AllowLoadingUniqueId=!0;const t=hR.Serialize(this._trackedScene);yt.AllowLoadingUniqueId=!1;const i={};for(const e in t)this._compareCollections(e,this._savedJSON[e],t[e],i);return Vo.ForceSerializeBuffers=e,i}_compareArray(e,t,i,s){if(0===t.length&&0===i.length)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(0===t.length)return!0;for(let r=0;re.uniqueId===a));if(l.length){const t=l[0],i={};this._compareObjects(o,t,i)||(s[e]||(s[e]=[]),i.__state={id:t.id||t.name},s[e].push(i))}else{const t={__state:{deleteId:o.id||o.name}};s[e]||(s[e]=[]),s[e].push(t)}}for(let t=0;te.getShadowGenerators()));for(const e of i)if(e){const i=e.values();for(let e=i.next();!0!==e.done;e=i.next()){const i=e.value;if(i&&i.id===t)return i}}return null}static ApplyDelta(e,t){"string"==typeof e&&(e=JSON.parse(e));const i=t;for(const s in e){const r=e[s],n=i[s];if(Array.isArray(n)||"shadowGenerators"===s)switch(s){case"cameras":this._ApplyDeltaForEntity(r,t,t.getCameraById.bind(t),(e=>Kr.Parse(e,t)));break;case"lights":this._ApplyDeltaForEntity(r,t,t.getLightById.bind(t),(e=>yo.Parse(e,t)));break;case"shadowGenerators":this._ApplyDeltaForEntity(r,t,(e=>this.GetShadowGeneratorById(t,e)),(e=>Kg.Parse(e,t)));break;case"meshes":this._ApplyDeltaForEntity(r,t,t.getMeshById.bind(t),(e=>bo.Parse(e,t,"")));break;case"skeletons":this._ApplyDeltaForEntity(r,t,t.getSkeletonById.bind(t),(e=>Ho.Parse(e,t)));break;case"materials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),(e=>uo.Parse(e,t,"")));break;case"multiMaterials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),(e=>_o.Parse(e,t,"")));break;case"transformNodes":this._ApplyDeltaForEntity(r,t,t.getTransformNodeById.bind(t),(e=>xn.Parse(e,t,"")));break;case"particleSystems":this._ApplyDeltaForEntity(r,t,t.getParticleSystemById.bind(t),(e=>HC.Parse(e,t,"")));break;case"morphTargetManagers":this._ApplyDeltaForEntity(r,t,t.getMorphTargetById.bind(t),(e=>pv.Parse(e,t)));break;case"postProcesses":this._ApplyDeltaForEntity(r,t,t.getPostProcessByName.bind(t),(e=>qa.Parse(e,t,"")))}else isNaN(n)?n.fromArray&&n.fromArray(r):i[s]=r}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const s=e[i],r=t[i];void 0!==r&&(!isNaN(r)||Array.isArray(r)?t[i]=s:r.fromArray?r.fromArray(s):"object"==typeof r&&null!==r&&this._ApplyPropertiesToEntity(s,r))}}static _ApplyDeltaForEntity(e,t,i,s){for(const r of e)if(r.__state&&void 0!==r.__state.id){const e=i(r.__state.id);e&&(this._ApplyPropertiesToEntity(r,e),yt.ParseProperties(r,e,t,null))}else if(r.__state&&void 0!==r.__state.deleteId){const e=i(r.__state.deleteId);e?.dispose()}else s(r)}}!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),s=new t(i.characters);return s._insertionCosts=i.insertionCosts,s._deletionCosts=i.deletionCosts,s._substitutionCosts=i.substitutionCosts,s}constructor(e,t=null,i=null,s=null){let r;t=t??(()=>1),i=i??(()=>1),s=s??((e,t)=>e===t?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const s=e._alphabet;if(s!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const r=e._characters,n=t._characters,o=r.length,a=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(bR||(bR={}));class CR{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new CR(t._segmentLength);return i._points=t._points.map((e=>new de(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/de.Distance(this._points[t-1],e);for(let s=i();s<=1;s=i()){const i=this._points[t-1].scale(1-s);e.scaleAndAddToRef(s,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new CR(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new de;for(let s=2;s.98||(de.CrossToRef(CR._ForwardDir,CR._InverseFromVec,CR._UpDir),CR._UpDir.normalize(),fe.LookAtLHToRef(e,t,CR._UpDir,CR._LookMatrix),i.subtractToRef(t,CR._FromToVec),CR._FromToVec.normalize(),de.TransformNormalToRef(CR._FromToVec,CR._LookMatrix,s),0))}static _TokenizeSegment(e,t){CR._BestMatch=0,CR._Score=de.Dot(e,t[0]),CR._BestScore=CR._Score;for(let i=1;iCR._BestScore&&(CR._BestMatch=i,CR._BestScore=CR._Score);return CR._BestMatch}}CR._ForwardDir=new de,CR._InverseFromVec=new de,CR._UpDir=new de,CR._FromToVec=new de,CR._LookMatrix=new fe;class ER{static Generate(e=64,t=256,i=.1,s=.001,r=[]){const n=new ER(e);for(let t=0;t{n.chars[e].subtractToRef(t,h),a=h.lengthSquared(),a>1e-6&&h.scaleAndAddToRef(1/(h.lengthSquared()*a),l)})),l.scaleInPlace(o),n.chars[e].addInPlace(l),n.chars[e].normalize()}var c;return n}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new ER(t.length);for(let e=0;ee.serialize())))}static Deserialize(e,t){const i=new AR;return i._sequences=JSON.parse(e).map((e=>bR.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return AR.CreateFromTokenizationPyramid(AR._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new AR;return i._sequences=e.map((e=>new bR.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=AR._FINEST_DESCRIPTOR_RESOLUTION){const s=[];for(let r=i;r>4;r=Math.floor(r/2))s.push(e.resampleAtTargetResolution(r).tokenize(t.chars));return s}distance(e){let t,i=0;for(let s=0;se.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),s=new PR;return s._descriptors=i.descriptors.map((e=>AR.Deserialize(e,t))),s._centroidIdx=i.centroidIdx,s._averageDistance=i.averageDistance,s}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,PR._MIN_AVERAGE_DISTANCE))}}PR._MIN_AVERAGE_DISTANCE=1;class RR{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach(((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())})),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new RR;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=ER.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=bR.Alphabet.Deserialize(t.levenshteinAlphabet);for(let e=0;e0===e?0:1),(e=>0===e?0:1),((t,i)=>Math.min(1-de.Dot(e.chars[t],e.chars[i]),1))),s=new RR;return s._vector3Alphabet=e,s._levenshteinAlphabet=i,s}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new PR),this._nameToDescribedTrajectory.get(t).add(AR.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=AR.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach(((e,s)=>{e.getMatchCost(t){const t=e.data;if(t.startsWith(IR._SERVER_PREFIX)){const e=t.substr(IR._SERVER_PREFIX.length);return we.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}we.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{we.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&hR.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}IR._SERVER_PREFIX="$$";class MR{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new X,MR.IsAvailable&&(this._observer=new PressureObserver((e=>{this._currentState=e,this.onPressureChanged.notifyObservers(e)}),e))}static get IsAvailable(){return"undefined"!=typeof PressureObserver&&PressureObserver.supportedSources.includes("cpu")}observe(e){try{this._observer?.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){try{this._observer?.unobserve(e)}catch{}}dispose(){this._observer?.disconnect(),this._observer=null,this.onPressureChanged.clear()}}class OR{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const DR=1800,wR="timestamp",NR="numPoints",FR=/\r/g;class BR{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=zt.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let s=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);s=e+this.datasets.data.at(e+BR.NumberOfPointsOffset)+BR.SliceDataOffset}if(this.datasets.startingIndices.push(s),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new W(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(this._strategies.get(e)?.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,s=0;const r=t.onAfterRenderObservable.add((()=>{s=i,i=0})),n=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>s,dispose:()=>{t.onAfterRenderObservable.remove(r),this._customEventObservable.remove(n)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:s}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:s}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){const e=[zt.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);s&&(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new OR(DR),this.datasets.ids.length=0,this.datasets.startingIndices=new OR(DR),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(FR,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),s=BR.NumberOfPointsOffset;if(i.length<2)return!1;const r={ids:[],data:new OR(DR),startingIndices:new OR(DR)},[n,...o]=i;if(n.length<2||n[0]!==wR||n[s]!==NR)return!1;const a=new Map;for(let e=BR.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${wR},${NR}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const LR=()=>{};class kR{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:LR}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const s=new MR;return s.observe("cpu"),s.onPressureChanged.add((e=>{for(const s of e)if(t&&s.factors.includes(t)||!t&&0===(s.factors?.length??0))switch(s.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1}})),{id:e,getData:()=>i,dispose:()=>s.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:LR})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:LR})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:LR})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:LR})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:LR})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:LR})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add((()=>{e.getEngine()._drawCalls.fetchNewFrame()})),s=e.onAfterRenderObservable.add((()=>{t=e.getEngine()._drawCalls.current}));return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(s)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:LR})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:LR})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:LR})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:LR})}static AbsoluteFpsStrategy(){return e=>{const t=new kg(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:LR}}}static MeshesSelectionStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeActiveMeshesEvaluationObservable.add((()=>{t=zt.Now})),r=e.onAfterActiveMeshesEvaluationObservable.add((()=>{i=zt.Now-t}));return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(s),e.onAfterActiveMeshesEvaluationObservable.remove(r)}}}}static RenderTargetsStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeRenderTargetsRenderObservable.add((()=>{t=zt.Now})),r=e.onAfterRenderTargetsRenderObservable.add((()=>{i=zt.Now-t}));return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(s),e.onAfterRenderTargetsRenderObservable.remove(r)}}}}static ParticlesStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeParticlesRenderingObservable.add((()=>{t=zt.Now})),r=e.onAfterParticlesRenderingObservable.add((()=>{i=zt.Now-t}));return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(s),e.onAfterParticlesRenderingObservable.remove(r)}}}}static SpritesStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeSpritesRenderingObservable?.add((()=>{t=zt.Now})),r=e.onAfterSpritesRenderingObservable?.add((()=>{i=zt.Now-t}));return{id:"Sprites",getData:()=>i,dispose:()=>{e.onBeforeSpritesRenderingObservable?.remove(s),e.onAfterSpritesRenderingObservable?.remove(r)}}}}static AnimationsStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{t=zt.Now})),r=e.onAfterAnimationsObservable.add((()=>{i=zt.Now-t}));return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterAnimationsObservable.remove(r)}}}}static PhysicsStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforePhysicsObservable?.add((()=>{t=zt.Now})),r=e.onAfterPhysicsObservable?.add((()=>{i=zt.Now-t}));return{id:"Physics",getData:()=>i,dispose:()=>{e.onBeforePhysicsObservable?.remove(s),e.onAfterPhysicsObservable?.remove(r)}}}}static RenderStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeDrawPhaseObservable.add((()=>{t=zt.Now})),r=e.onAfterDrawPhaseObservable.add((()=>{i=zt.Now-t}));return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(s),e.onAfterDrawPhaseObservable.remove(r)}}}}static FrameTotalStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{t=zt.Now})),r=e.onAfterRenderObservable.add((()=>{i=zt.Now-t}));return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static InterFrameStrategy(){return e=>{let t=zt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{i=zt.Now-t})),r=e.onAfterRenderObservable.add((()=>{t=zt.Now}));return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new Lg(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(1e-6*t.gpuFrameTimeCounter.current,0),dispose:()=>{t.dispose()}}}}}dr.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new BR(this)),this._perfCollector},X.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,s=new Array,r=e.add((()=>{const e=t.length;for(let r=0;r{t.push(e),i.push(r),s.push(n)},dispose:()=>{e.remove(r)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return Xr(e,this._coroutineScheduler)},X.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};async function VR(e,t){const i=t.probe??new Tv("tempProbe",t.size,e),s=!!t.probe;s||(t.position?i.position=t.position.clone():e.activeCamera&&(i.position=e.activeCamera.position.clone()));const r=t.meshesFilter?e.meshes.filter(t.meshesFilter):e.meshes;i.renderList?.push(...r),i.refreshRate=pl.REFRESHRATE_RENDER_ONCE,i.cubeTexture.render();const n=new Rx("tempProceduralTexture","equirectangularPanorama",{width:2*t.size,height:t.size},e);return n.setTexture("cubeMap",i.cubeTexture),new Promise(((e,r)=>{n.onGeneratedObservable.addOnce((()=>{const o=n.readPixels();if(!o)return r(new Error("No Pixel Data found on procedural texture")),n.dispose(),void(s||i.dispose());o.then((r=>{n.dispose(),s||i.dispose(),t.filename?(_l.DumpData(2*t.size,t.size,r,void 0,"image/png",t.filename),e(null)):e(r)}))}))}))}bi.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";class UR extends ua{constructor(e,t={}){super(e),this.options=t,this._direction=new de(0,0,-1),this._mat=new fe,this._onSelectEnabled=!1,this._origin=new de(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new X,this._onHitTestResults=e=>{const t=e.map((e=>{const t=fe.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&UR.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",hs.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then((e=>{const t=s||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;fe.FromArrayToRef(t.transform.matrix,0,this._mat),de.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),de.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});UR.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}UR.Name=ha.HIT_TEST,UR.Version=1,ca.AddWebXRFeature(UR.Name,((e,t)=>()=>new UR(e,t)),UR.Version,!1);let GR=0;class zR extends ua{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new X,this.onAnchorRemovedObservable=new X,this.onAnchorUpdatedObservable=new X,this._tmpVector=new de,this._tmpQuaternion=new pe,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new de,i=new pe){this._populateTmpTransformation(t,i);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(s);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:s,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new pe,i=!1){this._populateTmpTransformation(e,t);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let s=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),s++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),s=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,s,e),s.attachedNode&&(s.attachedNode.rotationQuaternion=s.attachedNode.rotationQuaternion||new pe,s.transformationMatrix.decompose(s.attachedNode.scaling,s.attachedNode.rotationQuaternion,s.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(s)}catch(e){hs.Warn("Anchor could not be updated")}}else{const i={id:GR++,xrAnchor:t,remove:()=>t.delete()},s=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(s),this.onAnchorAddedObservable.notifyObservers(s);const r=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];r&&(r.resolve(s),r.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new zR(e,t)),zR.Version);let WR=0;class HR extends ua{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new X,this.onPlaneRemovedObservable=new X,this.onPlaneUpdatedObservable=new X,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||e.worldInformation?.detectedPlanes;if(t){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),s=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,s,e),this.onPlaneUpdatedObservable.notifyObservers(s)}}else{const i={id:WR++,xrPlane:t,polygonDefinition:[]},s=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(s),this.onPlaneAddedObservable.notifyObservers(s)}})),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new de(e.x,e.y,e.z*t)}));const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const e=t.transformationMatrix||new fe;fe.FromArrayToRef(s.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new HR(e,t)),HR.Version);class XR extends ua{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new X}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}XR.Name=ha.BACKGROUND_REMOVER,XR.Version=1,ca.AddWebXRFeature(XR.Name,((e,t)=>()=>new XR(e,t)),XR.Version,!0);class YR{}class QR extends ua{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||ga.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=Eu("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new pe;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new ga(s,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||we.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new ga(t.rootMesh,ga.MeshImpostor,{mass:0,...this._options.physicsProperties}),s=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:s.position.clone(),oldRotation:s.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new pe,this._tmpVector=new de,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)}))}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:ga.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Eu("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new pe,this._headsetMesh.isVisible=!1,this._headsetImpostor=new ga(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e],i=t.xrController.grip||t.xrController.pointer,s=t.oldPos||t.impostorMesh.position;if(t.xrController._lastXRPose?.linearVelocity){const e=t.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setLinearVelocity(this._tmpVector)}else i.position.subtractToRef(s,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),t.impostor.setLinearVelocity(this._tmpVector);s.copyFrom(i.position),this._debugMode&&we.Log([this._tmpVector,"linear"]);const r=t.oldRotation||t.impostorMesh.rotationQuaternion;if(t.xrController._lastXRPose?.angularVelocity){const e=t.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setAngularVelocity(this._tmpVector)}else if(!r.equalsWithEpsilon(i.rotationQuaternion)){r.conjugateInPlace().multiplyToRef(i.rotationQuaternion,this._tmpQuaternion);const e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}t.impostor.setAngularVelocity(this._tmpVector)}r.copyFrom(i.rotationQuaternion),this._debugMode&&we.Log([this._tmpVector,this._tmpQuaternion,"angular"])}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}QR.Name=ha.PHYSICS_CONTROLLERS,QR.Version=1,ca.AddWebXRFeature(QR.Name,((e,t)=>()=>new QR(e,t)),QR.Version,!0);class jR extends ua{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new fe,this._tmpPos=new de,this._tmpQuat=new pe,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):hs.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new X,this.paused=!1,this.xrNativeFeatureName="hit-test",hs.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then((e=>{this._transientXrHitTestSource=e}))}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const s=e.getPose(this._xrSessionManager.referenceSpace);if(!s)return;const r=s.transform.position,n=s.transform.orientation;this._tmpPos.set(r.x,r.y,r.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(n.x,n.y,n.z,n.w),fe.FromFloat32ArrayToRefScaled(s.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const o={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(o)})),this.onHitTestResultObservable.notifyObservers(i)}}jR.Name=ha.HIT_TEST,jR.Version=2,ca.AddWebXRFeature(jR.Name,((e,t)=>()=>new jR(e,t)),jR.Version,!1);class KR extends ua{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new X,this.onFeaturePointsUpdatedObservable=new X,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=[],s=[];for(let r=0;r0&&this.onFeaturePointsAddedObservable.notifyObservers(s),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}KR.Name=ha.FEATURE_POINTS,KR.Version=1,ca.AddWebXRFeature(KR.Name,(e=>()=>new KR(e)),KR.Version);let $R=0;class qR extends ua{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new X,this.onMeshRemovedObservable=new X,this.onMeshUpdatedObservable=new X,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((e=>{this.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){try{if(!this.attached||!e)return;const t=e.detectedMeshes||e.worldInformation?.detectedMeshes;if(t){const i=new Set;this._detectedMeshes.forEach(((e,s)=>{t.has(s)||i.add(s)})),i.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),t.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:$R++,xrMesh:t},s=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,s),this.onMeshAddedObservable.notifyObservers(s)}}))}}catch(e){we.Log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let e=0;e()=>new qR(e,t)),qR.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(ZR||(ZR={}));class JR extends ua{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new X,this.onTrackableImageFoundObservable=new X,this.onTrackedImageUpdatedObservable=new X,this._trackableScoreStatus=ZR.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach((e=>{e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return hs.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===ZR.Waiting)return;if(this._trackableScoreStatus===ZR.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const s=i.index,r=this._trackedImages[s];if(!r)continue;r.xrTrackingResult=i,r.realWorldWidth!==i.measuredWidthInMeters&&(r.realWorldWidth=i.measuredWidthInMeters,t=!0);const n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){const e=r.transformationMatrix;fe.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const o="emulated"===i.trackingState;r.emulated!==o&&(r.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(r)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==ZR.NotReceived)return;this._trackableScoreStatus=ZR.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?ZR.Received:ZR.NotReceived}else this._trackableScoreStatus=ZR.NotReceived}}JR.Name=ha.IMAGE_TRACKING,JR.Version=1,ca.AddWebXRFeature(JR.Name,((e,t)=>()=>new JR(e,t)),JR.Version,!1);class eI extends ua{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",hs.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return hs.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return hs.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}eI.Name=ha.DOM_OVERLAY,eI.Version=1,ca.AddWebXRFeature(eI.Name,((e,t)=>()=>new eI(e,t)),eI.Version,!1);class tI extends ua{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new pe,this._tmpRotationMatrix=fe.Identity(),this._tmpTranslationDirection=new de,this._tmpMovementTranslation=new de,this._tempCacheQuaternion=new pe,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let s=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){s=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;s=t}if("function"==typeof i.componentSelectionPredicate&&(s=i.componentSelectionPredicate(e)),s&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===s)continue;const r={registrationConfiguration:i,component:s};t.registeredComponents.push(r),"axisChangedHandler"in i&&(r.onAxisChangedObserver=s.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(r.onButtonChangedObserver=s.onButtonStateChangedObservable.add((()=>{s.changes.pressed&&i.buttonChangedhandler(s.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=tI.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):hs.Error('WebXRControllerMovement feature requires "xrInput" option.')}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,pe.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(pe.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(fe.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),de.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}tI.Name=ha.MOVEMENT,tI.REGISTRATIONS={default:[{allowedComponentTypes:[cg.THUMBSTICK_TYPE,cg.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[cg.THUMBSTICK_TYPE,cg.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},tI.Version=1,ca.AddWebXRFeature(tI.Name,((e,t)=>()=>new tI(e,t)),tI.Version,!0);class iI extends ua{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=de.Up().negateInPlace(),this._lightColor=Ce.White(),this._intensity=1,this._sphericalHarmonics=new a_,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new X,this._updateReflectionCubeMap=()=>{if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)})))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new lm("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new de(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=nr.FALLOFF_GLTF),this._hdrFilter=new cv(this._xrSessionManager.scene.getEngine()),hs.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new No(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))})),!0}detach(){const e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new iI(e,t)),iI.Version,!1);class sI extends ua{constructor(e){super(e),this.onEyeTrackingStartedObservable=new X,this.onEyeTrackingEndedObservable=new X,this.onEyeTrackingFrameUpdateObservable=new X,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new Zo(de.Zero(),de.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const e=t.transform.orientation;ge.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?de.RightHandedForwardReadOnly.rotateByQuaternionToRef(ge.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,ge.Quaternion[0].z*=-1,ge.Quaternion[0].w*=-1,de.LeftHandedForwardReadOnly.rotateByQuaternionToRef(ge.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}sI.Name=ha.EYE_TRACKING,sI.Version=1,ca.AddWebXRFeature(sI.Name,(e=>()=>new sI(e)),sI.Version,!1);class rI{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class nI{constructor(){this._samples=new rI(20),this._entropy=0,this.onFirstStepDetected=new X}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=ue.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(a=t,o=e);if(on*this._squaredProjectionDistanceThreshold)return;const p=ge.Vector3[0];p.set(i,s,0);const f=ge.Vector3[1];f.set(h.x,h.y,0);const m=de.Cross(p,f).z>0,g=r.clone(),v=r.clone();l.subtractToRef(r,h),m?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,g),h.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,g),h.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:g,rightApex:v,currentPosition:r,currentStepDirection:m?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class aI{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new nI,this._walker=null,this._movement=new ue,this._millisecondsSinceLastUpdate=aI._MillisecondsPerUpdate,this.movementThisFrame=de.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new oI(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{we.Log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=aI._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=aI._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class lI extends ua{static get Name(){return ha.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new de,this._forward=new de,this._position=new de,this._movement=new de,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&we.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new aI(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||de.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}ca.AddWebXRFeature(lI.Name,((e,t)=>()=>new lI(e,t)),lI.Version,!1);class hI extends Cc{constructor(e,t,i,s,r,n,o=null){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n,this._originalInternalTexture=o}}class cI extends Ec{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new X,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),s="right"==t?1:0,r=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[s]||i?.textureWidth!==r||i?.textureHeight!==n){let i;const o=e.depthStencilTextureWidth??r,a=e.depthStencilTextureHeight??n;r!==o&&n!==a||(i=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(r,n,null,e.colorTexture,i,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e?.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,s=t.colorTextureHeight??t.textureHeight,r=t.viewport;e.x=r.x/i,e.y=r.y/s,e.width=r.width/i,e.height=r.height/s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class uI extends hI{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new dI(e,i,this))),this.layer=e}}class dI extends cI{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}const _I={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},pI={};class fI extends ua{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={..._I,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return!!super.detach()&&(this._existingLayers.forEach((e=>{e.dispose()})),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0)}createXRWebGLLayer(e=pI){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Ac(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=_I,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),s=new uI(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(s),s}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,s=this._existingLayers[0].layer.textureHeight,r={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:s,clearOnAccess:!0,...e.params};this._validateLayerInit(r,!1);const n=this._xrWebGLBinding.createQuadLayer(r);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new hI((()=>n.width),(()=>n.height),n,"XRQuadLayer",!1,(e=>new cI(e,this._xrWebGLBinding,o)));t&&this._compositionLayerTextureMapping.set(n,t);const a=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,a),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),s=i.layer,r={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};s.transform=new XRRigidTransform(r,{x:0,y:0,z:0,w:1});const n=this._layerToRTTProviderMapping.get(s);if(!n)throw new Error("Could not find the RTT provider for the layer");const o=this._xrSessionManager.scene.layers.find((t=>t.texture===e));if(!o)throw new Error("Could not find the babylon layer for the texture");return n.onRenderTargetTextureCreatedObservable.add((e=>{e.eye&&"right"===e.eye||(e.texture.clearColor=new Ee(0,0,0,0),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add((()=>{e.texture.render()})),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce((()=>{o.renderTargetTextures.splice(o.renderTargetTextures.indexOf(e.texture),1),o.renderOnlyInRenderTargetTextures=!1})))})),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;i.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});const s=this._layerToRTTProviderMapping.get(i);if(!s)throw new Error("Could not find the RTT provider for the layer");return s.onRenderTargetTextureCreatedObservable.add((t=>{t.texture.clearColor=new Ee(0,0,0,0),t.texture.customRenderFunction=()=>{e.render()}})),this._xrSessionManager.onXRSessionInit.add((()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)})),this._xrSessionManager.onXRSessionEnded.add((()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)})),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new fI(e,t)),fI.Version,!1);class mI extends ua{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new Pi(e,Ai.Unknown);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format="ushort"===this.depthDataFormat?2:5,t.generateMipMaps=!1,t.type="ushort"===this.depthDataFormat?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Ni(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new X,this.xrNativeFeatureName="depth-sensing",hs.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){this._cachedDepthImageTexture?.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:hs.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{data:r,width:n,height:o,rawValueToMeters:a,getDepthInMeters:l}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Wo.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,Vo.NEAREST_SAMPLINGMODE,gn.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Wo.CreateRTexture(null,n,o,a,!1,!0,Vo.NEAREST_SAMPLINGMODE,"ushort"===i?gn.TEXTURETYPE_UNSIGNED_BYTE:gn.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}mI.Name=ha.DEPTH_SENSING,mI.Version=1,ca.AddWebXRFeature(mI.Name,((e,t)=>()=>new mI(e,t)),mI.Version,!1);bi.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class gI extends pl{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[fe.Identity(),fe.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new Yu("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)})),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[1]}))}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class vI{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new gI(s,r,this._scene,n),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=s,a._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return s&&i?.textureWidth===r&&i?.textureHeight==n||(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.clear()}}class xI extends ua{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[ha.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new vI(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add((()=>this._onAfterRender())),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}xI.Name=ha.SPACE_WARP,xI.Version=1,ca.AddWebXRFeature(xI.Name,(e=>()=>new xI(e)),xI.Version,!1);class bI extends ua{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new X,this.xrNativeFeatureName="camera-access"}attach(e){return!!super.attach(e)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)}detach(){return!!super.detach()&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach((e=>e.dispose())),this.texturesData.forEach((e=>e.dispose())),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],a=i.height/2*s[5],l=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:a,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=this._glBinding?.getCameraImage(e.camera);if(this._cachedInternalTextures[t])this._cachedInternalTextures[t]._hardwareTexture?.set(i);else{const s=new Pi(this._xrSessionManager.scene.getEngine(),Ai.Unknown,!0);s.isCube=!0,s.invertY=!1,s.format=5,s.generateMipMaps=!0,s.type=1,s.samplingMode=3,s.width=e.camera.width,s.height=e.camera.height,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new Ni(i,this._glContext),this._cachedInternalTextures[t]=s;const r=new No(this._xrSessionManager.scene);r.name=`WebXR Raw Camera Access (${t})`,r._texture=this._cachedInternalTextures[t],this.texturesData[t]=r,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let s=!0;i.views.forEach(((e,t)=>{s=s&&this._updateInternalTextures(e,t)})),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}bI.Name=ha.RAW_CAMERA_ACCESS,bI.Version=1,ca.AddWebXRFeature(bI.Name,((e,t)=>()=>new bI(e,t)),bI.Version,!1);class TI extends ug{constructor(e,t,i){super(e,yI[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}mg.RegisterController("generic-hand-select-grasp",((e,t)=>new TI(t,e.gamepad,e.handedness)));const yI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class SI extends ug{constructor(e,t,i){super(e,CI["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?SI.MODEL_LEFT_FILENAME:SI.MODEL_RIGHT_FILENAME,{filename:e,path:SI.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=Pa.IsPluginForExtensionAvailable(".glb");return e||we.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],s=i.rootNodeName;if(!s)return void we.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const r=this._getChildByName(this.rootMesh,s);if(!r)return void we.Warn("Missing button mesh with name: "+s);if(i.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else we.Warn("Missing button submesh under mesh with name: "+s)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const s=this._mapping.axes[e][i],r=this._getChildByName(this.rootMesh,s.rootNodeName);r?(s.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.valueNodeName),s.minMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.minNodeName),s.maxMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.maxNodeName),s.valueMesh&&s.minMesh&&s.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(s,t,!0)}),void 0,!0):we.Warn("Missing axis submesh under mesh with name: "+s.rootNodeName)):we.Warn("Missing axis mesh with name: "+s.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew SI(t,e.gamepad,e.handedness)));const CI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class EI extends ug{constructor(e,t,i,s=!1,r=!1){super(e,AI[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?EI.MODEL_LEFT_FILENAME:EI.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?EI.QUEST_MODEL_BASE_URL:EI.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const s=e&&this.getComponent(e);s&&s.onButtonStateChangedObservable.add((s=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-s.value,this._modelRootNode.getChildren()[3].position.y=.005*-s.value,this._modelRootNode.getChildren()[3].position.z=.005*-s.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*s.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=pe.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}EI.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",EI.MODEL_LEFT_FILENAME="left.babylon",EI.MODEL_RIGHT_FILENAME="right.babylon",EI.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",mg.RegisterController("oculus-touch",((e,t)=>new EI(t,e.gamepad,e.handedness))),mg.RegisterController("oculus-touch-legacy",((e,t)=>new EI(t,e.gamepad,e.handedness,!0)));const AI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class PI extends ug{constructor(e,t,i){super(e,RI[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:PI.MODEL_FILENAME,path:PI.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new bo(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=pe.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}PI.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",PI.MODEL_FILENAME="wand.babylon",mg.RegisterController("htc-vive",((e,t)=>new PI(t,e.gamepad,e.handedness)));const RI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class II{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}var MI;$_("NativeXRFrame",II),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(MI||(MI={}));class OI{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=ns(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=new(hs.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class DI{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new DI(this.value+e.value)}subtract(e){return new DI(this.value-e.value)}multiply(e){return new DI(Math.imul(this.value,e.value))}divide(e){return new DI(this.value/e.value)}getClassName(){return DI.ClassName}equals(e){return this.value===e.value}static Parse(e){return new DI(e.value)}}DI.ClassName="FlowGraphInteger",ee("FlowGraphInteger",DI);class wI{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new wI(e.typeName,e.defaultValue)}}const NI=new wI("any",void 0),FI=new wI("string",""),BI=new wI("number",0),LI=new wI("boolean",!1),kI=new wI("Vector2",ue.Zero()),VI=new wI("Vector3",de.Zero()),UI=new wI("Vector4",_e.Zero()),GI=new wI("Matrix",fe.Identity()),zI=new wI("Color3",Ce.Black()),WI=new wI("Color4",new Ee(0,0,0,0)),HI=new wI("Quaternion",pe.Identity()),XI=new wI("FlowGraphInteger",new DI(0));function YI(e){switch(typeof e){case"string":return FI;case"number":return BI;case"boolean":return LI;case"object":return e instanceof ue?kI:e instanceof de?VI:e instanceof _e?UI:e instanceof Ce?zI:e instanceof Ee?WI:e instanceof pe?HI:e instanceof DI?XI:NI;default:return NI}}class QI extends OI{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===MI.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===MI.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=OI.Parse(e,t);return i.richType=wI.Parse(e.richType),i}}function jI(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function KI(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function $I(e,t,i){const s=t?.getClassName?.()??"";jI(s)?i[e]={name:t.name,className:s}:KI(s)?i[e]={value:t.asArray(),className:s}:i[e]=t}function qI(e,t,i){const s=t[e];let r;const n=s?.className;return r=jI(n)?i.getMeshByName(s.name):KI(n)?function(e,t){if("Vector2"===e)return ue.FromArray(t);if("Vector3"===e)return de.FromArray(t);if("Vector4"===e)return _e.FromArray(t);if("Quaternion"===e)return pe.FromArray(t);if("Color3"===e)return new Ce(t[0],t[1],t[2]);if("Color4"===e)return new Ee(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,s.value):"Matrix"===n?fe.FromArray(s.value):n===DI.ClassName?DI.Parse(s):s&&void 0!==s.value?s.value:s,r}ee("FGDataConnection",QI);class ZI{constructor(e){this.config=e,this.uniqueId=ns(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new QI(e,MI.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new QI(e,MI.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=$I){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=hs.Instantiate(e.className),s={},r=t.valueParseFunction??qI;if(e.config)for(const i in e.config)s[i]=r(i,e.config,t.scene);(function(e){return"FGSetPropertyBlock"===e||"FGGetPropertyBlock"===e||"FGPlayAnimationBlock"===e||"FGMeshPickEventBlock"===e})(e.className)&&(s.pathConverter=t.pathConverter);const n=new i(s);n.uniqueId=e.uniqueId;for(let t=0;tt.name===e))}getSignalOutput(e){return this.signalOutputs.find((t=>t.name===e))}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{t.type===Ms.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||rM(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const s=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return nM.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var oM;nM.ClassName="FGMeshPickEventBlock",ee(nM.ClassName,nM),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(oM||(oM={}));class aM{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=oM.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new sM({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==oM.Started){this.state=oM.Started,0===this._executionContexts.length&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===nM.ClassName){const i=t._getReferencedMesh();let s=0;for(;s0;){const s=t.pop();e(s);for(const e of s.dataInputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId));if(s instanceof eM)for(const e of s.signalOutputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof eM)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??qI;for(const n of e.allBlocks){const e=ZI.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(e),e instanceof iM&&i.addEventBlock(e)}for(const e of s){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=aM.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof eM)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=aM.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(const t of e.executionContexts)sM.Parse(t,{graph:i,valueParseFunction:r});return i}}class lM{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()})),(lM.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new aM({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=lM.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)}))}static Parse(e,t){const i=t.valueParseFunction??qI,s=new lM({scene:t.scene});return e._flowGraphs?.forEach((e=>{aM.Parse(e,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})})),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new X,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}lM.SceneCoordinators=new Map;class hM{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add((e=>{hs.Log(`Node executed: ${e.getClassName()}`)}))}}class cM extends eM{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class uM extends cM{constructor(e){super(e),this.message=this.registerDataInput("message",NI)}_execute(e){const t=this.message.getValue(e);we.Log(t),this.out._activateSignal(e)}getClassName(){return uM.ClassName}}uM.ClassName="FGConsoleLogBlock",ee(uM.ClassName,uM);class dM extends cM{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,NI)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return dM.ClassName}}dM.ClassName="FGSetVariableBlock",ee(dM.ClassName,dM);const _M=new RegExp(/\{(\w+)\}/g);class pM{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=_M.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,XI)),i=_M.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const s=e.getValue(t).value;i=i.replace(`{${e.name}}`,s.toString())}return e.convert(i)}}class fM extends cM{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",NI),this.templateComponent=new pM(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return fM.ClassName}}fM.ClassName="FGSetPropertyBlock",ee("FGSetPropertyBlock",fM);class mM extends cM{constructor(e){super(e),this.config=e;for(let e=0;et.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return mM.ClassName}}mM.ClassName="FGSendCustomEventBlock",ee("FGSendCustomEventBlock",mM);class gM extends eM{constructor(e){super(e),this.condition=this.registerDataInput("condition",LI),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}ee("FGBranchBlock",gM);class vM extends cM{constructor(e={startIndex:new DI(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",XI),this.value=this.registerDataOutput("value",XI)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.values)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const t=s-(r-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}}ee("FGThrottleBlock",bM);class TM extends tM{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",BI)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new Ig({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);-1!==s?i.splice(s,1):hs.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return TM.ClassName}}TM.ClassName="FGTimerBlock",ee("FGTimerBlock",TM);class yM extends eM{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",BI),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter((e=>e!==r)),0===s.length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((e=>e))){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}ee("FGDebounceBlock",PM);class RM extends eM{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",LI)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}ee("FGFlipFlopBlock",RM);class IM extends eM{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e)));this.runningAnimatable.setValue(t,e),n.push(t)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);-1!==s&&i.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const e of t)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return MM.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}MM.ClassName="FGPlayAnimationBlock",ee(MM.ClassName,MM);class OM extends cM{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",NI)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}ee("FGStopAnimationBlock",OM);class DM extends cM{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",NI)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}ee("FGPauseAnimationBlock",DM);class wM extends ZI{constructor(e){super(e),this.condition=this.registerDataInput("condition",LI),this.trueValue=this.registerDataInput("trueValue",NI),this.falseValue=this.registerDataInput("falseValue",NI),this.output=this.registerDataOutput("output",NI)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}ee("FGConditionalDataBlock",wM);class NM extends ZI{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,NI)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return NM.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}NM.ClassName="FGGetVariableBlock",ee(NM.ClassName,NM);class FM extends ZI{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",NI),this.destinationSystem=this.registerDataInput("destinationSystem",NI),this.inputCoordinates=this.registerDataInput("inputCoordinates",VI),this.outputCoordinates=this.registerDataOutput("outputCoordinates",VI)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=ge.Matrix[0].copyFrom(n);o.invert();const a=ge.Matrix[1];o.multiplyToRef(r,a);const l=this.outputCoordinates.getValue(e);de.TransformCoordinatesToRef(s,a,l)}getClassName(){return"FGCoordinateTransformBlock"}}ee("FGCoordinateTransformBlock",FM);class BM extends ZI{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",YI(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=$I){super.serialize(e),t("value",this.config.value,e.config)}}ee("FGConstantBlock",BM);class LM extends ZI{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",NI),this.templateComponent=new pM(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return LM.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}LM.ClassName="FGGetPropertyBlock",ee(LM.ClassName,LM);const kM="cachedOperationValue",VM="cachedExecutionId";class UM extends ZI{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,VM),i=e._getExecutionVariable(this,kM);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,kM,t),e._setExecutionVariable(this,VM,e.executionId),this.value.setValue(t,e)}}}class GM extends UM{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class zM extends UM{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const WM="FGLogic",HM="AndBlock",XM="OrBlock",YM="NotBlock";class QM extends GM{constructor(e){super(LI,LI,LI,((e,t)=>e&&t),`${WM}${HM}`,e)}}ee(`${WM}${HM}`,QM);class jM extends GM{constructor(e){super(LI,LI,LI,((e,t)=>e||t),`${WM}${XM}`,e)}}ee(`${WM}${XM}`,jM);class KM extends zM{constructor(e){super(LI,LI,(e=>!e),`${WM}${YM}`,e)}}ee(`${WM}${YM}`,KM);class $M extends UM{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class qM extends UM{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function ZM(e){return e.getClassName?e.getClassName():""}function JM(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function eO(e,t){return"Matrix"===e&&"Matrix"===t}function tO(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class iO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicAdd(e,t)),iO.ClassName,e)}_polymorphicAdd(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||eO(i,s)||tO(i,s)?e.add(t):e+t}}iO.ClassName="FGAddBlock",ee(iO.ClassName,iO);class sO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicAdd(e,t)),sO.ClassName,e)}_polymorphicAdd(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||tO(i,s)?e.subtract(t):eO(i,s)?e.add(t.scale(-1)):e-t}}sO.ClassName="FGSubBlock",ee(sO.ClassName,sO);class rO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicMultiply(e,t)),rO.ClassName,e)}_polymorphicMultiply(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||tO(i,s)?e.multiply(t):eO(i,s)?fe.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}rO.ClassName="FGMultiplyBlock",ee(rO.ClassName,rO);class nO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicDivide(e,t)),nO.ClassName,e)}_polymorphicDivide(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||tO(i,s)?e.divide(t):eO(i,s)?fe.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}nO.ClassName="FGDivideBlock",ee(nO.ClassName,nO);class oO extends $M{constructor(e){super(BI,(()=>Math.random()),oO.ClassName,e)}}oO.ClassName="FGRandomBlock",ee(oO.ClassName,oO);class aO extends GM{constructor(e){super(NI,NI,BI,((e,t)=>this._polymorphicDot(e,t)),aO.ClassName,e)}_polymorphicDot(e,t){switch(ZM(e)){case"Vector2":return ue.Dot(e,t);case"Vector3":return de.Dot(e,t);case"Vector4":return _e.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}aO.ClassName="FGDotBlock",ee(aO.ClassName,aO);class lO extends $M{constructor(e){super(BI,(()=>Math.E),lO.ClassName,e)}}lO.ClassName="FGEBlock",ee(lO.ClassName,lO);class hO extends $M{constructor(e){super(BI,(()=>Math.PI),hO.ClassName,e)}}hO.ClassName="FGPIBlock",ee(hO.ClassName,hO);class cO extends $M{constructor(e){super(BI,(()=>Number.POSITIVE_INFINITY),cO.ClassName,e)}}cO.ClassName="FGInfBlock",ee(cO.ClassName,cO);class uO extends $M{constructor(e){super(BI,(()=>Number.NaN),uO.ClassName,e)}}function dO(e,t){switch(ZM(e)){case"FlowGraphInteger":return new DI(t(e.value));case"Vector2":return new ue(t(e.x),t(e.y));case"Vector3":return new de(t(e.x),t(e.y),t(e.z));case"Vector4":return new _e(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return fe.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}uO.ClassName="FGNaNBlock",ee(uO.ClassName,uO);class _O extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicAbs(e)),_O.ClassName,e)}_polymorphicAbs(e){return dO(e,Math.abs)}}_O.ClassName="FGAbsBlock",ee(_O.ClassName,_O);class pO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicSign(e)),pO.ClassName,e)}_polymorphicSign(e){return dO(e,Math.sign)}}pO.ClassName="FGSignBlock",ee(pO.ClassName,pO);class fO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicTrunc(e)),fO.ClassName,e)}_polymorphicTrunc(e){return dO(e,Math.trunc)}}fO.ClassName="FGTruncBlock",ee(fO.ClassName,fO);class mO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicFloor(e)),mO.ClassName,e)}_polymorphicFloor(e){return dO(e,Math.floor)}}mO.ClassName="FGFloorBlock",ee(mO.ClassName,mO);class gO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicCeiling(e)),gO.ClassName,e)}_polymorphicCeiling(e){return dO(e,Math.ceil)}}gO.ClassName="FGCeilBlock",ee(gO.ClassName,gO);class vO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicFract(e)),vO.ClassName,e)}_polymorphicFract(e){return dO(e,(e=>e-Math.floor(e)))}}vO.ClassName="FGFractBlock",ee(vO.ClassName,vO);class xO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicNeg(e)),xO.ClassName,e)}_polymorphicNeg(e){return dO(e,(e=>-e))}}function bO(e,t,i){switch(ZM(e)){case"FlowGraphInteger":return new DI(i(e.value,t.value));case"Vector2":return new ue(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new de(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new _e(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return fe.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}xO.ClassName="FGNegBlock",ee(xO.ClassName,xO);class TO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicRemainder(e,t)),TO.ClassName,e)}_polymorphicRemainder(e,t){return bO(e,t,((e,t)=>e%t))}}TO.ClassName="FGRemainderBlock",ee(TO.ClassName,TO);class yO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicMin(e,t)),yO.ClassName,e)}_polymorphicMin(e,t){return bO(e,t,Math.min)}}yO.ClassName="FGMinBlock",ee(yO.ClassName,yO);class SO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicMax(e,t)),SO.ClassName,e)}_polymorphicMax(e,t){return bO(e,t,Math.max)}}function CO(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function EO(e,t,i,s){switch(ZM(e)){case"FlowGraphInteger":return new DI(s(e.value,t.value,i.value));case"Vector2":return new ue(s(e.x,t.x,i.x),s(e.y,t.y,i.y));case"Vector3":return new de(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z));case"Vector4":return new _e(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z),s(e.w,t.w,i.w));case"Matrix":return fe.FromValues(s(e.m[0],t.m[0],i.m[0]),s(e.m[4],t.m[4],i.m[4]),s(e.m[8],t.m[8],i.m[8]),s(e.m[12],t.m[12],i.m[12]),s(e.m[1],t.m[1],i.m[1]),s(e.m[5],t.m[5],i.m[5]),s(e.m[9],t.m[9],i.m[9]),s(e.m[13],t.m[13],i.m[13]),s(e.m[2],t.m[2],i.m[2]),s(e.m[6],t.m[6],i.m[6]),s(e.m[10],t.m[10],i.m[10]),s(e.m[14],t.m[14],i.m[14]),s(e.m[3],t.m[3],i.m[3]),s(e.m[7],t.m[7],i.m[7]),s(e.m[11],t.m[11],i.m[11]),s(e.m[15],t.m[15],i.m[15]));default:return s(e,t,i)}}SO.ClassName="FGMaxBlock",ee(SO.ClassName,SO);class AO extends qM{constructor(e){super(NI,NI,NI,NI,((e,t,i)=>this._polymorphicClamp(e,t,i)),AO.ClassName,e)}_polymorphicClamp(e,t,i){return EO(e,t,i,CO)}}function PO(e){return Math.min(Math.max(e,0),1)}AO.ClassName="FGClampBlock",ee(AO.ClassName,AO);class RO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicSaturate(e)),RO.ClassName,e)}_polymorphicSaturate(e){return dO(e,PO)}}RO.ClassName="FGSaturateBlock",ee(RO.ClassName,RO);class IO extends qM{constructor(e){super(NI,NI,NI,NI,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),IO.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return EO(e,t,i,this._interpolate)}}IO.ClassName="FGInterpolateBlock",ee(IO.ClassName,IO);class MO extends GM{constructor(e){super(NI,NI,LI,((e,t)=>this._polymorphicEq(e,t)),MO.ClassName,e)}_polymorphicEq(e,t){const i=ZM(e),s=ZM(t);return JM(i,s)||eO(i,s)||tO(i,s)?e.equals(t):e===t}}function OO(e,t,i){const s=ZM(e);if(s===ZM(t)){if(""===s)return i(e,t);if("FlowGraphInteger"===s)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}MO.ClassName="FGEqBlock",ee(MO.ClassName,MO);class DO extends GM{constructor(e){super(NI,NI,LI,((e,t)=>this._polymorphicLessThan(e,t)),DO.ClassName,e)}_polymorphicLessThan(e,t){return OO(e,t,((e,t)=>ethis._polymorphicLessThanOrEqual(e,t)),wO.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return OO(e,t,((e,t)=>e<=t))}}wO.ClassName="FGLessThanOrEqualBlock";class NO extends GM{constructor(e){super(NI,NI,LI,((e,t)=>this._polymorphicGreaterThan(e,t)),NO.ClassName,e)}_polymorphicGreaterThan(e,t){return OO(e,t,((e,t)=>e>t))}}NO.ClassName="FGGreaterThanBlock",ee(NO.ClassName,NO);class FO extends GM{constructor(e){super(NI,NI,LI,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),FO.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return OO(e,t,((e,t)=>e>=t))}}FO.ClassName="FGGreaterThanOrEqualBlock",ee(FO.ClassName,FO);class BO extends zM{constructor(e){super(NI,LI,(e=>this._polymorphicIsNan(e)),BO.ClassName,e)}_polymorphicIsNan(e){const t=ZM(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}BO.ClassName="FGIsNanBlock",ee(BO.ClassName,BO);class LO extends zM{constructor(e){super(NI,LI,(e=>this._polymorphicIsInf(e)),LO.ClassName,e)}_polymorphicIsInf(e){const t=ZM(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}LO.ClassName="FGIsInfBlock";class kO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicDegToRad(e)),kO.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return dO(e,this._degToRad)}}kO.ClassName="FGDegToRadBlock",ee(kO.ClassName,kO);class VO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicRadToDeg(e)),VO.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return dO(e,this._radToDeg)}}VO.ClassName="FGRadToDegBlock",ee(VO.ClassName,VO);class UO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicSin(e)),UO.ClassName,e)}_polymorphicSin(e){return dO(e,Math.sin)}}UO.ClassName="FGSinBlock",ee(UO.ClassName,UO);class GO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicCos(e)),GO.ClassName,e)}_polymorphicCos(e){return dO(e,Math.cos)}}GO.ClassName="FGCosBlock",ee(GO.ClassName,GO);class zO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicTan(e)),zO.ClassName,e)}_polymorphicTan(e){return dO(e,Math.tan)}}zO.ClassName="FGTanBlock",ee(zO.ClassName,zO);class WO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicAsin(e)),WO.ClassName,e)}_polymorphicAsin(e){return dO(e,Math.asin)}}WO.ClassName="FGAsinBlock",ee(WO.ClassName,WO);class HO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicAcos(e)),HO.ClassName,e)}_polymorphicAcos(e){return dO(e,Math.acos)}}HO.ClassName="FGAcosBlock",ee(HO.ClassName,HO);class XO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicAtan(e)),XO.ClassName,e)}_polymorphicAtan(e){return dO(e,Math.atan)}}XO.ClassName="FGAtanBlock",ee(XO.ClassName,XO);class YO extends GM{constructor(e){super(NI,NI,NI,((e,t)=>this._polymorphicAtan2(e,t)),YO.ClassName,e)}_polymorphicAtan2(e,t){return bO(e,t,Math.atan2)}}YO.ClassName="FGAtan2Block",ee(YO.ClassName,YO);class QO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicSinh(e)),QO.ClassName,e)}_polymorphicSinh(e){return dO(e,Math.sinh)}}QO.ClassName="FGSinhBlock",ee(QO.ClassName,QO);class jO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicCosh(e)),jO.ClassName,e)}_polymorphicCosh(e){return dO(e,Math.cosh)}}jO.ClassName="FGCoshBlock",ee(jO.ClassName,jO);class KO extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicTanh(e)),KO.ClassName,e)}_polymorphicTanh(e){return dO(e,Math.tanh)}}KO.ClassName="FGTanhBlock",ee(KO.ClassName,KO);class $O extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicAsinh(e)),$O.ClassName,e)}_polymorphicAsinh(e){return dO(e,Math.asinh)}}$O.ClassName="FGAsinhBlock",ee($O.ClassName,$O);class qO extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicAcosh(e)),qO.ClassName,e)}_polymorphicAcosh(e){return dO(e,Math.acosh)}}qO.ClassName="FGAcoshBlock",ee(qO.ClassName,qO);class ZO extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicAtanh(e)),ZO.ClassName,e)}_polymorphicAtanh(e){return dO(e,Math.atanh)}}ZO.ClassName="FGAtanhBlock",ee(ZO.ClassName,ZO);class JO extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicExp(e)),JO.ClassName,e)}_polymorphicExp(e){return dO(e,Math.exp)}}JO.ClassName="FGExpBlock",ee(JO.ClassName,JO);class eD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicLog(e)),eD.ClassName,e)}_polymorphicLog(e){return dO(e,Math.log)}}eD.ClassName="FGLogBlock",ee(eD.ClassName,eD);class tD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicLog2(e)),tD.ClassName,e)}_polymorphicLog2(e){return dO(e,Math.log2)}}tD.ClassName="FGLog2Block",ee(tD.ClassName,tD);class iD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicLog10(e)),iD.ClassName,e)}_polymorphicLog10(e){return dO(e,Math.log10)}}iD.ClassName="FGLog10Block",ee(iD.ClassName,iD);class sD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicSqrt(e)),sD.ClassName,e)}_polymorphicSqrt(e){return dO(e,Math.sqrt)}}sD.ClassName="FGSqrtBlock",ee(sD.ClassName,sD);class rD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicCubeRoot(e)),rD.ClassName,e)}_polymorphicCubeRoot(e){return dO(e,Math.cbrt)}}rD.ClassName="FGCubeRootBlock",ee(rD.ClassName,rD);class nD extends GM{constructor(e){super(NI,BI,BI,((e,t)=>this._polymorphicPow(e,t)),nD.ClassName,e)}_polymorphicPow(e,t){return bO(e,t,Math.pow)}}nD.ClassName="FGPowBlock",ee(nD.ClassName,nD);class oD extends zM{constructor(e){super(NI,BI,(e=>this._polymorphicLength(e)),oD.ClassName,e)}_polymorphicLength(e){switch(ZM(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}oD.ClassName="FGLengthBlock",ee(oD.ClassName,oD);class aD extends zM{constructor(e){super(NI,NI,(e=>this._polymorphicNormalize(e)),aD.ClassName,e)}_polymorphicNormalize(e){switch(ZM(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}aD.ClassName="FGNormalizeBlock",ee(aD.ClassName,aD);class lD extends GM{constructor(e){super(VI,VI,VI,((e,t)=>de.Cross(e,t)),lD.ClassName,e)}}lD.ClassName="FGCrossBlock",ee(lD.ClassName,lD);class hD extends GM{constructor(e){super(kI,BI,kI,((e,t)=>ue.Transform(e,fe.RotationZ(t))),hD.ClassName,e)}}hD.ClassName="FGRotate2DBlock",ee(hD.ClassName,hD);class cD extends qM{constructor(e){super(VI,VI,BI,VI,((e,t,i)=>de.TransformCoordinates(e,fe.RotationAxis(t,i))),cD.ClassName,e)}}cD.ClassName="FGRotate3DBlock",ee(cD.ClassName,cD);class uD extends zM{constructor(e){super(GI,GI,(e=>fe.Transpose(e)),uD.ClassName,e)}}uD.ClassName="FGTransposeBlock",ee(uD.ClassName,uD);class dD extends zM{constructor(e){super(GI,BI,(e=>e.determinant()),dD.ClassName,e)}}dD.ClassName="FGDeterminantBlock",ee(dD.ClassName,dD);class _D extends zM{constructor(e){super(GI,GI,(e=>fe.Invert(e)),_D.ClassName,e)}}_D.ClassName="FGInvertMatrixBlock",ee(_D.ClassName,_D);class pD extends GM{constructor(e){super(GI,GI,GI,((e,t)=>t.multiply(e)),pD.ClassName,e)}}pD.ClassName="FGMatMulBlock",ee(pD.ClassName,pD);class fD extends zM{constructor(e){super(XI,XI,(e=>new DI(~e.value)),fD.ClassName,e)}}fD.ClassName="FGBitwiseNotBlock",ee(fD.ClassName,fD);class mD extends GM{constructor(e){super(XI,XI,XI,((e,t)=>new DI(e.value&t.value)),mD.ClassName,e)}}mD.ClassName="FGBitwiseAndBlock",ee(mD.ClassName,mD);class gD extends GM{constructor(e){super(XI,XI,XI,((e,t)=>new DI(e.value|t.value)),gD.ClassName,e)}}gD.ClassName="FGBitwiseOrBlock",ee(gD.ClassName,gD);class vD extends GM{constructor(e){super(XI,XI,XI,((e,t)=>new DI(e.value^t.value)),vD.ClassName,e)}}vD.ClassName="FGBitwiseXorBlock",ee(vD.ClassName,vD);class xD extends GM{constructor(e){super(XI,XI,XI,((e,t)=>new DI(e.value<new DI(e.value>>t.value)),bD.ClassName,e)}}bD.ClassName="FGBitwiseRightShiftBlock",ee(bD.ClassName,bD);class TD extends zM{constructor(e){super(XI,XI,(e=>new DI(Math.clz32(e.value))),TD.ClassName,e)}}TD.ClassName="FGCountLeadingZerosBlock",ee(TD.ClassName,TD);class yD extends zM{constructor(e){super(XI,XI,(e=>new DI(e.value?31-Math.clz32(e.value&-e.value):32)),yD.ClassName,e)}}yD.ClassName="FGCountTrailingZerosBlock",ee(yD.ClassName,yD);class SD extends zM{constructor(e){super(XI,XI,(e=>new DI(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),SD.ClassName,e)}}SD.ClassName="FGCountOneBitsBlock",ee(SD.ClassName,SD);class CD extends iM{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return CD.ClassName}}CD.ClassName="FGSceneReadyEventBlock",ee("FGSceneReadyEventBlock",CD);class ED extends iM{constructor(e){super(e),this.config=e;for(let e=0;e{for(let i=0;i{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return AD.ClassName}}AD.ClassName="FGSceneTickEventBlock",ee(AD.ClassName,AD);class PD{constructor(e,t=PD.UNITMODE_PIXEL,i=!0){this.negativeValueAllowed=i,this._value=1,this._unit=PD.UNITMODE_PIXEL,this.ignoreAdaptiveScaling=!1,this.onChangedObservable=new X,this._value=e,this._unit=t,this._originalUnit=t}get isPercentage(){return this._unit===PD.UNITMODE_PERCENTAGE}get isPixel(){return this._unit===PD.UNITMODE_PIXEL}get internalValue(){return this._value}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this.onChangedObservable.notifyObservers())}get unit(){return this._unit}set unit(e){e!==this._unit&&(this._unit=e,this.onChangedObservable.notifyObservers())}getValueInPixel(e,t){return this.isPixel?this.getValue(e):this.getValue(e)*t}updateInPlace(e,t=PD.UNITMODE_PIXEL){return this.value===e&&this.unit===t||(this._value=e,this._unit=t,this.onChangedObservable.notifyObservers()),this}getValue(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==PD.UNITMODE_PERCENTAGE){let t=0,i=0;if(e.idealWidth&&(t=Math.ceil(this._value*e.getSize().width/e.idealWidth)),e.idealHeight&&(i=Math.ceil(this._value*e.getSize().height/e.idealHeight)),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidth{this._markAsDirty(),this._resetFontCache()}))),this._markAsDirty(),this._resetFontCache()}get _isFontSizeInPercentage(){return this._fontSize.isPercentage}get fontSizeInPixels(){const e=this._style?this._style._fontSize:this._fontSize;return e.isPixel?e.getValue(this._host):e.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)}set fontSizeInPixels(e){isNaN(e)||(this.fontSize=e+"px")}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&(this._markAsDirty(),this._resetFontCache())}get color(){return this._color}set color(e){this._color!==e&&(this._color=e,this._markAsDirty())}get gradient(){return this._gradient}set gradient(e){this._gradient!==e&&(this._gradient=e,this._markAsDirty())}get zIndex(){return this._zIndex}set zIndex(e){this.zIndex!==e&&(this._zIndex=e,this.parent&&this.parent._reOrderControl(this))}get notRenderable(){return this._doNotRender}set notRenderable(e){this._doNotRender!==e&&(this._doNotRender=e,this._markAsDirty())}get isVisible(){return this._isVisible}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this._markAsDirty(!0),this.onIsVisibleChangedObservable.notifyObservers(e))}get isDirty(){return this._isDirty}get linkedMesh(){return this._linkedMesh}get descendantsOnlyPadding(){return this._descendantsOnlyPadding}set descendantsOnlyPadding(e){this._descendantsOnlyPadding!==e&&(this._descendantsOnlyPadding=e,this._markAsDirty())}get paddingLeft(){return this._paddingLeft.toString(this._host)}set paddingLeft(e){this._paddingLeft.fromString(e)&&this._markAsDirty()}get paddingLeftInPixels(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingLeftInPixels(e){isNaN(e)||(this.paddingLeft=e+"px")}get _paddingLeftInPixels(){return this._descendantsOnlyPadding?0:this.paddingLeftInPixels}get paddingRight(){return this._paddingRight.toString(this._host)}set paddingRight(e){this._paddingRight.fromString(e)&&this._markAsDirty()}get paddingRightInPixels(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingRightInPixels(e){isNaN(e)||(this.paddingRight=e+"px")}get _paddingRightInPixels(){return this._descendantsOnlyPadding?0:this.paddingRightInPixels}get paddingTop(){return this._paddingTop.toString(this._host)}set paddingTop(e){this._paddingTop.fromString(e)&&this._markAsDirty()}get paddingTopInPixels(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingTopInPixels(e){isNaN(e)||(this.paddingTop=e+"px")}get _paddingTopInPixels(){return this._descendantsOnlyPadding?0:this.paddingTopInPixels}get paddingBottom(){return this._paddingBottom.toString(this._host)}set paddingBottom(e){this._paddingBottom.fromString(e)&&this._markAsDirty()}get paddingBottomInPixels(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingBottomInPixels(e){isNaN(e)||(this.paddingBottom=e+"px")}get _paddingBottomInPixels(){return this._descendantsOnlyPadding?0:this.paddingBottomInPixels}get left(){return this._left.toString(this._host)}set left(e){this._left.fromString(e)&&this._markAsDirty()}get leftInPixels(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)}set leftInPixels(e){isNaN(e)||(this.left=e+"px")}get top(){return this._top.toString(this._host)}set top(e){this._top.fromString(e)&&this._markAsDirty()}get topInPixels(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)}set topInPixels(e){isNaN(e)||(this.top=e+"px")}get linkOffsetX(){return this._linkOffsetX.toString(this._host)}set linkOffsetX(e){this._linkOffsetX.fromString(e)&&this._markAsDirty()}get linkOffsetXInPixels(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)}set linkOffsetXInPixels(e){isNaN(e)||(this.linkOffsetX=e+"px")}get linkOffsetY(){return this._linkOffsetY.toString(this._host)}set linkOffsetY(e){this._linkOffsetY.fromString(e)&&this._markAsDirty()}get linkOffsetYInPixels(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)}set linkOffsetYInPixels(e){isNaN(e)||(this.linkOffsetY=e+"px")}get centerX(){return this._currentMeasure.left+this._currentMeasure.width/2}get centerY(){return this._currentMeasure.top+this._currentMeasure.height/2}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled===e)return;this._isEnabled=e,this._markAsDirty();const t=e=>{if(e.host){for(const t in e.host._lastControlOver)e===this.host._lastControlOver[t]&&(e._onPointerOut(e,null,!0),delete e.host._lastControlOver[t]);void 0!==e.children&&e.children.forEach(t)}};t(this),this.onEnabledStateChangedObservable.notifyObservers(e)}get disabledColor(){return this._disabledColor}set disabledColor(e){this._disabledColor!==e&&(this._disabledColor=e,this._markAsDirty())}get disabledColorItem(){return this._disabledColorItem}set disabledColorItem(e){this._disabledColorItem!==e&&(this._disabledColorItem=e,this._markAsDirty())}constructor(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=DD.Empty(),this._tempPaddingMeasure=DD.Empty(),this._fontFamily="",this._fontStyle="",this._fontWeight="",this._fontSize=new PD(18,PD.UNITMODE_PIXEL,!1),this._width=new PD(1,PD.UNITMODE_PERCENTAGE,!1),this._height=new PD(1,PD.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._wasDirty=!1,this._tempParentMeasure=DD.Empty(),this._prevCurrentMeasureTransformedIntoGlobalSpace=DD.Empty(),this._cachedParentMeasure=DD.Empty(),this._descendantsOnlyPadding=!1,this._paddingLeft=new PD(0),this._paddingRight=new PD(0),this._paddingTop=new PD(0),this._paddingBottom=new PD(0),this._left=new PD(0),this._top=new PD(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=ND.Identity(),this._invertTransformMatrix=ND.Identity(),this._transformedPosition=ue.Zero(),this._isMatrixDirty=!0,this._isVisible=!0,this._isHighlighted=!1,this._highlightColor="#4affff",this._highlightLineWidth=2,this._fontSet=!1,this._dummyVector2=ue.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this._evaluatedMeasure=new DD(0,0,0,0),this._evaluatedParentMeasure=new DD(0,0,0,0),this._isEnabled=!0,this._disabledColor="#9a9a9a",this._disabledColorItem="#6a6a6a",this._isReadOnly=!1,this._gradient=null,this._rebuildLayout=!1,this.onEnabledStateChangedObservable=new X,this._customData={},this._isClipped=!1,this._automaticSize=!1,this.metadata=null,this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this._clipChildren=!0,this._clipContent=!0,this.useBitmapCache=!1,this._shadowOffsetX=0,this._shadowOffsetY=0,this._shadowBlur=0,this._previousShadowBlur=0,this._shadowColor="black",this.hoverCursor="",this._linkOffsetX=new PD(0),this._linkOffsetY=new PD(0),this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new X,this.onWheelObservable=new X,this.onPointerMoveObservable=new X,this.onPointerOutObservable=new X,this.onPointerDownObservable=new X,this.onPointerUpObservable=new X,this.onPointerClickObservable=new X,this.onPointerEnterObservable=new X,this.onDirtyObservable=new X,this.onBeforeDrawObservable=new X,this.onAfterDrawObservable=new X,this.onDisposeObservable=new X,this.onIsVisibleChangedObservable=new X,this.isSerializable=!0,this._fixedRatio=0,this._fixedRatioMasterIsWidth=!0,this.animations=null,this._tmpMeasureA=new DD(0,0,0,0)}_getTypeName(){return"Control"}getAscendantOfClass(e){return this.parent?this.parent.getClassName()===e?this.parent:this.parent.getAscendantOfClass(e):null}markAsDirty(e=!1){this._markAsDirty(e)}markAllAsDirty(){this._markAllAsDirty()}_resetFontCache(){this._fontSet=!0,this._markAsDirty()}isAscendant(e){return!!this.parent&&(this.parent===e||this.parent.isAscendant(e))}getLocalCoordinates(e){const t=ue.Zero();return this.getLocalCoordinatesToRef(e,t),t}getLocalCoordinatesToRef(e,t){return t.x=e.x-this._currentMeasure.left,t.y=e.y-this._currentMeasure.top,this}getParentLocalCoordinates(e){const t=ue.Zero();return t.x=e.x-this._cachedParentMeasure.left,t.y=e.y-this._cachedParentMeasure.top,t}moveToVector3(e,t){if(!this._host||this.parent!==this._host._rootContainer)return void hs.Error("Cannot move a control to a vector3 if the control is not at root level");this.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP;const i=this._host._getGlobalViewport(),s=de.Project(e,fe.IdentityReadOnly,t.getTransformMatrix(),i);this._moveToProjectedPosition(s),s.z<0||s.z>1?this.notRenderable=!0:this.notRenderable=!1}getDescendantsToRef(e,t=!1,i){}getDescendants(e,t){const i=[];return this.getDescendantsToRef(i,e,t),i}linkWithMesh(e){if(!this._host||this.parent&&this.parent!==this._host._rootContainer)return void(e&&hs.Error("Cannot link a control to a mesh if the control is not at root level"));const t=this._host._linkedControls.indexOf(this);if(-1!==t)return this._linkedMesh=e,void(e||this._host._linkedControls.splice(t,1));e&&(this.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._host._linkedControls.push(this))}setPadding(e,t,i,s){const r=e,n=t??r,o=i??r,a=s??n;this.paddingTop=r,this.paddingRight=n,this.paddingBottom=o,this.paddingLeft=a}setPaddingInPixels(e,t,i,s){const r=e,n=t??r,o=i??r,a=s??n;this.paddingTopInPixels=r,this.paddingRightInPixels=n,this.paddingBottomInPixels=o,this.paddingLeftInPixels=a}_moveToProjectedPosition(e){const t=this._left.getValue(this._host),i=this._top.getValue(this._host),s=this.parent?._currentMeasure;s&&this._processMeasures(s,this._host.getContext());let r=e.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,n=e.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;const o=this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling;o&&(Math.abs(r-t)<.5&&(r=t),Math.abs(n-i)<.5&&(n=i)),(o||t!==r||i!==n)&&(this.left=r+"px",this.top=n+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0,this._markAsDirty())}_offsetLeft(e){this._isDirty=!0,this._currentMeasure.left+=e}_offsetTop(e){this._isDirty=!0,this._currentMeasure.top+=e}_markMatrixAsDirty(){this._isMatrixDirty=!0,this._flagDescendantsAsMatrixDirty()}_flagDescendantsAsMatrixDirty(){}_intersectsRect(e,t){return this._transform(t),!(this._evaluatedMeasure.left>=e.left+e.width||this._evaluatedMeasure.top>=e.top+e.height||this._evaluatedMeasure.left+this._evaluatedMeasure.width<=e.left||this._evaluatedMeasure.top+this._evaluatedMeasure.height<=e.top)}_computeAdditionalOffsetX(){return 0}_computeAdditionalOffsetY(){return 0}invalidateRect(){if(this._transform(),this.host&&this.host.useInvalidateRectOptimization){this._currentMeasure.transformToRef(this._transformMatrix,this._tmpMeasureA),DD.CombineToRef(this._tmpMeasureA,this._prevCurrentMeasureTransformedIntoGlobalSpace,this._tmpMeasureA);const e=this.shadowOffsetX,t=this.shadowOffsetY,i=Math.max(this._previousShadowBlur,this.shadowBlur),s=Math.min(Math.min(e,0)-2*i,0),r=Math.max(Math.max(e,0)+2*i,0),n=Math.min(Math.min(t,0)-2*i,0),o=Math.max(Math.max(t,0)+2*i,0),a=this._computeAdditionalOffsetX(),l=this._computeAdditionalOffsetY();this.host.invalidateRect(Math.floor(this._tmpMeasureA.left+s-a),Math.floor(this._tmpMeasureA.top+n-l),Math.ceil(this._tmpMeasureA.left+this._tmpMeasureA.width+r+a),Math.ceil(this._tmpMeasureA.top+this._tmpMeasureA.height+o+l))}}_markAsDirty(e=!1){(this._isVisible||e)&&(this._isDirty=!0,this._markMatrixAsDirty(),this._host&&this._host.markAsDirty())}_markAllAsDirty(){this._markAsDirty(),this._font&&this._prepareFont()}_link(e){this._host=e,this._host&&(this.uniqueId=this._host.getScene().getUniqueId())}_transform(e){if(!this._isMatrixDirty&&1===this._scaleX&&1===this._scaleY&&0===this._rotation)return;const t=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;e&&(e.translate(t,i),e.rotate(this._rotation),e.scale(this._scaleX,this._scaleY),e.translate(-t,-i)),(this._isMatrixDirty||this._cachedOffsetX!==t||this._cachedOffsetY!==i)&&(this._cachedOffsetX=t,this._cachedOffsetY=i,this._isMatrixDirty=!1,this._flagDescendantsAsMatrixDirty(),ND.ComposeToRef(-t,-i,this._rotation,this._scaleX,this._scaleY,this.parent?this.parent._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure))}_renderHighlight(e){this.isHighlighted&&(e.save(),e.strokeStyle=this._highlightColor,e.lineWidth=this._highlightLineWidth,this._renderHighlightSpecific(e),e.restore())}_renderHighlightSpecific(e){e.strokeRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)}_getColor(e){return this.gradient?this.gradient.getCanvasGradient(e):this.color}_applyStates(e){this._isFontSizeInPercentage&&(this._fontSet=!0),this._host&&this._host.useSmallestIdeal&&!this._font&&(this._fontSet=!0),this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(e.font=this._font),(this._color||this.gradient)&&(e.fillStyle=this._getColor(e)),BD.AllowAlphaInheritance?e.globalAlpha*=this._alpha:this._alphaSet&&(e.globalAlpha=this.parent&&!this.parent.renderToIntermediateTexture?this.parent.alpha*this._alpha:this._alpha)}_layout(e,t){if(!this.isDirty&&(!this.isVisible||this.notRenderable))return!1;if(this._isDirty||!this._cachedParentMeasure.isEqualsTo(e)){this.host._numLayoutCalls++,this._currentMeasure.addAndTransformToRef(this._transformMatrix,0|-this._paddingLeftInPixels,0|-this._paddingTopInPixels,0|this._paddingRightInPixels,0|this._paddingBottomInPixels,this._prevCurrentMeasureTransformedIntoGlobalSpace),t.save(),this._applyStates(t);let i=0;do{this._rebuildLayout=!1,this._processMeasures(e,t),i++}while(this._rebuildLayout&&i<3);i>=3&&we.Error(`Layout cycle detected in GUI (Control name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this.invalidateRect(),this._evaluateClippingState(e)}return this._wasDirty=this._isDirty,this._isDirty=!1,!0}_processMeasures(e,t){this._tempPaddingMeasure.copyFrom(e),this.parent&&this.parent.descendantsOnlyPadding&&(this._tempPaddingMeasure.left+=this.parent.paddingLeftInPixels,this._tempPaddingMeasure.top+=this.parent.paddingTopInPixels,this._tempPaddingMeasure.width-=this.parent.paddingLeftInPixels+this.parent.paddingRightInPixels,this._tempPaddingMeasure.height-=this.parent.paddingTopInPixels+this.parent.paddingBottomInPixels),this._currentMeasure.copyFrom(this._tempPaddingMeasure),this._preMeasure(this._tempPaddingMeasure,t),this._measure(),this._postMeasure(this._tempPaddingMeasure,t),this._computeAlignment(this._tempPaddingMeasure,t),this._currentMeasure.left=0|this._currentMeasure.left,this._currentMeasure.top=0|this._currentMeasure.top,this._currentMeasure.width=0|this._currentMeasure.width,this._currentMeasure.height=0|this._currentMeasure.height,this._additionalProcessing(this._tempPaddingMeasure,t),this._cachedParentMeasure.copyFrom(this._tempPaddingMeasure),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)}_evaluateClippingState(e){if(this._transform(),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.parent&&this.parent.clipChildren){if(e.transformToRef(this.parent._transformMatrix,this._evaluatedParentMeasure),this._evaluatedMeasure.left>this._evaluatedParentMeasure.left+this._evaluatedParentMeasure.width)return void(this._isClipped=!0);if(this._evaluatedMeasure.left+this._evaluatedMeasure.widththis._evaluatedParentMeasure.top+this._evaluatedParentMeasure.height)return void(this._isClipped=!0);if(this._evaluatedMeasure.top+this._evaluatedMeasure.heightthis._currentMeasure.left+this._currentMeasure.width||tthis._currentMeasure.top+this._currentMeasure.height||(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),0))}_processPicking(e,t,i,s,r,n,o,a){return!(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this._doNotRender||!this.contains(e,t)||(this._processObservables(s,e,t,i,r,n,o,a),0))}_onPointerMove(e,t,i,s){this.onPointerMoveObservable.notifyObservers(t,-1,e,this,s)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerMove(e,t,i,s)}_onPointerEnter(e,t){return!!this._isEnabled&&(!(this._enterCount>0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,e,this,t)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerEnter(e,t),!0))}_onPointerOut(e,t,i=!1){if(!(i||this._isEnabled&&e!==this))return;this._enterCount=0;let s=!0;e.isAscendant(this)||(s=this.onPointerOutObservable.notifyObservers(this,-1,e,this,t)),s&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return this._onPointerEnter(this,r),0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new wD(t,s),-1,e,this,r)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerDown(e,t,i,s,r),r&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.add(r.event.pointerId),!0)}_onPointerUp(e,t,i,s,r,n){if(!this._isEnabled)return;this._downCount=0,delete this._downPointerIds[i];let o=r;r&&(this._enterCount>0||-1===this._enterCount)&&(o=this.onPointerClickObservable.notifyObservers(new wD(t,s),-1,e,this,n)),this.onPointerUpObservable.notifyObservers(new wD(t,s),-1,e,this,n)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerUp(e,t,i,s,o,n),n&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.delete(n.event.pointerId)}_forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,ue.Zero(),e,0,!0);else for(const e in this._downPointerIds)this._onPointerUp(this,ue.Zero(),+e,0,!0)}_onWheelScroll(e,t){this._isEnabled&&this.onWheelObservable.notifyObservers(new ue(e,t))&&null!=this.parent&&this.parent._onWheelScroll(e,t)}_onCanvasBlur(){}_processObservables(e,t,i,s,r,n,o,a){if(!this._isEnabled)return!1;if(this._dummyVector2.copyFromFloats(t,i),e===Ms.POINTERMOVE){this._onPointerMove(this,this._dummyVector2,r,s);const e=this._host._lastControlOver[r];return e&&e!==this&&e._onPointerOut(this,s),e!==this&&this._onPointerEnter(this,s),this._host._lastControlOver[r]=this,!0}return e===Ms.POINTERDOWN?(this._onPointerDown(this,this._dummyVector2,r,n,s),this._host._registerLastControlDown(this,r),this._host._lastPickedControl=this,!0):e===Ms.POINTERUP?(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,this._dummyVector2,r,n,!0,s),delete this._host._lastControlDown[r],!0):!(e!==Ms.POINTERWHEEL||!this._host._lastControlOver[r]||(this._host._lastControlOver[r]._onWheelScroll(o,a),0))}_getStyleProperty(e,t){const i=(this._style&&this._style[e])??this[e];return!i&&this.parent?this.parent._getStyleProperty(e,t):this.parent?i:t}_prepareFont(){(this._font||this._fontSet)&&(this._font=this._getStyleProperty("fontStyle","")+" "+this._getStyleProperty("fontWeight","")+" "+this.fontSizeInPixels+"px "+this._getStyleProperty("fontFamily","Arial"),this._fontOffset=BD._GetFontOffset(this._font),this.getDescendants().forEach((e=>e._markAllAsDirty())))}isDimensionFullyDefined(e){return this.getDimension(e).isPixel}getDimension(e){return"width"===e?this._width:this._height}clone(e){const t={};this.serialize(t,!0);const i=new(hs.Instantiate("BABYLON.GUI."+t.className));return i.parse(t,e),i}parse(e,t){return yt.Parse((()=>this),e,null),this.name=e.name,this._parseFromContent(e,t??this._host),this}serialize(e,t=!1){(this.isSerializable||t)&&(yt.Serialize(this,e),e.name=this.name,e.className=this.getClassName(),this._prepareFont(),this._font&&(e.fontFamily=this._fontFamily,e.fontSize=this.fontSize,e.fontWeight=this.fontWeight,e.fontStyle=this.fontStyle),this._gradient&&(e.gradient={},this._gradient.serialize(e.gradient)),yt.AppendSerializedAnimations(this,e))}_parseFromContent(e,t){if(e.fontFamily&&(this.fontFamily=e.fontFamily),e.fontSize&&(this.fontSize=e.fontSize),e.fontWeight&&(this.fontWeight=e.fontWeight),e.fontStyle&&(this.fontStyle=e.fontStyle),e.gradient){const t=hs.Instantiate("BABYLON.GUI."+e.gradient.className);this._gradient=new t,this._gradient?.parse(e.gradient)}if(e.animations){this.animations=[];for(let t=0;t-1&&this.linkWithMesh(null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}static get HORIZONTAL_ALIGNMENT_LEFT(){return BD._HORIZONTAL_ALIGNMENT_LEFT}static get HORIZONTAL_ALIGNMENT_RIGHT(){return BD._HORIZONTAL_ALIGNMENT_RIGHT}static get HORIZONTAL_ALIGNMENT_CENTER(){return BD._HORIZONTAL_ALIGNMENT_CENTER}static get VERTICAL_ALIGNMENT_TOP(){return BD._VERTICAL_ALIGNMENT_TOP}static get VERTICAL_ALIGNMENT_BOTTOM(){return BD._VERTICAL_ALIGNMENT_BOTTOM}static get VERTICAL_ALIGNMENT_CENTER(){return BD._VERTICAL_ALIGNMENT_CENTER}static _GetFontOffset(e){if(BD._FontHeightSizes[e])return BD._FontHeightSizes[e];const t=se.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");const i=t.getFontOffset(e);return BD._FontHeightSizes[e]=i,i}static Parse(e,t){const i=hs.Instantiate("BABYLON.GUI."+e.className),s=yt.Parse((()=>new i),e,null);return s.name=e.name,s._parseFromContent(e,t),s}static drawEllipse(e,t,i,s,r){r.translate(e,t),r.scale(i,s),r.beginPath(),r.arc(0,0,1,0,2*Math.PI),r.closePath(),r.scale(1/i,1/s),r.translate(-e,-t)}isReady(){return!0}}BD.AllowAlphaInheritance=!1,BD._ClipMeasure=new DD(0,0,0,0),BD._HORIZONTAL_ALIGNMENT_LEFT=0,BD._HORIZONTAL_ALIGNMENT_RIGHT=1,BD._HORIZONTAL_ALIGNMENT_CENTER=2,BD._VERTICAL_ALIGNMENT_TOP=0,BD._VERTICAL_ALIGNMENT_BOTTOM=1,BD._VERTICAL_ALIGNMENT_CENTER=2,BD._FontHeightSizes={},BD.AddHeader=()=>{},qe([st()],BD.prototype,"metadata",void 0),qe([st()],BD.prototype,"isHitTestVisible",void 0),qe([st()],BD.prototype,"isPointerBlocker",void 0),qe([st()],BD.prototype,"isFocusInvisible",void 0),qe([st()],BD.prototype,"clipChildren",null),qe([st()],BD.prototype,"clipContent",null),qe([st()],BD.prototype,"useBitmapCache",void 0),qe([st()],BD.prototype,"shadowOffsetX",null),qe([st()],BD.prototype,"shadowOffsetY",null),qe([st()],BD.prototype,"shadowBlur",null),qe([st()],BD.prototype,"shadowColor",null),qe([st()],BD.prototype,"hoverCursor",void 0),qe([st()],BD.prototype,"fontOffset",null),qe([st()],BD.prototype,"alpha",null),qe([st()],BD.prototype,"isSerializable",void 0),qe([st()],BD.prototype,"scaleX",null),qe([st()],BD.prototype,"scaleY",null),qe([st()],BD.prototype,"rotation",null),qe([st()],BD.prototype,"transformCenterY",null),qe([st()],BD.prototype,"transformCenterX",null),qe([st()],BD.prototype,"horizontalAlignment",null),qe([st()],BD.prototype,"verticalAlignment",null),qe([st()],BD.prototype,"fixedRatio",null),qe([st()],BD.prototype,"fixedRatioMasterIsWidth",null),qe([st()],BD.prototype,"width",null),qe([st()],BD.prototype,"height",null),qe([st()],BD.prototype,"style",null),qe([st()],BD.prototype,"color",null),qe([st()],BD.prototype,"gradient",null),qe([st()],BD.prototype,"zIndex",null),qe([st()],BD.prototype,"notRenderable",null),qe([st()],BD.prototype,"isVisible",null),qe([st()],BD.prototype,"descendantsOnlyPadding",null),qe([st()],BD.prototype,"paddingLeft",null),qe([st()],BD.prototype,"paddingRight",null),qe([st()],BD.prototype,"paddingTop",null),qe([st()],BD.prototype,"paddingBottom",null),qe([st()],BD.prototype,"left",null),qe([st()],BD.prototype,"top",null),qe([st()],BD.prototype,"linkOffsetX",null),qe([st()],BD.prototype,"linkOffsetY",null),qe([st()],BD.prototype,"isEnabled",null),qe([st()],BD.prototype,"disabledColor",null),qe([st()],BD.prototype,"disabledColorItem",null),qe([st()],BD.prototype,"overlapGroup",void 0),qe([st()],BD.prototype,"overlapDeltaMultiplier",void 0),ee("BABYLON.GUI.Control",BD);class LD extends BD{get renderToIntermediateTexture(){return this._renderToIntermediateTexture}set renderToIntermediateTexture(e){this._renderToIntermediateTexture!==e&&(this._renderToIntermediateTexture=e,this._markAsDirty())}get adaptHeightToChildren(){return this._adaptHeightToChildren}set adaptHeightToChildren(e){this._adaptHeightToChildren!==e&&(this._adaptHeightToChildren=e,e&&(this.height="100%"),this._markAsDirty())}get adaptWidthToChildren(){return this._adaptWidthToChildren}set adaptWidthToChildren(e){this._adaptWidthToChildren!==e&&(this._adaptWidthToChildren=e,e&&(this.width="100%"),this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get backgroundGradient(){return this._backgroundGradient}set backgroundGradient(e){this._backgroundGradient!==e&&(this._backgroundGradient=e,this._markAsDirty())}get children(){return this._children}get isReadOnly(){return this._isReadOnly}set isReadOnly(e){this._isReadOnly=e;for(const t of this._children)t.isReadOnly=e}constructor(e){super(e),this.name=e,this._children=new Array,this._measureForChildren=DD.Empty(),this._background="",this._backgroundGradient=null,this._adaptWidthToChildren=!1,this._adaptHeightToChildren=!1,this._renderToIntermediateTexture=!1,this._intermediateTexture=null,this.delegatePickingToChildren=!1,this.logLayoutCycleErrors=!1,this.maxLayoutCycle=3,this.onControlAddedObservable=new X,this.onControlRemovedObservable=new X,this._inverseTransformMatrix=ND.Identity(),this._inverseMeasure=new DD(0,0,0,0)}_getTypeName(){return"Container"}_flagDescendantsAsMatrixDirty(){for(const e of this.children)e._isClipped=!1,e._markMatrixAsDirty()}getChildByName(e){for(const t of this.children)if(t.name===e)return t;return null}getChildByType(e,t){for(const e of this.children)if(e.typeName===t)return e;return null}containsControl(e){return-1!==this.children.indexOf(e)}addControl(e){return e?(-1!==this._children.indexOf(e)||(e._link(this._host),e._markAllAsDirty(),this._reOrderControl(e),this._markAsDirty(),this.onControlAddedObservable.notifyObservers(e)),this):this}clearControls(){const e=this.children.slice();for(const t of e)this.removeControl(t);return this}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null),e.linkWithMesh(null),this._host&&this._host._cleanControlAfterRemoval(e),this._markAsDirty(),this.onControlRemovedObservable.notifyObservers(e),this}_reOrderControl(e){const t=e.linkedMesh;this.removeControl(e);let i=!1;for(let t=0;te.zIndex){this._children.splice(t,0,e),i=!0;break}i||this._children.push(e),e.parent=this,t&&e.linkWithMesh(t),this._markAsDirty()}_offsetLeft(e){super._offsetLeft(e);for(const t of this._children)t._offsetLeft(e)}_offsetTop(e){super._offsetTop(e);for(const t of this._children)t._offsetTop(e)}_markAllAsDirty(){super._markAllAsDirty();for(let e=0;e=0&&(s+=this.paddingLeftInPixels+this.paddingRightInPixels,this.width!==s+"px"&&(this.parent?._markAsDirty(),this.width=s+"px",this._width.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this.adaptHeightToChildren&&r>=0&&(r+=this.paddingTopInPixels+this.paddingBottomInPixels,this.height!==r+"px"&&(this.parent?._markAsDirty(),this.height=r+"px",this._height.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this._postMeasure()}i++}while(this._rebuildLayout&&i=3&&this.logLayoutCycleErrors&&we.Error(`Layout cycle detected in GUI (Container name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this._isDirty&&(this.invalidateRect(),this._isDirty=!1),!0}_postMeasure(){}_draw(e,t){const i=this._renderToIntermediateTexture&&this._intermediateTexture,s=i?this._intermediateTexture.getContext():e;i&&(s.save(),s.translate(-this._currentMeasure.left,-this._currentMeasure.top),t?(this._transformMatrix.invertToRef(this._inverseTransformMatrix),t.transformToRef(this._inverseTransformMatrix,this._inverseMeasure),s.clearRect(this._inverseMeasure.left,this._inverseMeasure.top,this._inverseMeasure.width,this._inverseMeasure.height)):s.clearRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._localDraw(s),e.save(),this.clipChildren&&this._clipForChildren(s);for(const e of this._children)t&&!e._intersectsRect(t)||e._render(s,t);i&&(s.restore(),e.save(),e.globalAlpha=this.alpha,e.drawImage(s.canvas,this._currentMeasure.left,this._currentMeasure.top),e.restore()),e.restore()}getDescendantsToRef(e,t=!1,i){if(this.children)for(let s=0;s=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}for(let l=this._children.length-1;l>=0;l--){const h=this._children[l];if(h._processPicking(e,t,i,s,r,n,o,a))return h.hoverCursor&&this._host._changeCursor(h.hoverCursor),!0}return!!l&&!!this.isHitTestVisible&&this._processObservables(s,e,t,i,r,n,o,a)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(this._currentMeasure)}_getAdaptDimTo(e){return"width"===e?this.adaptWidthToChildren:this.adaptHeightToChildren}isDimensionFullyDefined(e){if(this._getAdaptDimTo(e)){for(const t of this.children)if(!t.isDimensionFullyDefined(e))return!1;return!0}return super.isDimensionFullyDefined(e)}serialize(e,t=!1){if(super.serialize(e,t),(this.isSerializable||t)&&(this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient)),this.children.length)){e.children=[];for(const i of this.children)if(i.isSerializable||t){const t={};i.serialize(t),e.children.push(t)}}}dispose(){super.dispose();for(let e=this.children.length-1;e>=0;e--)this.children[e].dispose();this._intermediateTexture?.dispose()}_parseFromContent(e,t){if(super._parseFromContent(e,t),this._link(t),e.backgroundGradient){const t=hs.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this._backgroundGradient=new t,this._backgroundGradient?.parse(e.backgroundGradient)}if(e.children)for(const i of e.children)this.addControl(BD.Parse(i,t))}isReady(){for(const e of this.children)if(!e.isReady())return!1;return!0}}qe([st()],LD.prototype,"delegatePickingToChildren",void 0),qe([st()],LD.prototype,"renderToIntermediateTexture",null),qe([st()],LD.prototype,"maxLayoutCycle",void 0),qe([st()],LD.prototype,"adaptHeightToChildren",null),qe([st()],LD.prototype,"adaptWidthToChildren",null),qe([st()],LD.prototype,"background",null),qe([st()],LD.prototype,"backgroundGradient",null),ee("BABYLON.GUI.Container",LD);class kD extends LD{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get cornerRadius(){return this._cornerRadius[0]}set cornerRadius(e){e<0&&(e=0),this._cornerRadius[0]===e&&this._cornerRadius[1]===e&&this._cornerRadius[2]===e&&this._cornerRadius[3]===e||(this._cornerRadius[0]=this._cornerRadius[1]=this._cornerRadius[2]=this._cornerRadius[3]=e,this._markAsDirty())}get cornerRadiusX(){return this._cornerRadius[0]}set cornerRadiusX(e){this._cornerRadius[0]!==e&&(this._cornerRadius[0]=e)}get cornerRadiusY(){return this._cornerRadius[1]}set cornerRadiusY(e){this._cornerRadius[1]!==e&&(this._cornerRadius[1]=e)}get cornerRadiusZ(){return this._cornerRadius[2]}set cornerRadiusZ(e){this._cornerRadius[2]!==e&&(this._cornerRadius[2]=e)}get cornerRadiusW(){return this._cornerRadius[3]}set cornerRadiusW(e){this._cornerRadius[3]!==e&&(this._cornerRadius[3]=e)}constructor(e){super(e),this.name=e,this._thickness=1,this._cornerRadius=[0,0,0,0],this._cachedRadius=[0,0,0,0]}_getTypeName(){return"Rectangle"}_computeAdditionalOffsetX(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_computeAdditionalOffsetY(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_getRectangleFill(e){return this._getBackgroundColor(e)}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),(this._background||this._backgroundGradient)&&(e.fillStyle=this._getRectangleFill(e),0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.fill()):e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._thickness&&((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),(this.color||this.gradient)&&(e.strokeStyle=this.gradient?this.gradient.getCanvasGradient(e):this.color),e.lineWidth=this._thickness,0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.stroke()):e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness)),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_drawRoundedRect(e,t=0){const i=this._currentMeasure.left+t,s=this._currentMeasure.top+t,r=this._currentMeasure.width-2*t,n=this._currentMeasure.height-2*t;for(let e=0;ei&&(i=t.width)}if(this._resizeToFit){if(this._textWrapping===VD.Clip||this._forceResizeWidth){const e=Math.ceil(this._paddingLeftInPixels)+Math.ceil(this._paddingRightInPixels)+Math.ceil(i);e!==this._width.getValueInPixel(this._host,this._tempParentMeasure.width)&&(this._width.updateInPlace(e,PD.UNITMODE_PIXEL),this._rebuildLayout=!0)}let e=this._paddingTopInPixels+this._paddingBottomInPixels+this._fontOffset.height*this._lines.length|0;if(this._lines.length>0&&0!==this._lineSpacing.internalValue){let t=0;t=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),e+=(this._lines.length-1)*t}e!==this._height.internalValue&&(this._height.updateInPlace(e,PD.UNITMODE_PIXEL),this._rebuildLayout=!0)}}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=0;switch(this._textHorizontalAlignment){case BD.HORIZONTAL_ALIGNMENT_LEFT:n=0;break;case BD.HORIZONTAL_ALIGNMENT_RIGHT:n=r-t;break;case BD.HORIZONTAL_ALIGNMENT_CENTER:n=(r-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,this._currentMeasure.left+n,i),this._underline&&this._drawLine(this._currentMeasure.left+n,i+3,this._currentMeasure.left+n+t,i+3,s),this._lineThrough&&this._drawLine(this._currentMeasure.left+n,i-this.fontSizeInPixels/3,this._currentMeasure.left+n+t,i-this.fontSizeInPixels/3,s)}_drawLine(e,t,i,s,r){if(r.beginPath(),r.lineWidth=Math.round(.05*this.fontSizeInPixels),r.moveTo(e,t),r.lineTo(i,s),this.outlineWidth&&this.applyOutlineToUnderline)r.stroke(),r.fill();else{const e=r.strokeStyle;r.strokeStyle=r.fillStyle,r.stroke(),r.strokeStyle=e}r.closePath()}_draw(e){e.save(),this._applyStates(e),this._renderLines(e),e.restore()}_applyStates(e){super._applyStates(e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor,e.lineJoin="miter",e.miterLimit=2)}_breakLines(e,t,i){this._linesTemp.length=0;const s=this.text.split("\n");if(this._textWrapping===VD.Ellipsis)for(const t of s)this._linesTemp.push(this._parseLineEllipsis(t,e,i));else if(this._textWrapping===VD.WordWrap)for(const t of s)this._linesTemp.push(...this._parseLineWordWrap(t,e,i));else if(this._textWrapping===VD.WordWrapEllipsis)for(const r of s)this._linesTemp.push(...this._parseLineWordWrapEllipsis(r,e,t,i));else for(const e of s)this._linesTemp.push(this._parseLine(e,i));return this._linesTemp}_parseLine(e="",t){return{text:e,width:this._getTextMetricsWidth(t.measureText(e))}}_getCharsToRemove(e,t,i){const s=e>t?e-t:0,r=e/i;return Math.max(Math.floor(s/r),1)}_parseLineEllipsis(e="",t,i){let s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);const n=Array.from&&Array.from(e);if(n)for(;n.length&&s>t;)n.splice(n.length-r,r),e=`${n.join("")}…`,s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);else{for(;e.length>2&&s>t;)e=e.slice(0,-r),s=this._getTextMetricsWidth(i.measureText(e+"…")),r=this._getCharsToRemove(s,t,e.length);e+="…"}return{text:e,width:s}}_getTextMetricsWidth(e){return void 0!==e.actualBoundingBoxLeft?Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight):e.width}_parseLineWordWrap(e="",t,i){const s=[],r=this.wordSplittingFunction?this.wordSplittingFunction(e):e.split(this._wordDivider);let n=this._getTextMetricsWidth(i.measureText(e));for(let o=0;o0?e+this._wordDivider+r[o]:r[0],l=this._getTextMetricsWidth(i.measureText(a));l>t&&o>0?(s.push({text:e,width:n}),e=r[o],n=this._getTextMetricsWidth(i.measureText(e))):(n=l,e=a)}return s.push({text:e,width:n}),s}_parseLineWordWrapEllipsis(e="",t,i,s){const r=this._parseLineWordWrap(e,t,s);for(let e=1;e<=r.length;e++)if(this._computeHeightForLinesOf(e)>i&&e>1){const i=r[e-2],n=r[e-1];r[e-2]=this._parseLineEllipsis(i.text+this._wordDivider+n.text,t,s);const o=r.length-e+1;for(let e=0;e0&&0!==this._lineSpacing.internalValue){let i=0;i=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),t+=(e-1)*i}return t}isDimensionFullyDefined(e){return!!this.resizeToFit||super.isDimensionFullyDefined(e)}computeExpectedHeight(){if(this.text&&this.widthInPixels){const e=se.LastCreatedEngine?.createCanvas(0,0).getContext("2d");if(e){this._applyStates(e),this._fontOffset||(this._fontOffset=BD._GetFontOffset(e.font));const t=this._lines?this._lines:this._breakLines(this.widthInPixels-this._paddingLeftInPixels-this._paddingRightInPixels,this.heightInPixels-this._paddingTopInPixels-this._paddingBottomInPixels,e);return this._computeHeightForLinesOf(t.length)}}return 0}dispose(){super.dispose(),this.onTextChangedObservable.clear()}}qe([st()],UD.prototype,"resizeToFit",null),qe([st()],UD.prototype,"textWrapping",null),qe([st()],UD.prototype,"text",null),qe([st()],UD.prototype,"textHorizontalAlignment",null),qe([st()],UD.prototype,"textVerticalAlignment",null),qe([st()],UD.prototype,"lineSpacing",null),qe([st()],UD.prototype,"outlineWidth",null),qe([st()],UD.prototype,"underline",null),qe([st()],UD.prototype,"lineThrough",null),qe([st()],UD.prototype,"applyOutlineToUnderline",null),qe([st()],UD.prototype,"outlineColor",null),qe([st()],UD.prototype,"wordDivider",null),qe([st()],UD.prototype,"forceResizeWidth",null),ee("BABYLON.GUI.TextBlock",UD);class GD extends BD{get isLoaded(){return this._loaded}isReady(){return this.isLoaded}get detectPointerOnOpaqueOnly(){return this._detectPointerOnOpaqueOnly}set detectPointerOnOpaqueOnly(e){this._detectPointerOnOpaqueOnly!==e&&(this._detectPointerOnOpaqueOnly=e)}get sliceLeft(){return this._sliceLeft}set sliceLeft(e){this._sliceLeft!==e&&(this._sliceLeft=e,this._markAsDirty())}get sliceRight(){return this._sliceRight}set sliceRight(e){this._sliceRight!==e&&(this._sliceRight=e,this._markAsDirty())}get sliceTop(){return this._sliceTop}set sliceTop(e){this._sliceTop!==e&&(this._sliceTop=e,this._markAsDirty())}get sliceBottom(){return this._sliceBottom}set sliceBottom(e){this._sliceBottom!==e&&(this._sliceBottom=e,this._markAsDirty())}get sourceLeft(){return this._sourceLeft}set sourceLeft(e){this._sourceLeft!==e&&(this._sourceLeft=e,this._markAsDirty())}get sourceTop(){return this._sourceTop}set sourceTop(e){this._sourceTop!==e&&(this._sourceTop=e,this._markAsDirty())}get sourceWidth(){return this._sourceWidth}set sourceWidth(e){this._sourceWidth!==e&&(this._sourceWidth=e,this._markAsDirty())}get sourceHeight(){return this._sourceHeight}set sourceHeight(e){this._sourceHeight!==e&&(this._sourceHeight=e,this._markAsDirty())}get imageWidth(){return this._imageWidth}get imageHeight(){return this._imageHeight}get populateNinePatchSlicesFromImage(){return this._populateNinePatchSlicesFromImage}set populateNinePatchSlicesFromImage(e){this._populateNinePatchSlicesFromImage!==e&&(this._populateNinePatchSlicesFromImage=e,this._populateNinePatchSlicesFromImage&&this._loaded&&this._extractNinePatchSliceDataFromImage())}get isSVG(){return this._isSVG}get svgAttributesComputationCompleted(){return this._svgAttributesComputationCompleted}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale!==e&&(this._autoScale=e,e&&this._loaded&&this.synchronizeSizeWithContent())}get stretch(){return this._stretch}set stretch(e){this._stretch!==e&&(this._stretch=e,this._markAsDirty())}_rotate90(e,t=!1){const i=this._domImage.width,s=this._domImage.height,r=this._host?.getScene()?.getEngine()||se.LastCreatedEngine;if(!r)throw new Error("Invalid engine. Unable to create a canvas.");const n=r.createCanvas(s,i),o=n.getContext("2d");o.translate(n.width/2,n.height/2),o.rotate(e*Math.PI/2),o.drawImage(this._domImage,0,0,i,s,-i/2,-s/2,i,s);const a=n.toDataURL("image/jpg"),l=new GD(this.name+"rotated",a);return t&&(l._stretch=this._stretch,l._autoScale=this._autoScale,l._cellId=this._cellId,l._cellWidth=e%1?this._cellHeight:this._cellWidth,l._cellHeight=e%1?this._cellWidth:this._cellHeight),this._handleRotationForSVGImage(this,l,e),this._imageDataCache.data=null,l}_handleRotationForSVGImage(e,t,i){e._isSVG&&(e._svgAttributesComputationCompleted?(this._rotate90SourceProperties(e,t,i),this._markAsDirty()):e.onSVGAttributesComputedObservable.addOnce((()=>{this._rotate90SourceProperties(e,t,i),this._markAsDirty()})))}_rotate90SourceProperties(e,t,i){let s=e.sourceLeft,r=e.sourceTop,n=e.domImage.width,o=e.domImage.height,a=s,l=r,h=e.sourceWidth,c=e.sourceHeight;if(0!=i){const e=i<0?-1:1;i%=4;for(let t=0;t127&&-1===this._sliceLeft)this._sliceLeft=t;else if(e<127&&this._sliceLeft>-1){this._sliceRight=t;break}}this._sliceTop=-1,this._sliceBottom=-1;for(let i=0;i127&&-1===this._sliceTop)this._sliceTop=i;else if(t<127&&this._sliceTop>-1){this._sliceBottom=i;break}}}set domImage(e){this._domImage=e,this._loaded=!1,this._imageDataCache.data=null,this._domImage.width?this._onImageLoaded():this._domImage.onload=()=>{this._onImageLoaded()}}get domImage(){return this._domImage}_onImageLoaded(){this._imageDataCache.data=null,this._imageWidth=this._domImage.width,this._imageHeight=this._domImage.height,this._loaded=!0,this._populateNinePatchSlicesFromImage&&this._extractNinePatchSliceDataFromImage(),this._autoScale&&this.synchronizeSizeWithContent(),this.onImageLoadedObservable.notifyObservers(this),this._markAsDirty()}get source(){return this._source}static ResetImageCache(){GD.SourceImgCache.clear()}_removeCacheUsage(e){const t=e&&GD.SourceImgCache.get(e);t&&(t.timesUsed-=1,0===t.timesUsed&&GD.SourceImgCache.delete(e))}set source(e){if(this._source===e)return;this._removeCacheUsage(this._source),this._loaded=!1,this._source=e,this._imageDataCache.data=null,e&&(e=this._svgCheck(e));const t=this._host?.getScene()?.getEngine()||se.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");if(e&&GD.SourceImgCache.has(e)){const t=GD.SourceImgCache.get(e);return this._domImage=t.img,t.timesUsed+=1,void(t.loaded?this._onImageLoaded():t.waitingForLoadCallback.push(this._onImageLoaded.bind(this)))}this._domImage=t.createCanvasImage(),e&&GD.SourceImgCache.set(e,{img:this._domImage,timesUsed:1,loaded:!1,waitingForLoadCallback:[this._onImageLoaded.bind(this)]}),this._domImage.onload=()=>{if(e){const t=GD.SourceImgCache.get(e);if(t){t.loaded=!0;for(const e of t.waitingForLoadCallback)e();return void(t.waitingForLoadCallback.length=0)}}this._onImageLoaded()},e&&(hs.SetCorsBehavior(e,this._domImage),hs.SetReferrerPolicyBehavior(this.referrerPolicy,this._domImage),this._domImage.src=e)}_svgCheck(e){if(window.SVGSVGElement&&-1!==e.search(/.svg#/gi)&&e.indexOf("#")===e.lastIndexOf("#")){this._isSVG=!0;const t=e.split("#")[0],i=e.split("#")[1],s=document.body.querySelector('object[data="'+t+'"]');if(s){const t=s.contentDocument;if(t&&t.documentElement){const r=t.documentElement.getAttribute("viewBox"),n=Number(t.documentElement.getAttribute("width")),o=Number(t.documentElement.getAttribute("height"));if(t.getElementById(i)&&r&&n&&o)return this._getSVGAttribs(s,i),e}s.addEventListener("load",(()=>{this._getSVGAttribs(s,i)}))}else{const e=document.createElement("object");e.data=t,e.type="image/svg+xml",e.width="0%",e.height="0%",document.body.appendChild(e),e.onload=()=>{const e=document.body.querySelector('object[data="'+t+'"]');e&&this._getSVGAttribs(e,i)}}return t}return e}_getSVGAttribs(e,t){const i=e.contentDocument;if(i&&i.documentElement){const e=i.documentElement.getAttribute("viewBox"),s=Number(i.documentElement.getAttribute("width")),r=Number(i.documentElement.getAttribute("height")),n=i.getElementById(t);if(e&&s&&r&&n){const t=Number(e.split(" ")[2]),i=Number(e.split(" ")[3]),o=n.getBBox();let a=1,l=1,h=0,c=0;const u=n.transform.baseVal.consolidate().matrix;n.transform&&n.transform.baseVal.consolidate()&&(a=u.a,l=u.d,h=u.e,c=u.f),this.sourceLeft=(a*o.x+h)*s/t,this.sourceTop=(l*o.y+c)*r/i,this.sourceWidth=o.width*a*(s/t),this.sourceHeight=o.height*l*(r/i),this._svgAttributesComputationCompleted=!0,this.onSVGAttributesComputedObservable.notifyObservers(this)}}}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth!==e&&(this._cellWidth=e,this._markAsDirty())}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight!==e&&(this._cellHeight=e,this._markAsDirty())}get cellId(){return this._cellId}set cellId(e){this._cellId!==e&&(this._cellId=e,this._markAsDirty())}constructor(e,t=null){super(e),this.name=e,this._workingCanvas=null,this._loaded=!1,this._stretch=GD.STRETCH_FILL,this._autoScale=!1,this._sourceLeft=0,this._sourceTop=0,this._sourceWidth=0,this._sourceHeight=0,this._svgAttributesComputationCompleted=!1,this._isSVG=!1,this._cellWidth=0,this._cellHeight=0,this._cellId=-1,this._populateNinePatchSlicesFromImage=!1,this._imageDataCache={data:null,key:""},this.onImageLoadedObservable=new X,this.onSVGAttributesComputedObservable=new X,this.source=t}contains(e,t){if(!super.contains(e,t))return!1;if(!this._detectPointerOnOpaqueOnly||!this._workingCanvas)return!0;const i=0|this._currentMeasure.width,s=0|this._currentMeasure.height,r=i+"_"+s;let n=this._imageDataCache.data;if(!n||this._imageDataCache.key!==r){const e=this._workingCanvas.getContext("2d");this._imageDataCache.data=n=e.getImageData(0,0,i,s).data,this._imageDataCache.key=r}return n[4*((e=e-this._currentMeasure.left|0)+(t=t-this._currentMeasure.top|0)*i)+3]>0}_getTypeName(){return"Image"}synchronizeSizeWithContent(){this._loaded&&(this.width=this._domImage.width+"px",this.height=this._domImage.height+"px")}_processMeasures(e,t){if(this._loaded)switch(this._stretch){case GD.STRETCH_NONE:case GD.STRETCH_FILL:case GD.STRETCH_UNIFORM:case GD.STRETCH_NINE_PATCH:break;case GD.STRETCH_EXTEND:this._autoScale&&this.synchronizeSizeWithContent(),this.parent&&this.parent.parent&&(this.parent.adaptWidthToChildren=!0,this.parent.adaptHeightToChildren=!0)}super._processMeasures(e,t)}_prepareWorkingCanvasForOpaqueDetection(){if(!this._detectPointerOnOpaqueOnly)return;const e=this._currentMeasure.width,t=this._currentMeasure.height;if(!this._workingCanvas){const i=this._host?.getScene()?.getEngine()||se.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");this._workingCanvas=i.createCanvas(e,t)}this._workingCanvas.getContext("2d").clearRect(0,0,e,t)}_drawImage(e,t,i,s,r,n,o,a,l){if(e.drawImage(this._domImage,t,i,s,r,n,o,a,l),!this._detectPointerOnOpaqueOnly)return;const h=e.getTransform(),c=this._workingCanvas.getContext("2d");c.save();const u=n-this._currentMeasure.left,d=o-this._currentMeasure.top;c.setTransform(h.a,h.b,h.c,h.d,(u+a)/2,(d+l)/2),c.translate(-(u+a)/2,-(d+l)/2),c.drawImage(this._domImage,t,i,s,r,u,d,a,l),c.restore()}_draw(e){let t,i,s,r;if(e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),-1==this.cellId)t=this._sourceLeft,i=this._sourceTop,s=this._sourceWidth?this._sourceWidth:this._imageWidth,r=this._sourceHeight?this._sourceHeight:this._imageHeight;else{const e=this._domImage.naturalWidth/this.cellWidth,n=this.cellId/e|0,o=this.cellId%e;t=this.cellWidth*o,i=this.cellHeight*n,s=this.cellWidth,r=this.cellHeight}if(this._prepareWorkingCanvasForOpaqueDetection(),this._applyStates(e),this._loaded)switch(this._stretch){case GD.STRETCH_NONE:case GD.STRETCH_FILL:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case GD.STRETCH_UNIFORM:{const n=this._currentMeasure.width/s,o=this._currentMeasure.height/r,a=Math.min(n,o),l=(this._currentMeasure.width-s*a)/2,h=(this._currentMeasure.height-r*a)/2;this._drawImage(e,t,i,s,r,this._currentMeasure.left+l,this._currentMeasure.top+h,s*a,r*a);break}case GD.STRETCH_EXTEND:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case GD.STRETCH_NINE_PATCH:this._renderNinePatch(e,t,i,s,r)}e.restore()}_renderNinePatch(e,t,i,s,r){const n=this._sliceLeft,o=this._sliceTop,a=r-this._sliceBottom,l=s-this._sliceRight,h=this._sliceRight-this._sliceLeft,c=this._sliceBottom-this._sliceTop,u=this._currentMeasure.width-l-n+2,d=this._currentMeasure.height-a-o+2,_=this._currentMeasure.left+n-1,p=this._currentMeasure.top+o-1,f=this._currentMeasure.left+this._currentMeasure.width-l,m=this._currentMeasure.top+this._currentMeasure.height-a;this._drawImage(e,t,i,n,o,this._currentMeasure.left,this._currentMeasure.top,n,o),this._drawImage(e,t+this._sliceLeft,i,h,o,_+1,this._currentMeasure.top,u-2,o),this._drawImage(e,t+this._sliceRight,i,l,o,f,this._currentMeasure.top,l,o),this._drawImage(e,t,i+this._sliceTop,n,c,this._currentMeasure.left,p+1,n,d-2),this._drawImage(e,t+this._sliceLeft,i+this._sliceTop,h,c,_,p,u,d),this._drawImage(e,t+this._sliceRight,i+this._sliceTop,l,c,f,p+1,l,d-2),this._drawImage(e,t,i+this._sliceBottom,n,a,this._currentMeasure.left,m,n,a),this._drawImage(e,t+this.sliceLeft,i+this._sliceBottom,h,a,_+1,m,u-2,a),this._drawImage(e,t+this._sliceRight,i+this._sliceBottom,l,a,f,m,l,a)}dispose(){super.dispose(),this.onImageLoadedObservable.clear(),this.onSVGAttributesComputedObservable.clear(),this._removeCacheUsage(this._source)}}GD.SourceImgCache=new Map,GD.STRETCH_NONE=0,GD.STRETCH_FILL=1,GD.STRETCH_UNIFORM=2,GD.STRETCH_EXTEND=3,GD.STRETCH_NINE_PATCH=4,qe([st()],GD.prototype,"detectPointerOnOpaqueOnly",null),qe([st()],GD.prototype,"sliceLeft",null),qe([st()],GD.prototype,"sliceRight",null),qe([st()],GD.prototype,"sliceTop",null),qe([st()],GD.prototype,"sliceBottom",null),qe([st()],GD.prototype,"sourceLeft",null),qe([st()],GD.prototype,"sourceTop",null),qe([st()],GD.prototype,"sourceWidth",null),qe([st()],GD.prototype,"sourceHeight",null),qe([st()],GD.prototype,"populateNinePatchSlicesFromImage",null),qe([st()],GD.prototype,"autoScale",null),qe([st()],GD.prototype,"stretch",null),qe([st()],GD.prototype,"source",null),qe([st()],GD.prototype,"cellWidth",null),qe([st()],GD.prototype,"cellHeight",null),qe([st()],GD.prototype,"cellId",null),ee("BABYLON.GUI.Image",GD);class zD extends kD{get image(){return this._image}get textBlock(){return this._textBlock}constructor(e){super(e),this.name=e,this.thickness=1,this.isPointerBlocker=!0;let t=null;this.pointerEnterAnimation=()=>{t=this.alpha,this.alpha-=.1},this.pointerOutAnimation=()=>{null!==t&&(this.alpha=t)},this.pointerDownAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"Button"}_processPicking(e,t,i,s,r,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(s,e,t,i,r,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(!this.isReadOnly&&this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)}_onPointerOut(e,t,i=!1){!this.isReadOnly&&this.pointerOutAnimation&&this.pointerOutAnimation(),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(!this.isReadOnly&&this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_getRectangleFill(e){return this.isEnabled?this._getBackgroundColor(e):this._disabledColor}_onPointerUp(e,t,i,s,r,n){!this.isReadOnly&&this.pointerUpAnimation&&this.pointerUpAnimation(),super._onPointerUp(e,t,i,s,r,n)}serialize(e,t){super.serialize(e,t),(this.isSerializable||t)&&(this._textBlock&&(e.textBlockName=this._textBlock.name),this._image&&(e.imageName=this._image.name))}_parseFromContent(e,t){super._parseFromContent(e,t),e.textBlockName&&(this._textBlock=this.getChildByName(e.textBlockName)),e.imageName&&(this._image=this.getChildByName(e.imageName))}static CreateImageButton(e,t,i){const s=new this(e),r=new UD(e+"_button",t);r.textWrapping=!0,r.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,r.paddingLeft="20%",s.addControl(r);const n=new GD(e+"_icon",i);return n.width="20%",n.stretch=GD.STRETCH_UNIFORM,n.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,s.addControl(n),s._image=n,s._textBlock=r,s}static CreateImageOnlyButton(e,t){const i=new this(e),s=new GD(e+"_icon",t);return s.stretch=GD.STRETCH_FILL,s.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,i.addControl(s),i._image=s,i}static CreateSimpleButton(e,t){const i=new this(e),s=new UD(e+"_button",t);return s.textWrapping=!0,s.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,i.addControl(s),i._textBlock=s,i}static CreateImageWithCenterTextButton(e,t,i){const s=new this(e),r=new GD(e+"_icon",i);r.stretch=GD.STRETCH_FILL,s.addControl(r);const n=new UD(e+"_button",t);return n.textWrapping=!0,n.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,s.addControl(n),s._image=r,s._textBlock=n,s}}ee("BABYLON.GUI.Button",zD);class WD extends LD{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get spacing(){return this._spacing}set spacing(e){this._spacing!==e&&(this._spacing=e,this._markAsDirty())}set width(e){this._doNotTrackManualChanges||(this._manualWidth=!0),this._width.toString(this._host)!==e&&this._width.fromString(e)&&this._markAsDirty()}get width(){return this._width.toString(this._host)}set height(e){this._doNotTrackManualChanges||(this._manualHeight=!0),this._height.toString(this._host)!==e&&this._height.fromString(e)&&this._markAsDirty()}get height(){return this._height.toString(this._host)}constructor(e){super(e),this.name=e,this._isVertical=!0,this._manualWidth=!1,this._manualHeight=!1,this._doNotTrackManualChanges=!1,this._spacing=0,this.ignoreLayoutWarnings=!1}_getTypeName(){return"StackPanel"}_preMeasure(e,t){for(const e of this._children)this._isVertical?e.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP:e.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT;super._preMeasure(e,t)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(e),this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this.isVertical&&!this._manualWidth||(this._measureForChildren.width=this._currentMeasure.width),(this.isVertical||this._manualHeight)&&(this._measureForChildren.height=this._currentMeasure.height)}_postMeasure(){let e=0,t=0;const i=this._children.length;for(let s=0;s=0?Math.min(e,this._characters.length):this._characters.length+Math.max(e,-this._characters.length),void 0===t?t=this._characters.length-e:(isNaN(t)||t<0)&&(t=0);const i=[];for(;--t>=0;)i[t]=this._characters[e+t];return i.join("")}return this._text.substr(e,t)}substring(e,t){if(this._characters){isNaN(e)?e=0:e>this._characters.length?e=this._characters.length:e<0&&(e=0),void 0===t?t=this._characters.length:isNaN(t)?t=0:t>this._characters.length?t=this._characters.length:t<0&&(t=0);const i=[];let s=0;for(;e{switch(e.type){case qf.COPY:this._onCopyText(e.event),this.onTextCopyObservable.notifyObservers(this);break;case qf.CUT:this._onCutText(e.event),this.onTextCutObservable.notifyObservers(this);break;case qf.PASTE:this._onPasteText(e.event),this.onTextPasteObservable.notifyObservers(this);break;default:return}}));const e=this._host.getScene();e&&(this._onPointerDblTapObserver=e.onPointerObservable.add((e=>{this._isFocused&&e.type===Ms.POINTERDOUBLETAP&&this._processDblClick(e)}))),this._onFocusSelectAll&&this._selectAllText()}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}_getTypeName(){return"InputText"}keepsFocusWith(){return this._connectedVirtualKeyboard?[this._connectedVirtualKeyboard]:null}processKey(e,t,i){if(!this.isReadOnly&&(!i||!i.ctrlKey&&!i.metaKey||67!==e&&86!==e&&88!==e)){if(i&&(i.ctrlKey||i.metaKey)&&65===e)return this._selectAllText(),void i.preventDefault();switch(e){case 32:t=" ";break;case 191:i&&i.preventDefault();break;case 8:if(this._textWrapper.text&&this._textWrapper.length>0){if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this._blinkIsEven=!1,void(i&&i.preventDefault());if(0===this._cursorOffset)this.text=this._textWrapper.substr(0,this._textWrapper.length-1);else{const e=this._textWrapper.length-this._cursorOffset;e>0&&(this._textWrapper.removePart(e-1,e),this._textHasChanged())}}return void(i&&i.preventDefault());case 46:if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,void(i&&i.preventDefault());if(this._textWrapper.text&&this._textWrapper.length>0&&this._cursorOffset>0){const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e+1),this._textHasChanged(),this._cursorOffset--}return void(i&&i.preventDefault());case 13:return this._host.focusedControl=null,void(this.isTextHighlightOn=!1);case 35:return this._cursorOffset=0,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 36:return this._cursorOffset=this._textWrapper.length,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 37:if(this._cursorOffset++,this._cursorOffset>this._textWrapper.length&&(this._cursorOffset=this._textWrapper.length),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(this._textWrapper.length===this._cursorOffset)return;this._endHighlightIndex=this._textWrapper.length-this._cursorOffset+1}return this._startHighlightIndex=0,this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=this._textWrapper.length,this.isTextHighlightOn=!0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=0===this._startHighlightIndex?this._textWrapper.length:this._textWrapper.length-this._startHighlightIndex+1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset>=this._textWrapper.length?this._textWrapper.length:this._cursorOffset-1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=this._textWrapper.length,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty();case 39:if(this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(0===this._cursorOffset)return;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset-1}return this._endHighlightIndex=this._textWrapper.length,this.isTextHighlightOn=!0,this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=this._textWrapper.length===this._endHighlightIndex?0:this._textWrapper.length-this._endHighlightIndex-1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset<=0?0:this._cursorOffset+1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._endHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=0,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty()}if(32===e&&(t=i?.key??" "),this._deadKey="Dead"===t,t&&(-1===e||32===e||34===e||39===e||e>47&&e<64||e>64&&e<91||e>159&&e<193||e>218&&e<223||e>95&&e<112)&&(this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&!this._deadKey))if(this.isTextHighlightOn)this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex,t),this._textHasChanged(),this._cursorOffset=this._textWrapper.length-(this._startHighlightIndex+1),this.isTextHighlightOn=!1,this._blinkIsEven=!1,this._markAsDirty();else if(0===this._cursorOffset)this.text+=this._deadKey&&i?.key?i.key:t;else{const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e,t),this._textHasChanged()}}}_updateValueFromCursorIndex(e){if(this._blinkIsEven=!1,-1===this._cursorIndex)this._cursorIndex=e;else if(this._cursorIndexthis._cursorOffset))return this.isTextHighlightOn=!1,void this._markAsDirty();this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex}this.isTextHighlightOn=!0,this._markAsDirty()}_processDblClick(e){let t,i;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset,this._endHighlightIndex=this._startHighlightIndex;do{i=this._endHighlightIndex0&&this._textWrapper.isWord(this._startHighlightIndex-1)?--this._startHighlightIndex:0}while(t||i);this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!0,this._clickedCoordinate=null,this._blinkIsEven=!0,this._cursorIndex=-1,this._markAsDirty()}_selectAllText(){this._blinkIsEven=!0,this.isTextHighlightOn=!0,this._startHighlightIndex=0,this._endHighlightIndex=this._textWrapper.length,this._cursorOffset=this._textWrapper.length,this._cursorIndex=-1,this._markAsDirty()}processKeyboard(e){this.processKey(e.keyCode,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e)}_onCopyText(e){this.isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._highlightedText=""}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData;const i=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(i,i,t),this._textHasChanged()}_draw(e){e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._fontOffset&&!this._wasDirty||(this._fontOffset=BD._GetFontOffset(e.font));const t=this._currentMeasure.left+this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this.color&&(e.fillStyle=this.color);let i=this._beforeRenderText(this._textWrapper);this._isFocused||this._textWrapper.text||!this._placeholderText||(i=new XD,i.text=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(i.text).width;const s=2*this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,this._tempParentMeasure.width),this._textWidth+s)+"px",this._autoStretchWidth=!0);const r=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,n=this._width.getValueInPixel(this._host,this._tempParentMeasure.width)-s;if(e.save(),e.beginPath(),e.rect(t,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,n+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>n){const e=t-this._textWidth+n;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=t;if(this.outlineWidth&&e.strokeText(i.text,this._scrollLeft,this._currentMeasure.top+r),e.fillText(i.text,this._scrollLeft,this._currentMeasure.top+r),this._isFocused){if(this._clickedCoordinate){const t=this._scrollLeft+this._textWidth-this._clickedCoordinate;let s=0;this._cursorOffset=0;let r=0;do{this._cursorOffset&&(r=Math.abs(t-s)),this._cursorOffset++,s=e.measureText(i.substr(i.length-this._cursorOffset,this._cursorOffset)).width}while(s=this._cursorOffset);Math.abs(t-s)>r&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){const s=i.substr(i.length-this._cursorOffset),r=e.measureText(s).width;let o=this._scrollLeft+this._textWidth-r;ot+n&&(this._scrollLeft+=t+n-o,o=t+n,this._markAsDirty()),this.isTextHighlightOn||e.fillRect(o,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}if(clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500),this.isTextHighlightOn){clearTimeout(this._blinkTimeout);const s=e.measureText(i.substring(this._startHighlightIndex)).width;let r=this._scrollLeft+this._textWidth-s;this._highlightedText=i.substring(this._startHighlightIndex,this._endHighlightIndex);let n=e.measureText(i.substring(this._startHighlightIndex,this._endHighlightIndex)).width;r=this._rowDefinitions.length?null:this._rowDefinitions[e]}getColumnDefinition(e){return e<0||e>=this._columnDefinitions.length?null:this._columnDefinitions[e]}addRowDefinition(e,t=!1){return this._rowDefinitions.push(new PD(e,t?PD.UNITMODE_PIXEL:PD.UNITMODE_PERCENTAGE)),this._rowDefinitionObservers.push(this._rowDefinitions[this.rowCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}addColumnDefinition(e,t=!1){return this._columnDefinitions.push(new PD(e,t?PD.UNITMODE_PIXEL:PD.UNITMODE_PERCENTAGE)),this._columnDefinitionObservers.push(this._columnDefinitions[this.columnCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}setRowDefinition(e,t,i=!1){if(e<0||e>=this._rowDefinitions.length)return this;const s=this._rowDefinitions[e];return s&&s.isPixel===i&&s.value===t||(this._rowDefinitions[e].onChangedObservable.remove(this._rowDefinitionObservers[e]),this._rowDefinitions[e]=new PD(t,i?PD.UNITMODE_PIXEL:PD.UNITMODE_PERCENTAGE),this._rowDefinitionObservers[e]=this._rowDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}setColumnDefinition(e,t,i=!1){if(e<0||e>=this._columnDefinitions.length)return this;const s=this._columnDefinitions[e];return s&&s.isPixel===i&&s.value===t||(this._columnDefinitions[e].onChangedObservable.remove(this._columnDefinitionObservers[e]),this._columnDefinitions[e]=new PD(t,i?PD.UNITMODE_PIXEL:PD.UNITMODE_PERCENTAGE),this._columnDefinitionObservers[e]=this._columnDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}getChildrenAt(e,t){const i=this._cells[`${e}:${t}`];return i?i.children:null}getChildCellInfo(e){return e._tag}_removeCell(e,t){if(e){super.removeControl(e);for(const t of e.children){const e=this._childControls.indexOf(t);-1!==e&&this._childControls.splice(e,1)}delete this._cells[t]}}_offsetCell(e,t){if(this._cells[t]){this._cells[e]=this._cells[t];for(const t of this._cells[e].children)t._tag=e;delete this._cells[t]}}removeColumnDefinition(e){if(e<0||e>=this._columnDefinitions.length)return this;for(let t=0;t=this._rowDefinitions.length)return this;for(let t=0;t{for(const r in this._cells){if(!Object.prototype.hasOwnProperty.call(this._cells,r))continue;const n=r.split(":"),o=parseInt(n[0]),a=parseInt(n[1]),l=this._cells[r];l.leftInPixels=e[a],l.topInPixels=t[o],l.widthInPixels=i[a],l.heightInPixels=s[o],l._left.ignoreAdaptiveScaling=!0,l._top.ignoreAdaptiveScaling=!0,l._width.ignoreAdaptiveScaling=!0,l._height.ignoreAdaptiveScaling=!0}})),super._additionalProcessing(e,t)}_flagDescendantsAsMatrixDirty(){for(const e in this._cells)Object.prototype.hasOwnProperty.call(this._cells,e)&&this._cells[e]._markMatrixAsDirty()}_renderHighlightSpecific(e){super._renderHighlightSpecific(e),this._getGridDefinitions(((t,i,s,r)=>{for(let i=0;i{e.tags.push(t._tag)}))}}_parseFromContent(e,t){super._parseFromContent(e,t);const i=[];this.children.forEach((e=>{i.push(e)})),this.removeRowDefinition(0),this.removeColumnDefinition(0);for(let t=0;t=1-jD._Epsilon&&(this._value.r=1),this._value.g>=1-jD._Epsilon&&(this._value.g=1),this._value.b>=1-jD._Epsilon&&(this._value.b=1),this.onValueChangedObservable.notifyObservers(this._value))}get width(){return this._width.toString(this._host)}set width(e){this._width.toString(this._host)!==e&&this._width.fromString(e)&&(0===this._width.getValue(this._host)&&(e="1px",this._width.fromString(e)),this._height.fromString(e),this._markAsDirty())}get height(){return this._height.toString(this._host)}set height(e){this._height.toString(this._host)!==e&&this._height.fromString(e)&&(0===this._height.getValue(this._host)&&(e="1px",this._height.fromString(e)),this._width.fromString(e),this._markAsDirty())}get size(){return this.width}set size(e){this.width=e}constructor(e){super(e),this.name=e,this._value=Ce.Red(),this._tmpColor=new Ce,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._squareLeft=0,this._squareTop=0,this._squareSize=0,this._h=360,this._s=1,this._v=1,this._lastPointerDownId=-1,this.onValueChangedObservable=new X,this._pointerIsDown=!1,this.value=new Ce(.88,.1,.1),this.size="200px",this.isPointerBlocker=!0}_getTypeName(){return"ColorPicker"}_preMeasure(e){e.widthl||sg?f:(f-p)*(e-m)/(g-m)+p,d=(r-h)/(e-h),o[u+3]=d<_?d/_*255:d>1-_?255*(1-(d-(1-_))/_):255}return r.putImageData(n,0,0),s}_draw(e){e.save(),this._applyStates(e);const t=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),i=.2*t,s=this._currentMeasure.left,r=this._currentMeasure.top;this._colorWheelCanvas&&this._colorWheelCanvas.width==2*t||(this._colorWheelCanvas=this._createColorWheelCanvas(t,i)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,s,r),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);let n=this._squareLeft+this._squareSize*this._s,o=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(n,o,.04*t,e);const a=t-.5*i;n=s+t+Math.cos((this._h-180)*Math.PI/180)*a,o=r+t+Math.sin((this._h-180)*Math.PI/180)*a,this._drawCircle(n,o,.35*i,e),e.restore()}_updateValueFromPointer(e,t){if(this._pointerStartedOnWheel){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),s=i+this._currentMeasure.left,r=i+this._currentMeasure.top;this._h=180*Math.atan2(t-r,e-s)/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(e-this._squareLeft)/this._squareSize,this._v=1-(t-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,jD._Epsilon),this._v=Math.min(this._v,1),this._v=Math.max(this._v,jD._Epsilon));Ce.HSVtoRGBToRef(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor}_isPointOnSquare(e,t){this._updateSquareProps();const i=this._squareLeft,s=this._squareTop,r=this._squareSize;return e>=i&&e<=i+r&&t>=s&&t<=s+r}_isPointOnWheel(e,t){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),s=i-.2*i,r=e-(i+this._currentMeasure.left),n=t-(i+this._currentMeasure.top),o=r*r+n*n;return o<=i*i&&o>=s*s}_onPointerDown(e,t,i,s,r){if(!super._onPointerDown(e,t,i,s,r))return!1;if(this.isReadOnly)return!0;this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const n=this._transformedPosition.x,o=this._transformedPosition.y;return this._isPointOnSquare(n,o)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(n,o)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(n,o),this._host._capturingControl[i]=this,this._lastPointerDownId=i,!0}_onPointerMove(e,t,i,s){if(i==this._lastPointerDownId){if(!this.isReadOnly){this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const e=this._transformedPosition.x,i=this._transformedPosition.y;this._pointerIsDown&&this._updateValueFromPointer(e,i)}super._onPointerMove(e,t,i,s)}}_onPointerUp(e,t,i,s,r,n){this._pointerIsDown=!1,delete this._host._capturingControl[i],super._onPointerUp(e,t,i,s,r,n)}_onCanvasBlur(){this._forcePointerUp(),super._onCanvasBlur()}static ShowPickerDialogAsync(e,t){return new Promise((i=>{t.pickerWidth=t.pickerWidth||"640px",t.pickerHeight=t.pickerHeight||"400px",t.headerHeight=t.headerHeight||"35px",t.lastColor=t.lastColor||"#000000",t.swatchLimit=t.swatchLimit||20,t.numSwatchesPerLine=t.numSwatchesPerLine||10;const s=t.swatchLimit/t.numSwatchesPerLine,r=parseFloat(t.pickerWidth)/t.numSwatchesPerLine,n=Math.floor(.25*r),o=n*(t.numSwatchesPerLine+1),a=Math.floor((parseFloat(t.pickerWidth)-o)/t.numSwatchesPerLine),l=a*s+n*(s+1),h=(parseInt(t.pickerHeight)+l+Math.floor(.25*a)).toString()+"px",c="#c0c0c0",u="#535353",d="#414141",_="515151",p="#555555",f="#454545",m=Ce.FromHexString("#dddddd"),g=m.r+m.g+m.b,v="#aaaaaa",x="#ffffff";let b,T;const y=["R","G","B"],S="#454545",C="#f0f0f0";let E,A,P,R,I,M=!1;const O=new QD;if(O.name="Dialog Container",O.width=t.pickerWidth,t.savedColors){O.height=h;const e=parseInt(t.pickerHeight)/parseInt(h);O.addRowDefinition(e,!1),O.addRowDefinition(1-e,!1)}else O.height=t.pickerHeight,O.addRowDefinition(1,!1);if(e.addControl(O),t.savedColors){A=new QD,A.name="Swatch Drawer",A.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,A.background=u,A.width=t.pickerWidth;const e=t.savedColors.length/t.numSwatchesPerLine;let i;i=0==e?0:e+1,A.height=(a*e+i*n).toString()+"px",A.top=Math.floor(.25*a).toString()+"px";for(let e=0;e<2*Math.ceil(t.savedColors.length/t.numSwatchesPerLine)+1;e++)e%2!=0?A.addRowDefinition(a,!0):A.addRowDefinition(n,!0);for(let e=0;e<2*t.numSwatchesPerLine+1;e++)e%2!=0?A.addColumnDefinition(a,!0):A.addColumnDefinition(n,!0);O.addControl(A,1,0)}const D=new QD;D.name="Picker Panel",D.height=t.pickerHeight;const w=parseInt(t.headerHeight)/parseInt(t.pickerHeight),N=[w,1-w];D.addRowDefinition(N[0],!1),D.addRowDefinition(N[1],!1),O.addControl(D,0,0);const F=new kD;F.name="Dialogue Header Bar",F.background="#cccccc",F.thickness=0,D.addControl(F,0,0);const B=zD.CreateSimpleButton("closeButton","a");B.fontFamily="coreglyphs";const L=Ce.FromHexString(F.background),k=new Ce(1-L.r,1-L.g,1-L.b);B.color=k.toHexString(),B.fontSize=Math.floor(.6*parseInt(t.headerHeight)),B.textBlock.textVerticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,B.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_RIGHT,B.height=B.width=t.headerHeight,B.background=F.background,B.thickness=0,B.pointerDownAnimation=()=>{},B.pointerUpAnimation=()=>{B.background=F.background},B.pointerEnterAnimation=()=>{B.color=F.background,B.background="red"},B.pointerOutAnimation=()=>{B.color=k.toHexString(),B.background=F.background},B.onPointerClickObservable.add((()=>{De(te.background)})),D.addControl(B,0,0);const V=new QD;V.name="Dialogue Body",V.background=u;const U=[.4375,.5625];V.addRowDefinition(1,!1),V.addColumnDefinition(U[0],!1),V.addColumnDefinition(U[1],!1),D.addControl(V,1,0);const G=new QD;G.name="Picker Grid",G.addRowDefinition(.85,!1),G.addRowDefinition(.15,!1),V.addControl(G,0,0);const z=new jD;z.name="GUI Color Picker",t.pickerHeight{I=z.name,R="",Re(!1)})),z.onValueChangedObservable.add((function(e){I==z.name&&Se(e,z.name)})),G.addControl(z,0,0);const W=new QD;W.name="Dialogue Right Half",W.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT;const H=[.514,.486];W.addRowDefinition(H[0],!1),W.addRowDefinition(H[1],!1),V.addControl(W,1,1);const X=new QD;X.name="Swatches and Buttons";const Y=[.417,.583];X.addRowDefinition(1,!1),X.addColumnDefinition(Y[0],!1),X.addColumnDefinition(Y[1],!1),W.addControl(X,0,0);const Q=new QD;Q.name="New and Current Swatches";const j=[.04,.16,.64,.16];Q.addRowDefinition(j[0],!1),Q.addRowDefinition(j[1],!1),Q.addRowDefinition(j[2],!1),Q.addRowDefinition(j[3],!1),X.addControl(Q,0,0);const K=new QD;K.name="Active Swatches",K.width=.67,K.addRowDefinition(.5,!1),K.addRowDefinition(.5,!1),Q.addControl(K,2,0);const $=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[0]*.11),q=Math.floor(parseInt(t.pickerHeight)*N[1]*H[0]*j[1]*.5);let Z;Z=t.pickerWidth>t.pickerHeight?q:$;const J=new UD;J.text="new",J.name="New Color Label",J.color=c,J.fontSize=Z,Q.addControl(J,1,0);const ee=new kD;ee.name="New Color Swatch",ee.background=t.lastColor,ee.thickness=0,K.addControl(ee,0,0);const te=zD.CreateSimpleButton("currentSwatch","");te.background=t.lastColor,te.thickness=0,te.onPointerClickObservable.add((()=>{Se(Ce.FromHexString(te.background),te.name),Re(!1)})),te.pointerDownAnimation=()=>{},te.pointerUpAnimation=()=>{},te.pointerEnterAnimation=()=>{},te.pointerOutAnimation=()=>{},K.addControl(te,1,0);const ie=new kD;ie.name="Swatch Outline",ie.width=.67,ie.thickness=2,ie.color="#404040",ie.isHitTestVisible=!1,Q.addControl(ie,2,0);const se=new UD;se.name="Current Color Label",se.text="current",se.color=c,se.fontSize=Z,Q.addControl(se,3,0);const re=new QD;re.name="Button Grid",re.height=.8;const ne=1/3;re.addRowDefinition(ne,!1),re.addRowDefinition(ne,!1),re.addRowDefinition(ne,!1),X.addControl(re,0,1);const oe=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[1]*.67).toString()+"px",ae=Math.floor(parseInt(t.pickerHeight)*N[1]*H[0]*(parseFloat(re.height.toString())/100)*ne*.7).toString()+"px";b=parseFloat(oe)>parseFloat(ae)?Math.floor(.45*parseFloat(ae)):Math.floor(.11*parseFloat(oe));const le=zD.CreateSimpleButton("butOK","OK");le.width=oe,le.height=ae,le.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,le.thickness=2,le.color=c,le.fontSize=b,le.background=u,le.onPointerEnterObservable.add((()=>{le.background=d})),le.onPointerOutObservable.add((()=>{le.background=u})),le.pointerDownAnimation=()=>{le.background=_},le.pointerUpAnimation=()=>{le.background=d},le.onPointerClickObservable.add((()=>{Re(!1),De(ee.background)})),re.addControl(le,0,0);const he=zD.CreateSimpleButton("butCancel","Cancel");he.width=oe,he.height=ae,he.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,he.thickness=2,he.color=c,he.fontSize=b,he.background=u,he.onPointerEnterObservable.add((()=>{he.background=d})),he.onPointerOutObservable.add((()=>{he.background=u})),he.pointerDownAnimation=()=>{he.background=_},he.pointerUpAnimation=()=>{he.background=d},he.onPointerClickObservable.add((()=>{Re(!1),De(te.background)})),re.addControl(he,1,0),t.savedColors&&(P=zD.CreateSimpleButton("butSave","Save"),P.width=oe,P.height=ae,P.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,P.thickness=2,P.fontSize=b,t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&(0==t.savedColors.length&&Me(!0),t.savedColors.length0&&Me(!0),re.addControl(P,2,0));const ce=new QD;ce.name="Dialog Lower Right",ce.addRowDefinition(.02,!1),ce.addRowDefinition(.63,!1),ce.addRowDefinition(.21,!1),ce.addRowDefinition(.14,!1),W.addControl(ce,1,0);const ue=Ce.FromHexString(t.lastColor),de=new QD;de.name="RGB Values",de.width=.82,de.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,de.addRowDefinition(1/3,!1),de.addRowDefinition(1/3,!1),de.addRowDefinition(1/3,!1),de.addColumnDefinition(.1,!1),de.addColumnDefinition(.2,!1),de.addColumnDefinition(.7,!1),ce.addControl(de,1,0);for(let e=0;e{I=_e.name,R=_e.text,Re(!1)})),_e.onBlurObservable.add((()=>{""==_e.text&&(_e.text="0"),Ee(_e,"r"),I==_e.name&&(I="")})),_e.onTextChangedObservable.add((()=>{I==_e.name&&Ee(_e,"r")})),de.addControl(_e,0,1);const pe=new YD;pe.width=.83,pe.height=.72,pe.name="gIntField",pe.fontSize=b,pe.text=(255*ue.g).toString(),pe.color=C,pe.background=S,pe.onFocusObservable.add((()=>{I=pe.name,R=pe.text,Re(!1)})),pe.onBlurObservable.add((()=>{""==pe.text&&(pe.text="0"),Ee(pe,"g"),I==pe.name&&(I="")})),pe.onTextChangedObservable.add((()=>{I==pe.name&&Ee(pe,"g")})),de.addControl(pe,1,1);const fe=new YD;fe.width=.83,fe.height=.72,fe.name="bIntField",fe.fontSize=b,fe.text=(255*ue.b).toString(),fe.color=C,fe.background=S,fe.onFocusObservable.add((()=>{I=fe.name,R=fe.text,Re(!1)})),fe.onBlurObservable.add((()=>{""==fe.text&&(fe.text="0"),Ee(fe,"b"),I==fe.name&&(I="")})),fe.onTextChangedObservable.add((()=>{I==fe.name&&Ee(fe,"b")})),de.addControl(fe,2,1);const me=new YD;me.width=.95,me.height=.72,me.name="rDecField",me.fontSize=b,me.text=ue.r.toString(),me.color=C,me.background=S,me.onFocusObservable.add((()=>{I=me.name,R=me.text,Re(!1)})),me.onBlurObservable.add((()=>{0!=parseFloat(me.text)&&""!=me.text||(me.text="0",Ae(me,"r")),I==me.name&&(I="")})),me.onTextChangedObservable.add((()=>{I==me.name&&Ae(me,"r")})),de.addControl(me,0,2);const ge=new YD;ge.width=.95,ge.height=.72,ge.name="gDecField",ge.fontSize=b,ge.text=ue.g.toString(),ge.color=C,ge.background=S,ge.onFocusObservable.add((()=>{I=ge.name,R=ge.text,Re(!1)})),ge.onBlurObservable.add((()=>{0!=parseFloat(ge.text)&&""!=ge.text||(ge.text="0",Ae(ge,"g")),I==ge.name&&(I="")})),ge.onTextChangedObservable.add((()=>{I==ge.name&&Ae(ge,"g")})),de.addControl(ge,1,2);const ve=new YD;ve.width=.95,ve.height=.72,ve.name="bDecField",ve.fontSize=b,ve.text=ue.b.toString(),ve.color=C,ve.background=S,ve.onFocusObservable.add((()=>{I=ve.name,R=ve.text,Re(!1)})),ve.onBlurObservable.add((()=>{0!=parseFloat(ve.text)&&""!=ve.text||(ve.text="0",Ae(ve,"b")),I==ve.name&&(I="")})),ve.onTextChangedObservable.add((()=>{I==ve.name&&Ae(ve,"b")})),de.addControl(ve,2,2);const xe=new QD;xe.name="Hex Value",xe.width=.82,xe.addRowDefinition(1,!1),xe.addColumnDefinition(.1,!1),xe.addColumnDefinition(.9,!1),ce.addControl(xe,2,0);const be=new UD;be.text="#",be.color=c,be.fontSize=b,xe.addControl(be,0,0);const Te=new YD;Te.width=.96,Te.height=.72,Te.name="hexField",Te.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,Te.fontSize=b;const ye=t.lastColor.split("#");function Se(e,t){I=t;const i=e.toHexString();if(ee.background=i,_e.name!=I&&(_e.text=Math.floor(255*e.r).toString()),pe.name!=I&&(pe.text=Math.floor(255*e.g).toString()),fe.name!=I&&(fe.text=Math.floor(255*e.b).toString()),me.name!=I&&(me.text=e.r.toString()),ge.name!=I&&(ge.text=e.g.toString()),ve.name!=I&&(ve.text=e.b.toString()),Te.name!=I){const e=i.split("#");Te.text=e[1]}z.name!=I&&(z.value=e)}function Ee(e,t){let i=e.text;if(/[^0-9]/g.test(i))e.text=R;else if(""!=i&&(Math.floor(parseInt(i))<0?i="0":Math.floor(parseInt(i))>255?i="255":isNaN(parseInt(i))&&(i="0")),I==e.name&&(R=i),""!=i){i=parseInt(i).toString(),e.text=i;const s=Ce.FromHexString(ee.background);I==e.name&&Se("r"==t?new Ce(parseInt(i)/255,s.g,s.b):"g"==t?new Ce(s.r,parseInt(i)/255,s.b):new Ce(s.r,s.g,parseInt(i)/255),e.name)}}function Ae(e,t){let i=e.text;if(/[^0-9.]/g.test(i))return void(e.text=R);""!=i&&"."!=i&&0!=parseFloat(i)&&(parseFloat(i)<0?i="0.0":parseFloat(i)>1?i="1.0":isNaN(parseFloat(i))&&(i="0.0")),I==e.name&&(R=i),""!=i&&"."!=i&&0!=parseFloat(i)?(i=parseFloat(i).toString(),e.text=i):i="0.0";const s=Ce.FromHexString(ee.background);I==e.name&&Se("r"==t?new Ce(parseFloat(i),s.g,s.b):"g"==t?new Ce(s.r,parseFloat(i),s.b):new Ce(s.r,s.g,parseFloat(i)),e.name)}function Pe(){if(t.savedColors&&t.savedColors[E]){let e;e=M?"b":"";const i=zD.CreateSimpleButton("Swatch_"+E,e);i.fontFamily="coreglyphs";const s=Ce.FromHexString(t.savedColors[E]),r=s.r+s.g+s.b;i.color=r>g?v:x,i.fontSize=Math.floor(.7*a),i.textBlock.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,i.height=i.width=a.toString()+"px",i.background=t.savedColors[E],i.thickness=2;const n=E;return i.pointerDownAnimation=()=>{i.thickness=4},i.pointerUpAnimation=()=>{i.thickness=3},i.pointerEnterAnimation=()=>{i.thickness=3},i.pointerOutAnimation=()=>{i.thickness=2},i.onPointerClickObservable.add((()=>{var e;M?(e=n,t.savedColors&&t.savedColors.splice(e,1),t.savedColors&&0==t.savedColors.length&&(Me(!1),M=!1),Ie("",P)):t.savedColors&&Se(Ce.FromHexString(t.savedColors[n]),i.name)})),i}return null}function Re(e){let t;if(void 0!==e&&(M=e),M){for(let e=0;ei*t.numSwatchesPerLine?t.numSwatchesPerLine:t.savedColors.length-(i-1)*t.numSwatchesPerLine;const r=Math.min(Math.max(s,0),t.numSwatchesPerLine);for(let i=0,s=1;it.numSwatchesPerLine)continue;const r=Pe();null!=r&&(A.addControl(r,e,s),s+=2,E++)}}t.savedColors.length>=t.swatchLimit?Oe(i,!0):Oe(i,!1)}}function Me(e){e?(T=zD.CreateSimpleButton("butEdit","Edit"),T.width=oe,T.height=ae,T.left=Math.floor(.1*parseInt(oe)).toString()+"px",T.top=(-1*parseFloat(T.left)).toString()+"px",T.verticalAlignment=BD.VERTICAL_ALIGNMENT_BOTTOM,T.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,T.thickness=2,T.color=c,T.fontSize=b,T.background=u,T.onPointerEnterObservable.add((()=>{T.background=d})),T.onPointerOutObservable.add((()=>{T.background=u})),T.pointerDownAnimation=()=>{T.background=_},T.pointerUpAnimation=()=>{T.background=d},T.onPointerClickObservable.add((()=>{M=!M,Re()})),G.addControl(T,1,0)):G.removeControl(T)}function Oe(e,t){t?(e.color=p,e.background=f):(e.color=c,e.background=u)}function De(s){t.savedColors&&t.savedColors.length>0?i({savedColors:t.savedColors,pickedColor:s}):i({pickedColor:s}),e.removeControl(O)}Te.text=ye[1],Te.color=C,Te.background=S,Te.onFocusObservable.add((()=>{I=Te.name,R=Te.text,Re(!1)})),Te.onBlurObservable.add((()=>{if(3==Te.text.length){const e=Te.text.split("");Te.text=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]}""==Te.text&&(Te.text="000000",Se(Ce.FromHexString(Te.text),"b")),I==Te.name&&(I="")})),Te.onTextChangedObservable.add((()=>{let e=Te.text;const t=/[^0-9A-F]/i.test(e);if((Te.text.length>6||t)&&I==Te.name)Te.text=R;else{if(Te.text.length<6){const t=6-Te.text.length;for(let i=0;i0&&Ie("",P)}))}}jD._Epsilon=1e-6,qe([st()],jD.prototype,"value",null),qe([st()],jD.prototype,"width",null),qe([st()],jD.prototype,"height",null),qe([st()],jD.prototype,"size",null),ee("BABYLON.GUI.ColorPicker",jD);class KD extends LD{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thickness=1}_getTypeName(){return"Ellipse"}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),(this._backgroundGradient||this._background)&&(e.fillStyle=this._getBackgroundColor(e),e.fill()),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.stroke()),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_clipForChildren(e){BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2,this._currentMeasure.height/2,e),e.clip()}_renderHighlightSpecific(e){BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._highlightLineWidth/2,this._currentMeasure.height/2-this._highlightLineWidth/2,e),e.stroke()}}qe([st()],KD.prototype,"thickness",null),ee("BABYLON.GUI.Ellipse",KD);class $D extends zD{constructor(e){super(e),this.name=e,this.focusedColor=null,this._isFocused=!1,this._unfocusedColor=null,this.onFocusObservable=new X,this.onBlurObservable=new X,this.onKeyboardEventProcessedObservable=new X,this._unfocusedColor=this.color}onBlur(){this._isFocused&&(this._isFocused=!1,this.focusedColor&&null!=this._unfocusedColor&&(this.color=this._unfocusedColor),this.onBlurObservable.notifyObservers(this))}onFocus(){this._isFocused=!0,this.focusedColor&&(this._unfocusedColor=this.color,this.color=this.focusedColor),this.onFocusObservable.notifyObservers(this)}keepsFocusWith(){return null}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}processKeyboard(e){this.onKeyboardEventProcessedObservable.notifyObservers(e,-1,this)}_onPointerDown(e,t,i,s,r){return this.isReadOnly||this.focus(),super._onPointerDown(e,t,i,s,r)}dispose(){super.dispose(),this.onBlurObservable.clear(),this.onFocusObservable.clear(),this.onKeyboardEventProcessedObservable.clear()}}ee("BABYLON.GUI.FocusableButton",$D);class qD extends YD{get autoStretchHeight(){return this._autoStretchHeight}set autoStretchHeight(e){this._autoStretchHeight!==e&&(this._autoStretchHeight=e,this._markAsDirty())}set height(e){this.fixedRatioMasterIsWidth=!1,this._height.toString(this._host)!==e&&(this._height.fromString(e)&&this._markAsDirty(),this._autoStretchHeight=!1)}get maxHeight(){return this._maxHeight.toString(this._host)}get maxHeightInPixels(){return this._maxHeight.getValueInPixel(this._host,this._cachedParentMeasure.height)}set maxHeight(e){this._maxHeight.toString(this._host)!==e&&this._maxHeight.fromString(e)&&this._markAsDirty()}constructor(e,t=""){super(e),this.name=e,this._textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._textVerticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._prevText=this.text,this._lineSpacing=new PD(0),this._maxHeight=new PD(1,PD.UNITMODE_PERCENTAGE,!1),this.onLinesReadyObservable=new X,this.text=t,this.isPointerBlocker=!0,this.onLinesReadyObservable.add((()=>this._updateCursorPosition())),this._highlightCursorInfo={initialStartIndex:-1,initialRelativeStartIndex:-1,initialLineIndex:-1},this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeEndIndex:0,relativeStartIndex:0,currentLineIndex:0}}_getTypeName(){return"InputTextArea"}processKeyboard(e){this.isReadOnly||(this.alternativeProcessKey(e.code,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e))}alternativeProcessKey(e,t,i){if(!i||!i.ctrlKey&&!i.metaKey||"KeyC"!==e&&"KeyV"!==e&&"KeyX"!==e){switch(e){case"KeyA":if(i&&(i.ctrlKey||i.metaKey))return this._selectAllText(),void i.preventDefault();break;case"Period":i&&i.shiftKey&&i.preventDefault();break;case"Backspace":!this._isTextHighlightOn&&this._cursorInfo.globalStartIndex>0&&(this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--),this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,i&&i.preventDefault(),this._blinkIsEven=!1,this._isTextHighlightOn=!1,this._textHasChanged();break;case"Delete":!this._isTextHighlightOn&&this._cursorInfo.globalEndIndexthis._highlightCursorInfo.initialStartIndex?this._cursorInfo.globalEndIndex--:this._cursorInfo.globalStartIndex--:(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--,this._isTextHighlightOn=!0),this._blinkIsEven=!0,void i.preventDefault()):(this._isTextHighlightOn?this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex:i&&(i.ctrlKey||i.metaKey)?(this._cursorInfo.globalStartIndex-=this._cursorInfo.relativeStartIndex,i.preventDefault()):this._cursorInfo.globalStartIndex>0&&this._cursorInfo.globalStartIndex--,this._blinkIsEven=!1,void(this._isTextHighlightOn=!1));case"ArrowRight":if(this._markAsDirty(),i&&i.shiftKey){if(i.ctrlKey||i.metaKey){const e=this._lines[this._cursorInfo.currentLineIndex].text.length-this._cursorInfo.relativeEndIndex-1;this._cursorInfo.globalEndIndex+=e,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex}return this._isTextHighlightOn?this._cursorInfo.globalStartIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndex<=this._highlightCursorInfo.initialLineIndex?(this._cursorInfo.globalStartIndex=i,this._cursorInfo.globalEndIndex=this._highlightCursorInfo.initialStartIndex,this._cursorInfo.relativeEndIndex=this._highlightCursorInfo.initialRelativeStartIndex):this._cursorInfo.globalEndIndex=i:this._cursorInfo.globalStartIndex=i}return void this._markAsDirty();case"ArrowDown":if(this._blinkIsEven=!1,i&&(i.shiftKey?(this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex),this._isTextHighlightOn=!0,this._blinkIsEven=!0):this._isTextHighlightOn=!1,i.preventDefault()),this._cursorInfo.currentLineIndex===this._lines.length-1)this._cursorInfo.globalStartIndex=this.text.length;else{const e=this._lines[this._cursorInfo.currentLineIndex],t=this._lines[this._cursorInfo.currentLineIndex+1];let i=0,s=0;!this._isTextHighlightOn||this._cursorInfo.currentLineIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndexthis._cursorInfo.globalEndIndex&&(this._cursorInfo.globalEndIndex+=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex=this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex-=this._cursorInfo.globalStartIndex)):(this._cursorInfo.globalEndIndex=i,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex):this._cursorInfo.globalStartIndex=i}return void this._markAsDirty()}1===t?.length&&(i?.preventDefault(),this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&(this._isTextHighlightOn=!1,this._blinkIsEven=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t),this._cursorInfo.globalStartIndex+=t.length,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()))}}_parseLineWordWrap(e="",t,i){const s=[],r=e.split(" ");let n=0;for(let o=0;o0?e+" "+r[o]:r[0],l=i.measureText(a).width;if(l>t){o>0&&(n=i.measureText(e).width,s.push({text:e,width:n,lineEnding:" "})),e=r[o];let a="";e.split("").map((e=>{i.measureText(a+e).width>t&&(s.push({text:a,width:i.measureText(a).width,lineEnding:""}),a=""),a+=e})),e=a,n=i.measureText(e).width}else n=l,e=a}return s.push({text:e,width:n,lineEnding:" "}),s}_breakLines(e,t){const i=[],s=(this.text||this.placeholderText).split("\n");if(this.clipContent)for(const r of s)i.push(...this._parseLineWordWrap(r,e,t));else for(const e of s)i.push(this._parseLine(e,t));return i[i.length-1].lineEnding="\n",i}_parseLine(e="",t){return{text:e,width:t.measureText(e).width,lineEnding:" "}}_preMeasure(e,t){this._fontOffset&&!this._wasDirty||(this._fontOffset=BD._GetFontOffset(t.font));let i=this._beforeRenderText(this._textWrapper).text;!this.text&&this._placeholderText&&(i=this._placeholderText),this._textWidth=t.measureText(i).width;const s=2*this._margin.getValueInPixel(this._host,e.width);if(this._autoStretchWidth){const r=i.split("\n").reduce(((e,i)=>t.measureText(i).width>t.measureText(e).width?i:e),""),n=t.measureText(r).width;this.width=Math.min(this._maxWidth.getValueInPixel(this._host,e.width),n+s)+"px",this.autoStretchWidth=!0}if(this._availableWidth=this._width.getValueInPixel(this._host,e.width)-s,this._lines=this._breakLines(this._availableWidth,t),this._contextForBreakLines=t,this._autoStretchHeight){const t=this._lines.length*this._fontOffset.height+2*this._margin.getValueInPixel(this._host,e.height);this.height=Math.min(this._maxHeight.getValueInPixel(this._host,e.height),t)+"px",this._autoStretchHeight=!0}if(this._availableHeight=this._height.getValueInPixel(this._host,e.height)-s,this._isFocused){this._cursorInfo.currentLineIndex=0;let e=this._lines[this._cursorInfo.currentLineIndex].text.length+this._lines[this._cursorInfo.currentLineIndex].lineEnding.length,t=0;for(;t+e<=this._cursorInfo.globalStartIndex;)t+=e,this._cursorInfo.currentLineIndexthis._availableWidth){const e=this._clipTextLeft-this._lines[this._cursorInfo.currentLineIndex].width+this._availableWidth;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=this._clipTextLeft;if(this._isFocused&&!this._autoStretchHeight){const e=(this._cursorInfo.currentLineIndex+1)*this._fontOffset.height,t=this._clipTextTop-e;this._scrollTop||(this._scrollTop=t)}else this._scrollTop=this._clipTextTop}_additionalProcessing(){this.highlightedText="",this.onLinesReadyObservable.notifyObservers(this)}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=this._scrollLeft;switch(this._textHorizontalAlignment){case BD.HORIZONTAL_ALIGNMENT_LEFT:n+=0;break;case BD.HORIZONTAL_ALIGNMENT_RIGHT:n+=r-t;break;case BD.HORIZONTAL_ALIGNMENT_CENTER:n+=(r-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,n,i)}_onCopyText(e){this._isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._textHasChanged()}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData,this._isTextHighlightOn=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t);const i=t.length-(this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex);this._cursorInfo.globalStartIndex+=i,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()}_draw(e){this._computeScroll(),this._scrollLeft=this._scrollLeft??0,this._scrollTop=this._scrollTop??0,e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this.color&&(e.fillStyle=this.color);const t=this._currentMeasure.height,i=this._currentMeasure.width;let s=0;switch(this._textVerticalAlignment){case BD.VERTICAL_ALIGNMENT_TOP:s=this._fontOffset.ascent;break;case BD.VERTICAL_ALIGNMENT_BOTTOM:s=t-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case BD.VERTICAL_ALIGNMENT_CENTER:s=this._fontOffset.ascent+(t-this._fontOffset.height*this._lines.length)/2}e.save(),e.beginPath(),e.fillStyle=this.fontStyle,!this._textWrapper.text&&this.placeholderText&&(e.fillStyle=this._placeholderColor),e.rect(this._clipTextLeft,this._clipTextTop,this._availableWidth+2,this._availableHeight+2),e.clip(),s+=this._scrollTop;for(let t=0;tthis._clipTextLeft+this._availableWidth&&(this._scrollLeft+=this._clipTextLeft+this._availableWidth-t,t=this._clipTextLeft+this._availableWidth,this._markAsDirty());let i=this._scrollTop+this._cursorInfo.currentLineIndex*this._fontOffset.height;ithis._clipTextTop+this._availableHeight&&(this._scrollTop+=this._clipTextTop+this._availableHeight-i-this._fontOffset.height,i=this._clipTextTop+this._availableHeight-this._fontOffset.height,this._markAsDirty()),this._isTextHighlightOn||e.fillRect(t,i,2,this._fontOffset.height)}if(this._resetBlinking(),this._isTextHighlightOn){clearTimeout(this._blinkTimeout),this._highlightedText=this.text.substring(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),e.globalAlpha=this._highligherOpacity,e.fillStyle=this._textHighlightColor;const t=Math.min(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex),s=Math.max(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex);let r=this._scrollTop+t*this._fontOffset.height;for(let n=t;n<=s;n++){const o=this._lines[n];let a=this._scrollLeft;switch(this._textHorizontalAlignment){case BD.HORIZONTAL_ALIGNMENT_LEFT:a+=0;break;case BD.HORIZONTAL_ALIGNMENT_RIGHT:a+=i-o.width;break;case BD.HORIZONTAL_ALIGNMENT_CENTER:a+=(i-o.width)/2}const l=n===t?this._cursorInfo.relativeStartIndex:0,h=n===s?this._cursorInfo.relativeEndIndex:o.text.length,c=e.measureText(o.text.substr(0,l)).width,u=o.text.substring(l,h),d=e.measureText(u).width;e.fillRect(a+c,r,d,this._fontOffset.height),r+=this._fontOffset.height}this._cursorInfo.globalEndIndex===this._cursorInfo.globalStartIndex&&this._resetBlinking()}}e.restore(),this._thickness&&(this._isFocused?this.focusedColor&&(e.strokeStyle=this.focusedColor):this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}_resetBlinking(){clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500)}_onPointerDown(e,t,i,s,r){return!(!super._onPointerDown(e,t,i,s,r)||!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn=!1,this._highlightedText="",this._isPointerDown=!0,this._host._capturingControl[i]=this,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),0):!this._isEnabled||(this._host.focusedControl=this,0)))}_onPointerMove(e,t,i,s){0===s.event.movementX&&0===s.event.movementY||(this._host.focusedControl===this&&this._isPointerDown&&!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._isTextHighlightOn=!0),this._markAsDirty()),super._onPointerMove(e,t,i,s))}_updateCursorPosition(){if(this._isFocused)if(!this._textWrapper.text&&this.placeholderText)this._cursorInfo.currentLineIndex=0,this._cursorInfo.globalStartIndex=0,this._cursorInfo.globalEndIndex=0,this._cursorInfo.relativeStartIndex=0,this._cursorInfo.relativeEndIndex=0;else if(this._clickedCoordinateX&&this._clickedCoordinateY){this._isTextHighlightOn||(this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeStartIndex:0,relativeEndIndex:0,currentLineIndex:0});let e=0,t=0;const i=this._clickedCoordinateY-this._scrollTop,s=Math.floor(i/this._fontOffset.height);this._cursorInfo.currentLineIndex=Math.min(Math.max(s,0),this._lines.length-1);let r=0;const n=this._clickedCoordinateX-(this._scrollLeft??0);let o=0;for(let t=0;tt;)t++,o=Math.abs(n-r),r=this._contextForBreakLines.measureText(this._lines[this._cursorInfo.currentLineIndex].text.substr(0,t)).width;Math.abs(n-r)>o&&t>0&&t--,e+=t,this._isTextHighlightOn?e=this._highlightCursorInfo.initialStartIndex){for(;t+e<=this._cursorInfo.globalEndIndex;)t+=e,this._cursorInfo.currentLineIndex0&&this._textWrapper.isWord(this._cursorInfo.globalStartIndex-1)?--this._cursorInfo.globalStartIndex:0,i=this._cursorInfo.globalEndIndexthis._markAsDirty()))),this._connectedControl=e,this._markAsDirty())}get x1(){return this._x1.toString(this._host)}set x1(e){this._x1.toString(this._host)!==e&&this._x1.fromString(e)&&this._markAsDirty()}get y1(){return this._y1.toString(this._host)}set y1(e){this._y1.toString(this._host)!==e&&this._y1.fromString(e)&&this._markAsDirty()}get x2(){return this._x2.toString(this._host)}set x2(e){this._x2.toString(this._host)!==e&&this._x2.fromString(e)&&this._markAsDirty()}get y2(){return this._y2.toString(this._host)}set y2(e){this._y2.toString(this._host)!==e&&this._y2.fromString(e)&&this._markAsDirty()}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}get _effectiveX2(){return(this._connectedControl?this._connectedControl.centerX:0)+this._x2.getValue(this._host)}get _effectiveY2(){return(this._connectedControl?this._connectedControl.centerY:0)+this._y2.getValue(this._host)}constructor(e){super(e),this.name=e,this._lineWidth=1,this._x1=new PD(0),this._y1=new PD(0),this._x2=new PD(0),this._y2=new PD(0),this._dash=new Array,this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP}_getTypeName(){return"Line"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this._getColor(e),e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath(),e.moveTo(this._cachedParentMeasure.left+this._x1.getValue(this._host),this._cachedParentMeasure.top+this._y1.getValue(this._host)),e.lineTo(this._cachedParentMeasure.left+this._effectiveX2,this._cachedParentMeasure.top+this._effectiveY2),e.stroke(),e.restore()}_measure(){this._currentMeasure.width=Math.abs(this._x1.getValue(this._host)-this._effectiveX2)+this._lineWidth,this._currentMeasure.height=Math.abs(this._y1.getValue(this._host)-this._effectiveY2)+this._lineWidth}_computeAlignment(e){this._currentMeasure.left=e.left+Math.min(this._x1.getValue(this._host),this._effectiveX2)-this._lineWidth/2,this._currentMeasure.top=e.top+Math.min(this._y1.getValue(this._host),this._effectiveY2)-this._lineWidth/2}moveToVector3(e,t,i=!1){if(!this._host||this.parent!==this._host._rootContainer)return void hs.Error("Cannot move a control to a vector3 if the control is not at root level");const s=this._host._getGlobalViewport(),r=de.Project(e,fe.IdentityReadOnly,t.getTransformMatrix(),s);this._moveToProjectedPosition(r,i),r.z<0||r.z>1?this.notRenderable=!0:this.notRenderable=!1}_moveToProjectedPosition(e,t=!1){const i=e.x+this._linkOffsetX.getValue(this._host)+"px",s=e.y+this._linkOffsetY.getValue(this._host)+"px";t?(this.x2=i,this.y2=s,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=s,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)}}qe([st()],JD.prototype,"dash",null),qe([st()],JD.prototype,"x1",null),qe([st()],JD.prototype,"y1",null),qe([st()],JD.prototype,"x2",null),qe([st()],JD.prototype,"y2",null),qe([st()],JD.prototype,"lineWidth",null),ee("BABYLON.GUI.Line",JD);class ew{constructor(e){this._multiLine=e,this._x=new PD(0),this._y=new PD(0),this._point=new de(0,0,0)}get x(){return this._x.toString(this._multiLine._host)}set x(e){this._x.toString(this._multiLine._host)!==e&&this._x.fromString(e)&&this._multiLine._markAsDirty()}get y(){return this._y.toString(this._multiLine._host)}set y(e){this._y.toString(this._multiLine._host)!==e&&this._y.fromString(e)&&this._multiLine._markAsDirty()}get control(){return this._control}set control(e){this._control!==e&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=e,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=e,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}resetLinks(){this.control=null,this.mesh=null}translate(){return this._point=this._translatePoint(),this._point}_translatePoint(){if(null!=this._mesh)return this._multiLine._host.getProjectedPositionWithZ(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(null!=this._control)return new de(this._control.centerX,this._control.centerY,1-K);{const e=this._multiLine._host,t=this._x.getValueInPixel(e,Number(e._canvas.width)),i=this._y.getValueInPixel(e,Number(e._canvas.height));return new de(t,i,1-K)}}dispose(){this.resetLinks()}}class tw extends BD{constructor(e){super(e),this.name=e,this._lineWidth=1,this.onPointUpdate=()=>{this._markAsDirty()},this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._dash=[],this._points=[]}get dash(){return this._dash}set dash(e){this._dash!==e&&(this._dash=e,this._markAsDirty())}getAt(e){return this._points[e]||(this._points[e]=new ew(this)),this._points[e]}add(...e){return e.map((e=>this.push(e)))}push(e){const t=this.getAt(this._points.length);return null==e||(e instanceof Sn?t.mesh=e:e instanceof BD?t.control=e:null!=e.x&&null!=e.y&&(t.x=e.x,t.y=e.y)),t}remove(e){let t;if(e instanceof ew){if(t=this._points.indexOf(e),-1===t)return}else t=e;const i=this._points[t];i&&(i.dispose(),this._points.splice(t,1))}reset(){for(;this._points.length>0;)this.remove(this._points.length-1)}resetLinks(){this._points.forEach((e=>{null!=e&&e.resetLinks()}))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}_getTypeName(){return"MultiLine"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this.color,e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath();let t,i=!0;this._points.forEach((s=>{s&&(i?(e.moveTo(s._point.x,s._point.y),i=!1):s._point.z<1&&t.z<1?e.lineTo(s._point.x,s._point.y):e.moveTo(s._point.x,s._point.y),t=s._point)})),e.stroke(),e.restore()}_additionalProcessing(){this._minX=null,this._minY=null,this._maxX=null,this._maxY=null,this._points.forEach((e=>{e&&(e.translate(),(null==this._minX||e._point.xthis._maxX)&&(this._maxX=e._point.x),(null==this._maxY||e._point.y>this._maxY)&&(this._maxY=e._point.y))})),null==this._minX&&(this._minX=0),null==this._minY&&(this._minY=0),null==this._maxX&&(this._maxX=0),null==this._maxY&&(this._maxY=0)}_measure(){null!=this._minX&&null!=this._maxX&&null!=this._minY&&null!=this._maxY&&(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)}_computeAlignment(){null!=this._minX&&null!=this._minY&&(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)}dispose(){this.reset(),super.dispose()}}qe([st()],tw.prototype,"dash",null),ee("BABYLON.GUI.MultiLine",tw);class iw extends BD{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get checkSizeRatio(){return this._checkSizeRatio}set checkSizeRatio(e){e=Math.max(Math.min(1,e),0),this._checkSizeRatio!==e&&(this._checkSizeRatio=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get isChecked(){return this._isChecked}set isChecked(e){this._isChecked!==e&&(this._isChecked=e,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(e),this._isChecked&&this._host&&this._host.executeOnAllControls((e=>{if(e===this)return;if(void 0===e.group)return;const t=e;t.group===this.group&&(t.isChecked=!1)})))}constructor(e){super(e),this.name=e,this._isChecked=!1,this._background="black",this._checkSizeRatio=.8,this._thickness=1,this.group="",this.onIsCheckedChangedObservable=new X,this.isPointerBlocker=!0}_getTypeName(){return"RadioButton"}_draw(e){e.save(),this._applyStates(e);const t=this._currentMeasure.width-this._thickness,i=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this._isEnabled?this.color:this._disabledColor;const s=t*this._checkSizeRatio,r=i*this._checkSizeRatio;BD.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,s/2-this._thickness/2,r/2-this._thickness/2,e),e.fill()}e.restore()}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(this.isReadOnly||this.isChecked||(this.isChecked=!0),!0)}static AddRadioButtonWithHeader(e,t,i,s){const r=new WD;r.isVertical=!1,r.height="30px";const n=new iw;n.width="20px",n.height="20px",n.isChecked=i,n.color="green",n.group=t,n.onIsCheckedChangedObservable.add((e=>s(n,e))),r.addControl(n);const o=new UD;return o.text=e,o.width="180px",o.paddingLeft="5px",o.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,o.color="white",r.addControl(o),r}}qe([st()],iw.prototype,"thickness",null),qe([st()],iw.prototype,"group",void 0),qe([st()],iw.prototype,"checkSizeRatio",null),qe([st()],iw.prototype,"background",null),qe([st()],iw.prototype,"isChecked",null),ee("BABYLON.GUI.RadioButton",iw);class sw extends BD{get displayThumb(){return this._displayThumb}set displayThumb(e){this._displayThumb!==e&&(this._displayThumb=e,this._markAsDirty())}get step(){return this._step}set step(e){this._step!==e&&(this._step=e,this._markAsDirty())}get barOffset(){return this._barOffset.toString(this._host)}get barOffsetInPixels(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)}set barOffset(e){this._barOffset.toString(this._host)!==e&&this._barOffset.fromString(e)&&this._markAsDirty()}get thumbWidth(){return this._thumbWidth.toString(this._host)}get thumbWidthInPixels(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)}set thumbWidth(e){this._thumbWidth.toString(this._host)!==e&&this._thumbWidth.fromString(e)&&this._markAsDirty()}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get value(){return this._value}set value(e){e=Math.max(Math.min(e,this._maximum),this._minimum),this._value!==e&&(this._value=e,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))}get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get isThumbClamped(){return this._isThumbClamped}set isThumbClamped(e){this._isThumbClamped!==e&&(this._isThumbClamped=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbWidth=new PD(20,PD.UNITMODE_PIXEL,!1),this._minimum=0,this._maximum=100,this._value=50,this._isVertical=!1,this._barOffset=new PD(5,PD.UNITMODE_PIXEL,!1),this._isThumbClamped=!1,this._displayThumb=!0,this._step=0,this._lastPointerDownId=-1,this._effectiveBarOffset=0,this.onValueChangedObservable=new X,this._pointerIsDown=!1,this.isPointerBlocker=!0}_getTypeName(){return"BaseSlider"}_getThumbPosition(){return this.isVertical?(this.maximum-this.value)/(this.maximum-this.minimum)*this._backgroundBoxLength:(this.value-this.minimum)/(this.maximum-this.minimum)*this._backgroundBoxLength}_getThumbThickness(e){let t=0;switch(e){case"circle":t=this._thumbWidth.isPixel?Math.max(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host);break;case"rectangle":t=this._thumbWidth.isPixel?Math.min(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host)}return t}_prepareRenderingData(e){this._effectiveBarOffset=0,this._renderLeft=this._currentMeasure.left,this._renderTop=this._currentMeasure.top,this._renderWidth=this._currentMeasure.width,this._renderHeight=this._currentMeasure.height,this._backgroundBoxLength=Math.max(this._currentMeasure.width,this._currentMeasure.height),this._backgroundBoxThickness=Math.min(this._currentMeasure.width,this._currentMeasure.height),this._effectiveThumbThickness=this._getThumbThickness(e),this.displayThumb&&(this._backgroundBoxLength-=this._effectiveThumbThickness),this.isVertical&&this._currentMeasure.height=this._selectors.length))return this._selectors[e]}removeSelector(e){e<0||e>=this._selectors.length||(this._groupPanel.removeControl(this._selectors[e]),this._selectors.splice(e,1))}}class ow extends nw{addCheckbox(e,t=(e=>{}),i=!1){i=i||!1;const s=new HD;s.width="20px",s.height="20px",s.color="#364249",s.background="#CCCCCC",s.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,s.onIsCheckedChangedObservable.add((function(e){t(e)}));const r=BD.AddHeader(s,e,"200px",{isHorizontal:!0,controlFirst:!0});r.height="30px",r.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,r.left="4px",this.groupPanel.addControl(r),this.selectors.push(r),s.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(s.color=this.groupPanel.parent.parent.buttonColor,s.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class aw extends nw{constructor(){super(...arguments),this._selectNb=0}addRadio(e,t=(e=>{}),i=!1){const s=this._selectNb++,r=new iw;r.name=e,r.width="20px",r.height="20px",r.color="#364249",r.background="#CCCCCC",r.group=this.name,r.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,r.onIsCheckedChangedObservable.add((function(e){e&&t(s)}));const n=BD.AddHeader(r,e,"200px",{isHorizontal:!0,controlFirst:!0});n.height="30px",n.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,n.left="4px",this.groupPanel.addControl(n),this.selectors.push(n),r.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(r.color=this.groupPanel.parent.parent.buttonColor,r.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class lw extends nw{addSlider(e,t=(e=>{}),i="Units",s=0,r=0,n=0,o=(e=>0|e)){const a=new rw;a.name=i,a.value=n,a.minimum=s,a.maximum=r,a.width=.9,a.height="20px",a.color="#364249",a.background="#CCCCCC",a.borderColor="black",a.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,a.left="4px",a.paddingBottom="4px",a.onValueChangedObservable.add((function(e){a.parent.children[0].text=a.parent.children[0].name+": "+o(e)+" "+a.name,t(e)}));const l=BD.AddHeader(a,e+": "+o(n)+" "+i,"30px",{isHorizontal:!1,controlFirst:!1});l.height="60px",l.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,l.left="4px",l.children[0].name=e,this.groupPanel.addControl(l),this.selectors.push(l),this.groupPanel.parent&&this.groupPanel.parent.parent&&(a.color=this.groupPanel.parent.parent.buttonColor,a.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[0].name=t,this.selectors[e].children[0].text=t+": "+this.selectors[e].children[1].value+" "+this.selectors[e].children[1].name}_setSelectorLabelColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[1].background=t}}class hw extends kD{constructor(e,t=[]){if(super(e),this.name=e,this.groups=t,this._buttonColor="#364249",this._buttonBackground="#CCCCCC",this._headerColor="black",this._barColor="white",this._barHeight="2px",this._spacerHeight="20px",this._bars=new Array,this._groups=t,this.thickness=2,this._panel=new WD,this._panel.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._panel.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._panel.top=5,this._panel.left=5,this._panel.width=.95,t.length>0){for(let e=0;e0&&this._addSpacer(),this._panel.addControl(e.groupPanel),this._groups.push(e),e.groupPanel.children[0].color=this._headerColor;for(let t=0;t=this._groups.length)return;const t=this._groups[e];this._panel.removeControl(t.groupPanel),this._groups.splice(e,1),e=this._groups.length||(this._groups[t].groupPanel.children[0].text=e)}relabel(e,t,i){if(t<0||t>=this._groups.length)return;const s=this._groups[t];i<0||i>=s.selectors.length||s._setSelectorLabel(i,e)}removeFromGroupSelector(e,t){if(e<0||e>=this._groups.length)return;const i=this._groups[e];t<0||t>=i.selectors.length||i.removeSelector(t)}addToGroupCheckbox(e,t,i=(()=>{}),s=!1){e<0||e>=this._groups.length||this._groups[e].addCheckbox(t,i,s)}addToGroupRadio(e,t,i=(()=>{}),s=!1){e<0||e>=this._groups.length||this._groups[e].addRadio(t,i,s)}addToGroupSlider(e,t,i=(()=>{}),s="Units",r=0,n=0,o=0,a=(e=>0|e)){e<0||e>=this._groups.length||this._groups[e].addSlider(t,i,s,r,n,o,a)}}class cw extends LD{get freezeControls(){return this._freezeControls}set freezeControls(e){if(this._freezeControls===e)return;e||this._restoreMeasures(),this._freezeControls=!1;const t=this.host.getSize(),i=t.width,s=t.height,r=this.host.getContext(),n=new DD(0,0,i,s);this.host._numLayoutCalls=0,this.host._rootContainer._layout(n,r),e&&(this._updateMeasures(),this._useBuckets()&&this._makeBuckets()),this._freezeControls=e,this.host.markAsDirty()}get bucketWidth(){return this._bucketWidth}get bucketHeight(){return this._bucketHeight}setBucketSizes(e,t){this._bucketWidth=e,this._bucketHeight=t,this._useBuckets()?this._freezeControls&&this._makeBuckets():this._buckets={}}_useBuckets(){return this._bucketWidth>0&&this._bucketHeight>0}_makeBuckets(){this._buckets={},this._bucketLen=Math.ceil(this.widthInPixels/this._bucketWidth),this._dispatchInBuckets(this._children),this._oldLeft=null,this._oldTop=null}_dispatchInBuckets(e){for(let t=0;t0&&this._dispatchInBuckets(i._children)}}_updateMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left-=e,this._measureForChildren.top-=t,this._currentMeasure.left-=e,this._currentMeasure.top-=t,this._customData.origLeftForChildren=this._measureForChildren.left,this._customData.origTopForChildren=this._measureForChildren.top,this._customData.origLeft=this._currentMeasure.left,this._customData.origTop=this._currentMeasure.top,this._updateChildrenMeasures(this._children,e,t)}_updateChildrenMeasures(e,t,i){for(let s=0;s0&&this._updateChildrenMeasures(r._children,t,i)}}_restoreMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left=this._customData.origLeftForChildren+e,this._measureForChildren.top=this._customData.origTopForChildren+t,this._currentMeasure.left=this._customData.origLeft+e,this._currentMeasure.top=this._customData.origTop+t}constructor(e){super(e),this._freezeControls=!1,this._bucketWidth=0,this._bucketHeight=0,this._buckets={}}_getTypeName(){return"ScrollViewerWindow"}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._parentMeasure=e,this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this._measureForChildren.width=e.width,this._measureForChildren.height=e.height}_layout(e,t){return this._freezeControls?(this.invalidateRect(),!1):super._layout(e,t)}_scrollChildren(e,t,i){for(let s=0;s0&&this._scrollChildren(r._children,t,i)}}_scrollChildrenWithBuckets(e,t,i,s){const r=Math.max(0,Math.floor(-e/this._bucketWidth)),n=Math.floor((-e+this._parentMeasure.width-1)/this._bucketWidth),o=Math.floor((-t+this._parentMeasure.height-1)/this._bucketHeight);let a=Math.max(0,Math.floor(-t/this._bucketHeight));for(;a<=o;){for(let e=r;e<=n;++e){const t=a*this._bucketLen+e,r=this._buckets[t];if(r)for(let e=0;ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;s=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}serialize(e){super.serialize(e),this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient))}_parseFromContent(e,t){if(super._parseFromContent(e,t),e.backgroundGradient){const t=hs.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this.backgroundGradient=new t,this.backgroundGradient.parse(e.backgroundGradient)}}}qe([st()],uw.prototype,"borderColor",null),qe([st()],uw.prototype,"background",null),qe([st()],uw.prototype,"invertScrollDirection",null),ee("BABYLON.GUI.Scrollbar",uw);class dw extends sw{get invertScrollDirection(){return this._invertScrollDirection}set invertScrollDirection(e){this._invertScrollDirection=e}get backgroundImage(){return this._backgroundBaseImage}set backgroundImage(e){this._backgroundBaseImage!==e&&(this._backgroundBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._backgroundImage=e._rotate90(this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(this.num90RotationInVerticalMode,!0);this._backgroundImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._backgroundImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbImage(){return this._thumbBaseImage}set thumbImage(e){this._thumbBaseImage!==e&&(this._thumbBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._thumbImage=e._rotate90(-this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(-this.num90RotationInVerticalMode,!0);this._thumbImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbLength(){return this._thumbLength}set thumbLength(e){this._thumbLength!==e&&(this._thumbLength=e,this._markAsDirty())}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){this._thumbLength!==e&&(this._thumbHeight=e,this._markAsDirty())}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){this._barImageHeight!==e&&(this._barImageHeight=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._tempMeasure=new DD(0,0,0,0),this._invertScrollDirection=!1,this.num90RotationInVerticalMode=1}_getTypeName(){return"ImageScrollBar"}_getThumbThickness(){let e=0;return e=this._thumbWidth.isPixel?this._thumbWidth.getValue(this._host):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host),e}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isVertical?(this._tempMeasure.copyFromFloats(i+r*(1-this._barImageHeight)*.5,this._currentMeasure.top,r*this._barImageHeight,n),this._tempMeasure.height+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)):(this._tempMeasure.copyFromFloats(this._currentMeasure.left,s+n*(1-this._barImageHeight)*.5,r,n*this._barImageHeight),this._tempMeasure.width+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)),this._backgroundImage._draw(e)),this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset+this._currentMeasure.width*(1-this._thumbHeight)*.5,this._currentMeasure.top+t,this._currentMeasure.width*this._thumbHeight,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top+this._currentMeasure.height*(1-this._thumbHeight)*.5,this._effectiveThumbThickness,this._currentMeasure.height*this._thumbHeight),this._thumbImage&&(this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}_updateValueFromPointer(e,t){0!=this.rotation&&(this._invertTransformMatrix.transformCoordinates(e,t,this._transformedPosition),e=this._transformedPosition.x,t=this._transformedPosition.y);const i=this._invertScrollDirection?-1:1;this._first&&(this._first=!1,this._originX=e,this._originY=t,(ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;s=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}}qe([st()],dw.prototype,"num90RotationInVerticalMode",void 0),qe([st()],dw.prototype,"invertScrollDirection",null);class _w extends kD{get horizontalBar(){return this._horizontalBar}get verticalBar(){return this._verticalBar}addControl(e){return e?(this._window.addControl(e),this):this}removeControl(e){return this._window.removeControl(e),this}get children(){return this._window.children}_flagDescendantsAsMatrixDirty(){for(const e of this._children)e._markMatrixAsDirty()}get freezeControls(){return this._window.freezeControls}set freezeControls(e){this._window.freezeControls=e}get bucketWidth(){return this._window.bucketWidth}get bucketHeight(){return this._window.bucketHeight}setBucketSizes(e,t){this._window.setBucketSizes(e,t)}get forceHorizontalBar(){return this._forceHorizontalBar}set forceHorizontalBar(e){this._grid.setRowDefinition(1,e?this._barSize:0,!0),this._horizontalBar.isVisible=e,this._forceHorizontalBar=e}get forceVerticalBar(){return this._forceVerticalBar}set forceVerticalBar(e){this._grid.setColumnDefinition(1,e?this._barSize:0,!0),this._verticalBar.isVisible=e,this._forceVerticalBar=e}constructor(e,t){super(e),this._barSize=20,this._pointerIsOver=!1,this._wheelPrecision=.05,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._horizontalBarImageHeight=1,this._verticalBarImageHeight=1,this._oldWindowContentsWidth=0,this._oldWindowContentsHeight=0,this._forceHorizontalBar=!1,this._forceVerticalBar=!1,this._useImageBar=t||!1,this.onDirtyObservable.add((()=>{this._horizontalBarSpace.color=this.color,this._verticalBarSpace.color=this.color,this._dragSpace.color=this.color})),this.onPointerEnterObservable.add((()=>{this._pointerIsOver=!0})),this.onPointerOutObservable.add((()=>{this._pointerIsOver=!1})),this._grid=new QD,this._useImageBar?(this._horizontalBar=new dw,this._verticalBar=new dw):(this._horizontalBar=new uw,this._verticalBar=new uw),this._window=new cw("scrollViewer_window"),this._window.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._window.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._grid.addColumnDefinition(1),this._grid.addColumnDefinition(0,!0),this._grid.addRowDefinition(1),this._grid.addRowDefinition(0,!0),super.addControl(this._grid),this._grid.addControl(this._window,0,0),this._verticalBarSpace=new kD,this._verticalBarSpace.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._verticalBarSpace.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._verticalBarSpace.thickness=1,this._grid.addControl(this._verticalBarSpace,0,1),this._addBar(this._verticalBar,this._verticalBarSpace,!0,Math.PI),this._horizontalBarSpace=new kD,this._horizontalBarSpace.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._horizontalBarSpace.verticalAlignment=BD.VERTICAL_ALIGNMENT_TOP,this._horizontalBarSpace.thickness=1,this._grid.addControl(this._horizontalBarSpace,1,0),this._addBar(this._horizontalBar,this._horizontalBarSpace,!1,0),this._dragSpace=new kD,this._dragSpace.thickness=1,this._grid.addControl(this._dragSpace,1,1),this._grid.clipChildren=!1,this._useImageBar||(this.barColor="grey",this.barBackground="transparent")}resetWindow(){this._window.width="100%",this._window.height="100%"}_getTypeName(){return"ScrollViewer"}_buildClientSizes(){const e=this.host.idealRatio;this._window.parentClientWidth=this._currentMeasure.width-(this._verticalBar.isVisible||this.forceVerticalBar?this._barSize*e:0)-2*this.thickness,this._window.parentClientHeight=this._currentMeasure.height-(this._horizontalBar.isVisible||this.forceHorizontalBar?this._barSize*e:0)-2*this.thickness,this._clientWidth=this._window.parentClientWidth,this._clientHeight=this._window.parentClientHeight}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._buildClientSizes()}_postMeasure(){super._postMeasure(),this._updateScroller(),this._setWindowPosition(!1)}get wheelPrecision(){return this._wheelPrecision}set wheelPrecision(e){this._wheelPrecision!==e&&(e<0&&(e=0),e>1&&(e=1),this._wheelPrecision=e)}get scrollBackground(){return this._horizontalBarSpace.background}set scrollBackground(e){this._horizontalBarSpace.background!==e&&(this._horizontalBarSpace.background=e,this._verticalBarSpace.background=e)}get barColor(){return this._barColor}set barColor(e){this._barColor!==e&&(this._barColor=e,this._horizontalBar.color=e,this._verticalBar.color=e)}get thumbImage(){return this._barImage}set thumbImage(e){if(this._barImage===e)return;this._barImage=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbImage=e,i.thumbImage=e}get horizontalThumbImage(){return this._horizontalBarImage}set horizontalThumbImage(e){this._horizontalBarImage!==e&&(this._horizontalBarImage=e,this._horizontalBar.thumbImage=e)}get verticalThumbImage(){return this._verticalBarImage}set verticalThumbImage(e){this._verticalBarImage!==e&&(this._verticalBarImage=e,this._verticalBar.thumbImage=e)}get barSize(){return this._barSize}set barSize(e){this._barSize!==e&&(this._barSize=e,this._markAsDirty(),this._horizontalBar.isVisible&&this._grid.setRowDefinition(1,this._barSize,!0),this._verticalBar.isVisible&&this._grid.setColumnDefinition(1,this._barSize,!0))}get thumbLength(){return this._thumbLength}set thumbLength(e){if(this._thumbLength===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbLength=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbLength=e,i.thumbLength=e,this._markAsDirty()}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){if(this._thumbHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbHeight=e,i.thumbHeight=e,this._markAsDirty()}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){if(this._barImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._barImageHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.barImageHeight=e,i.barImageHeight=e,this._markAsDirty()}get horizontalBarImageHeight(){return this._horizontalBarImageHeight}set horizontalBarImageHeight(e){this._horizontalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._horizontalBarImageHeight=e,this._horizontalBar.barImageHeight=e,this._markAsDirty())}get verticalBarImageHeight(){return this._verticalBarImageHeight}set verticalBarImageHeight(e){this._verticalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._verticalBarImageHeight=e,this._verticalBar.barImageHeight=e,this._markAsDirty())}get barBackground(){return this._barBackground}set barBackground(e){if(this._barBackground===e)return;this._barBackground=e;const t=this._horizontalBar,i=this._verticalBar;t.background=e,i.background=e,this._dragSpace.background=e}get barImage(){return this._barBackgroundImage}set barImage(e){this._barBackgroundImage=e;const t=this._horizontalBar,i=this._verticalBar;t.backgroundImage=e,i.backgroundImage=e}get horizontalBarImage(){return this._horizontalBarBackgroundImage}set horizontalBarImage(e){this._horizontalBarBackgroundImage=e,this._horizontalBar.backgroundImage=e}get verticalBarImage(){return this._verticalBarBackgroundImage}set verticalBarImage(e){this._verticalBarBackgroundImage=e,this._verticalBar.backgroundImage=e}_setWindowPosition(e=!0){const t=this.host.idealRatio,i=this._window._currentMeasure.width,s=this._window._currentMeasure.height;if(!e&&this._oldWindowContentsWidth===i&&this._oldWindowContentsHeight===s)return;this._oldWindowContentsWidth=i,this._oldWindowContentsHeight=s;const r=this._clientWidth-i,n=this._clientHeight-s,o=this._horizontalBar.value/t*r+"px",a=this._verticalBar.value/t*n+"px";o!==this._window.left&&(this._window.left=o,this.freezeControls||(this._rebuildLayout=!0)),a!==this._window.top&&(this._window.top=a,this.freezeControls||(this._rebuildLayout=!0))}_updateScroller(){const e=this._window._currentMeasure.width,t=this._window._currentMeasure.height;this._horizontalBar.isVisible&&e<=this._clientWidth&&!this.forceHorizontalBar?(this._grid.setRowDefinition(1,0,!0),this._horizontalBar.isVisible=!1,this._horizontalBar.value=0,this._rebuildLayout=!0):!this._horizontalBar.isVisible&&(e>this._clientWidth||this.forceHorizontalBar)&&(this._grid.setRowDefinition(1,this._barSize,!0),this._horizontalBar.isVisible=!0,this._rebuildLayout=!0),this._verticalBar.isVisible&&t<=this._clientHeight&&!this.forceVerticalBar?(this._grid.setColumnDefinition(1,0,!0),this._verticalBar.isVisible=!1,this._verticalBar.value=0,this._rebuildLayout=!0):!this._verticalBar.isVisible&&(t>this._clientHeight||this.forceVerticalBar)&&(this._grid.setColumnDefinition(1,this._barSize,!0),this._verticalBar.isVisible=!0,this._rebuildLayout=!0),this._buildClientSizes();const i=this.host.idealRatio;this._horizontalBar.thumbWidth=.9*this._thumbLength*(this._clientWidth/i)+"px",this._verticalBar.thumbWidth=.9*this._thumbLength*(this._clientHeight/i)+"px"}_link(e){super._link(e),this._attachWheel()}_addBar(e,t,i,s){e.paddingLeft=0,e.width="100%",e.height="100%",e.barOffset=0,e.value=0,e.maximum=1,e.horizontalAlignment=BD.HORIZONTAL_ALIGNMENT_CENTER,e.verticalAlignment=BD.VERTICAL_ALIGNMENT_CENTER,e.isVertical=i,e.rotation=s,e.isVisible=!1,t.addControl(e),e.onValueChangedObservable.add((()=>{this._setWindowPosition()}))}_attachWheel(){this._host&&!this._onWheelObserver&&(this._onWheelObserver=this.onWheelObservable.add((e=>{this._pointerIsOver&&!this.isReadOnly&&(1==this._verticalBar.isVisible&&(e.y<0&&this._verticalBar.value>0?this._verticalBar.value-=this._wheelPrecision:e.y>0&&this._verticalBar.value0&&this._horizontalBar.value>0&&(this._horizontalBar.value-=this._wheelPrecision)))})))}_renderHighlightSpecific(e){this.isHighlighted&&(super._renderHighlightSpecific(e),this._grid._renderHighlightSpecific(e),e.restore())}dispose(){this.onWheelObservable.remove(this._onWheelObserver),this._onWheelObserver=null,super.dispose()}}qe([st()],_w.prototype,"wheelPrecision",null),qe([st()],_w.prototype,"scrollBackground",null),qe([st()],_w.prototype,"barColor",null),qe([st()],_w.prototype,"barSize",null),qe([st()],_w.prototype,"barBackground",null),ee("BABYLON.GUI.ScrollViewer",_w);class pw extends kD{get group(){return this._group}set group(e){this._group!==e&&(this._group=e)}get isActive(){return this._isActive}set isActive(e){this._isActive!==e&&(this._isActive=e,this._isActive?this.toActiveAnimation?.():this.toInactiveAnimation?.(),this._markAsDirty(),this.onIsActiveChangedObservable.notifyObservers(e),this._isActive&&this._host&&this._group&&this._host.executeOnAllControls((e=>{if("ToggleButton"===e.typeName){if(e===this)return;const t=e;t.group===this.group&&(t.isActive=!1)}})))}constructor(e,t){super(e),this.name=e,this.onIsActiveChangedObservable=new X,this.delegatePickingToChildren=!1,this._isActive=!1,this.group=t??"",this.thickness=0,this.isPointerBlocker=!0;let i=null;this.toActiveAnimation=()=>{this.thickness=1},this.toInactiveAnimation=()=>{this.thickness=0},this.pointerEnterActiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutActiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownActiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpActiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05},this.pointerEnterInactiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutInactiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownInactiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpInactiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"ToggleButton"}_processPicking(e,t,i,s,r,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(s,e,t,i,r,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(this.isReadOnly||(this._isActive?this.pointerEnterActiveAnimation&&this.pointerEnterActiveAnimation():this.pointerEnterInactiveAnimation&&this.pointerEnterInactiveAnimation()),!0)}_onPointerOut(e,t,i=!1){this.isReadOnly||(this._isActive?this.pointerOutActiveAnimation&&this.pointerOutActiveAnimation():this.pointerOutInactiveAnimation&&this.pointerOutInactiveAnimation()),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(this.isReadOnly||(this._isActive?this.pointerDownActiveAnimation&&this.pointerDownActiveAnimation():this.pointerDownInactiveAnimation&&this.pointerDownInactiveAnimation()),!0)}_onPointerUp(e,t,i,s,r,n){this.isReadOnly||(this._isActive?this.pointerUpActiveAnimation&&this.pointerUpActiveAnimation():this.pointerUpInactiveAnimation&&this.pointerUpInactiveAnimation()),super._onPointerUp(e,t,i,s,r,n)}}ee("BABYLON.GUI.ToggleButton",pw);class fw{}class mw extends WD{constructor(){super(...arguments),this.onKeyPressObservable=new X,this.defaultButtonWidth="40px",this.defaultButtonHeight="40px",this.defaultButtonPaddingLeft="2px",this.defaultButtonPaddingRight="2px",this.defaultButtonPaddingTop="2px",this.defaultButtonPaddingBottom="2px",this.defaultButtonColor="#DDD",this.defaultButtonBackground="#070707",this.shiftButtonColor="#7799FF",this.selectedShiftThickness=1,this.shiftState=0,this._currentlyConnectedInputText=null,this._connectedInputTexts=[],this._onKeyPressObserver=null}_getTypeName(){return"VirtualKeyboard"}_createKey(e,t){const i=zD.CreateSimpleButton(e,e);return i.width=t&&t.width?t.width:this.defaultButtonWidth,i.height=t&&t.height?t.height:this.defaultButtonHeight,i.color=t&&t.color?t.color:this.defaultButtonColor,i.background=t&&t.background?t.background:this.defaultButtonBackground,i.paddingLeft=t&&t.paddingLeft?t.paddingLeft:this.defaultButtonPaddingLeft,i.paddingRight=t&&t.paddingRight?t.paddingRight:this.defaultButtonPaddingRight,i.paddingTop=t&&t.paddingTop?t.paddingTop:this.defaultButtonPaddingTop,i.paddingBottom=t&&t.paddingBottom?t.paddingBottom:this.defaultButtonPaddingBottom,i.thickness=0,i.isFocusInvisible=!0,i.shadowColor=this.shadowColor,i.shadowBlur=this.shadowBlur,i.shadowOffsetX=this.shadowOffsetX,i.shadowOffsetY=this.shadowOffsetY,i.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e)})),i}addKeysRow(e,t){const i=new WD;i.isVertical=!1,i.isFocusInvisible=!0;let s=null;for(let r=0;rs.heightInPixels)&&(s=o),i.addControl(o)}i.height=s?s.height:this.defaultButtonHeight,this.addControl(i)}applyShiftState(e){if(this.children)for(let t=0;t1?this.selectedShiftThickness:0),r.text=e>0?r.text.toUpperCase():r.text.toLowerCase()}}}get connectedInputText(){return this._currentlyConnectedInputText}connect(e){if(this._connectedInputTexts.some((t=>t.input===e)))return;null===this._onKeyPressObserver&&(this._onKeyPressObserver=this.onKeyPressObservable.add((e=>{if(this._currentlyConnectedInputText){switch(this._currentlyConnectedInputText._host.focusedControl=this._currentlyConnectedInputText,e){case"⇧":return this.shiftState++,this.shiftState>2&&(this.shiftState=0),void this.applyShiftState(this.shiftState);case"←":return void(this._currentlyConnectedInputText instanceof qD?this._currentlyConnectedInputText.alternativeProcessKey("Backspace"):this._currentlyConnectedInputText.processKey(8));case"↵":return void(this._currentlyConnectedInputText instanceof qD?this._currentlyConnectedInputText.alternativeProcessKey("Enter"):this._currentlyConnectedInputText.processKey(13))}this._currentlyConnectedInputText instanceof qD?this._currentlyConnectedInputText.alternativeProcessKey("",this.shiftState?e.toUpperCase():e):this._currentlyConnectedInputText.processKey(-1,this.shiftState?e.toUpperCase():e),1===this.shiftState&&(this.shiftState=0,this.applyShiftState(this.shiftState))}}))),this.isVisible=!1,this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this;const t=e.onFocusObservable.add((()=>{this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this,this.isVisible=!0})),i=e.onBlurObservable.add((()=>{e._connectedVirtualKeyboard=null,this._currentlyConnectedInputText=null,this.isVisible=!1}));this._connectedInputTexts.push({input:e,onBlurObserver:i,onFocusObserver:t})}disconnect(e){if(e){const t=this._connectedInputTexts.filter((t=>t.input===e));1===t.length&&(this._removeConnectedInputObservables(t[0]),this._connectedInputTexts=this._connectedInputTexts.filter((t=>t.input!==e)),this._currentlyConnectedInputText===e&&(this._currentlyConnectedInputText=null))}else this._connectedInputTexts.forEach((e=>{this._removeConnectedInputObservables(e)})),this._connectedInputTexts.length=0;0===this._connectedInputTexts.length&&(this._currentlyConnectedInputText=null,this.onKeyPressObservable.remove(this._onKeyPressObserver),this._onKeyPressObserver=null)}_removeConnectedInputObservables(e){e.input._connectedVirtualKeyboard=null,e.input.onFocusObservable.remove(e.onFocusObserver),e.input.onBlurObservable.remove(e.onBlurObserver)}dispose(){super.dispose(),this.disconnect()}static CreateDefaultLayout(e){const t=new mw(e);return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","←"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","↵"]),t.addKeysRow(["⇧","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t}_parseFromContent(e,t){super._parseFromContent(e,t);for(const e of this.children)if("StackPanel"===e.getClassName()){const t=e;for(const e of t.children)"Button"===e.getClassName()&&e.name&&e.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e.name)}))}}}ee("BABYLON.GUI.VirtualKeyboard",mw);class gw extends BD{get displayMinorLines(){return this._displayMinorLines}set displayMinorLines(e){this._displayMinorLines!==e&&(this._displayMinorLines=e,this._markAsDirty())}get displayMajorLines(){return this._displayMajorLines}set displayMajorLines(e){this._displayMajorLines!==e&&(this._displayMajorLines=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth=e,this._markAsDirty()}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight=e,this._markAsDirty()}get minorLineTickness(){return this._minorLineTickness}set minorLineTickness(e){this._minorLineTickness=e,this._markAsDirty()}get minorLineColor(){return this._minorLineColor}set minorLineColor(e){this._minorLineColor=e,this._markAsDirty()}get majorLineTickness(){return this._majorLineTickness}set majorLineTickness(e){this._majorLineTickness=e,this._markAsDirty()}get majorLineColor(){return this._majorLineColor}set majorLineColor(e){this._majorLineColor=e,this._markAsDirty()}get majorLineFrequency(){return this._majorLineFrequency}set majorLineFrequency(e){this._majorLineFrequency=e,this._markAsDirty()}constructor(e){super(e),this.name=e,this._cellWidth=20,this._cellHeight=20,this._minorLineTickness=1,this._minorLineColor="DarkGray",this._majorLineTickness=2,this._majorLineColor="White",this._majorLineFrequency=5,this._background="Black",this._displayMajorLines=!0,this._displayMinorLines=!0}_draw(e){if(e.save(),this._applyStates(e),this._isEnabled){this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height));const t=this._currentMeasure.width/this._cellWidth,i=this._currentMeasure.height/this._cellHeight,s=this._currentMeasure.left+this._currentMeasure.width/2,r=this._currentMeasure.top+this._currentMeasure.height/2;if(this._displayMinorLines){e.strokeStyle=this._minorLineColor,e.lineWidth=this._minorLineTickness;for(let i=-t/2+1;ithis._markAsDirty())),this._markAsDirty())}get valueBarImage(){return this._valueBarImage}set valueBarImage(e){this._valueBarImage!==e&&(this._valueBarImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}get thumbImage(){return this._thumbImage}set thumbImage(e){this._thumbImage!==e&&(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}constructor(e){super(e),this.name=e,this._tempMeasure=new DD(0,0,0,0)}_getTypeName(){return"ImageBasedSlider"}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isThumbClamped&&this.displayThumb&&(this.isVertical?this._tempMeasure.height+=this._effectiveThumbThickness:this._tempMeasure.width+=this._effectiveThumbThickness),this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure),this._backgroundImage._draw(e)),this._valueBarImage&&(this.isVertical?this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s+t,r,n-t+this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(i,s+t,r,n-t):this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s,t+this._effectiveThumbThickness/2,n):this._tempMeasure.copyFromFloats(i,s,t,n),this._valueBarImage._currentMeasure.copyFrom(this._tempMeasure),this._valueBarImage._draw(e)),this.displayThumb&&(this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset,this._currentMeasure.top+t,this._currentMeasure.width,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top,this._effectiveThumbThickness,this._currentMeasure.height),this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}serialize(e){super.serialize(e);const t={},i={},s={};this.backgroundImage.serialize(t),this.thumbImage.serialize(i),this.valueBarImage.serialize(s),e.backgroundImage=t,e.thumbImage=i,e.valueBarImage=s}_parseFromContent(e,t){super._parseFromContent(e,t),this.backgroundImage=GD.Parse(e.backgroundImage,t),this.thumbImage=GD.Parse(e.thumbImage,t),this.valueBarImage=GD.Parse(e.valueBarImage,t)}}qe([st()],vw.prototype,"displayThumb",null),ee("BABYLON.GUI.ImageBasedSlider",vw);const xw="Statics";BD.AddHeader=function(e,t,i,s){const r=new WD("panel"),n=!s||s.isHorizontal,o=!s||s.controlFirst;r.isVertical=!n;const a=new UD("header");return a.text=t,a.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,n?a.width=i:a.height=i,o?(r.addControl(e),r.addControl(a),a.paddingLeft="5px"):(r.addControl(a),r.addControl(e),a.paddingRight="5px"),a.shadowBlur=e.shadowBlur,a.shadowColor=e.shadowColor,a.shadowOffsetX=e.shadowOffsetX,a.shadowOffsetY=e.shadowOffsetY,r};class bw{constructor(){this._colorStops=[],this._gradientDirty=!0}_addColorStopsToCanvasGradient(){for(const e of this._colorStops)this._canvasGradient.addColorStop(e.offset,e.color)}getCanvasGradient(e){return(this._gradientDirty||this._context!==e)&&(this._context=e,this._canvasGradient=this._createCanvasGradient(e),this._addColorStopsToCanvasGradient(),this._gradientDirty=!1),this._canvasGradient}addColorStop(e,t){this._colorStops.push({offset:e,color:t}),this._gradientDirty=!0}removeColorStop(e){this._colorStops=this._colorStops.filter((t=>t.offset!==e)),this._gradientDirty=!0}clearColorStops(){this._colorStops=[],this._gradientDirty=!0}get colorStops(){return this._colorStops}getClassName(){return"BaseGradient"}serialize(e){e.colorStops=this._colorStops,e.className=this.getClassName()}parse(e){this._colorStops=e.colorStops}}class Tw extends bw{constructor(e,t,i,s){super(),this._x0=e??0,this._y0=t??0,this._x1=i??0,this._y1=s??0}_createCanvasGradient(e){return e.createLinearGradient(this._x0,this._y0,this._x1,this._y1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}getClassName(){return"LinearGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.x1=this._x1,e.y1=this._y1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._x1=e.x1,this._y1=e.y1}}ee("BABYLON.GUI.LinearGradient",Tw);class yw extends bw{constructor(e,t,i,s,r,n){super(),this._x0=e??0,this._y0=t??0,this._r0=i??0,this._x1=s??0,this._y1=r??0,this._r1=n??0}_createCanvasGradient(e){return e.createRadialGradient(this._x0,this._y0,this._r0,this._x1,this._y1,this._r1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}get r0(){return this._r0}get r1(){return this._r1}getClassName(){return"RadialGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.r0=this._r0,e.x1=this._x1,e.y1=this._y1,e.r1=this._r1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._r0=e.r0,this._x1=e.x1,this._y1=e.y1,this._r1=e.r1}}ee("BABYLON.GUI.RadialGradient",yw);class Sw{constructor(e){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new PD(18,PD.UNITMODE_PIXEL,!1),this.onChangedObservable=new X,this._host=e}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&this.onChangedObservable.notifyObservers(this)}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.onChangedObservable.notifyObservers(this))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.onChangedObservable.notifyObservers(this))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.onChangedObservable.notifyObservers(this))}dispose(){this.onChangedObservable.clear()}}class Cw extends Sc{get numLayoutCalls(){return this._numLayoutCalls}get numRenderCalls(){return this._numRenderCalls}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this._onResize())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this.markAsDirty())}get idealWidth(){return this._idealWidth}set idealWidth(e){this._idealWidth!==e&&(this._idealWidth=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get idealHeight(){return this._idealHeight}set idealHeight(e){this._idealHeight!==e&&(this._idealHeight=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get useSmallestIdeal(){return this._useSmallestIdeal}set useSmallestIdeal(e){this._useSmallestIdeal!==e&&(this._useSmallestIdeal=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get renderAtIdealSize(){return this._renderAtIdealSize}set renderAtIdealSize(e){this._renderAtIdealSize!==e&&(this._renderAtIdealSize=e,this._onResize())}get idealRatio(){let e=0,t=0;return this._idealWidth&&(e=this.getSize().width/this._idealWidth),this._idealHeight&&(t=this.getSize().height/this._idealHeight),this._useSmallestIdeal&&this._idealWidth&&this._idealHeight?window.innerWidtht.typeName===e))}getControlByName(e){return this._getControlByKey("name",e)}_getControlByKey(e,t){return this._rootContainer.getDescendants().find((i=>i[e]===t))||null}get focusedControl(){return this._focusedControl}set focusedControl(e){this._focusedControl!=e&&(this._focusedControl&&this._focusedControl.onBlur(),e&&e.onFocus(),this._focusedControl=e)}get isForeground(){return!this.layer||!this.layer.isBackground}set isForeground(e){this.layer&&this.layer.isBackground!==!e&&(this.layer.isBackground=!e)}get clipboardData(){return this._clipboardData}set clipboardData(e){this._clipboardData=e}constructor(e,t=0,i=0,s,r=!1,n=Vo.NEAREST_SAMPLINGMODE,o=!0){super(e,{width:t,height:i},s,r,n,Yd.TEXTUREFORMAT_RGBA,o),this.onGuiReadyObservable=new X,this._isDirty=!1,this._rootContainer=new LD("root"),this._lastControlOver={},this._lastControlDown={},this._capturingControl={},this._linkedControls=new Array,this._isFullscreen=!1,this._fullscreenViewport=new jr(0,0,1,1),this._idealWidth=0,this._idealHeight=0,this._useSmallestIdeal=!1,this._renderAtIdealSize=!1,this._blockNextFocusCheck=!1,this._renderScale=1,this._cursorChanged=!1,this._defaultMousePointerId=0,this._rootChildrenHaveChanged=!1,this._capturedPointerIds=new Set,this._numLayoutCalls=0,this._numRenderCalls=0,this._clipboardData="",this.onClipboardObservable=new X,this.onControlPickedObservable=new X,this.onBeginLayoutObservable=new X,this.onEndLayoutObservable=new X,this.onBeginRenderObservable=new X,this.onEndRenderObservable=new X,this.premulAlpha=!1,this.applyYInversionOnUpdate=!0,this.skipBlockEvents=0,this.checkPointerEveryFrame=!1,this._useInvalidateRectOptimization=!0,this._invalidatedRectangle=null,this._clearMeasure=new DD(0,0,0,0),this._onClipboardCopy=e=>{const t=e,i=new Zf(qf.COPY,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardCut=e=>{const t=e,i=new Zf(qf.CUT,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardPaste=e=>{const t=e,i=new Zf(qf.PASTE,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this.parseContent=this.parseSerializedObject,(s=this.getScene())&&this._texture&&(this.applyYInversionOnUpdate=o,this._rootElement=s.getEngine().getInputElement(),this._renderObserver=s.onBeforeCameraRenderObservable.add((e=>this._checkUpdate(e))),this._controlAddedObserver=this._rootContainer.onControlAddedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._controlRemovedObserver=this._rootContainer.onControlRemovedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._preKeyboardObserver=s.onPreKeyboardObservable.add((e=>{this._focusedControl&&(e.type===Ns.KEYDOWN&&this._focusedControl.processKeyboard(e.event),e.skipOnPointerObservable=!0)})),this._rootContainer._link(this),this.hasAlpha=!0,t&&i||(this._resizeObserver=s.getEngine().onResizeObservable.add((()=>this._onResize())),this._onResize()),this._texture.isReady=!0)}getClassName(){return"AdvancedDynamicTexture"}executeOnAllControls(e,t){t||(t=this._rootContainer),e(t);for(const i of t.children)i.children?this.executeOnAllControls(e,i):e(i)}get useInvalidateRectOptimization(){return this._useInvalidateRectOptimization}set useInvalidateRectOptimization(e){this._useInvalidateRectOptimization=e}invalidateRect(e,t,i,s){if(this._useInvalidateRectOptimization)if(this._invalidatedRectangle){const r=Math.ceil(Math.max(this._invalidatedRectangle.left+this._invalidatedRectangle.width-1,i)),n=Math.ceil(Math.max(this._invalidatedRectangle.top+this._invalidatedRectangle.height-1,s));this._invalidatedRectangle.left=Math.floor(Math.min(this._invalidatedRectangle.left,e)),this._invalidatedRectangle.top=Math.floor(Math.min(this._invalidatedRectangle.top,t)),this._invalidatedRectangle.width=r-this._invalidatedRectangle.left+1,this._invalidatedRectangle.height=n-this._invalidatedRectangle.top+1}else this._invalidatedRectangle=new DD(e,t,i-e+1,s-t+1)}markAsDirty(){this._isDirty=!0}createStyle(){return new Sw(this)}addControl(e){return this._rootContainer.addControl(e),this}removeControl(e){return this._rootContainer.removeControl(e),this}moveToNonOverlappedPosition(e,t=1,i=1){let s;if(Array.isArray(e))s=e;else{const t=this.getDescendants(!0);s=void 0===e?t.filter((e=>void 0!==e.overlapGroup)):t.filter((t=>t.overlapGroup===e))}s.forEach((e=>{let r=ue.Zero();const n=new ue(e.centerX,e.centerY);s.forEach((t=>{if(e!==t&&Cw._Overlaps(e,t)){const e=n.subtract(new ue(t.centerX,t.centerY)),s=e.length();s>0&&(r=r.add(e.normalize().scale(i/s)))}})),r.length()>0&&(r=r.normalize().scale(t*(e.overlapDeltaMultiplier??1)),e.linkOffsetXInPixels+=r.x,e.linkOffsetYInPixels+=r.y)}))}dispose(){const e=this.getScene();e&&(this._rootElement=null,e.onBeforeCameraRenderObservable.remove(this._renderObserver),this._resizeObserver&&e.getEngine().onResizeObservable.remove(this._resizeObserver),this._prePointerObserver&&e.onPrePointerObservable.remove(this._prePointerObserver),this._sceneRenderObserver&&e.onBeforeRenderObservable.remove(this._sceneRenderObserver),this._pointerObserver&&e.onPointerObservable.remove(this._pointerObserver),this._preKeyboardObserver&&e.onPreKeyboardObservable.remove(this._preKeyboardObserver),this._canvasPointerOutObserver&&e.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver),this._canvasBlurObserver&&e.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver),this._controlAddedObserver&&this._rootContainer.onControlAddedObservable.remove(this._controlAddedObserver),this._controlRemovedObserver&&this._rootContainer.onControlRemovedObservable.remove(this._controlRemovedObserver),this._layerToDispose&&(this._layerToDispose.texture=null,this._layerToDispose.dispose(),this._layerToDispose=null),this._rootContainer.dispose(),this.onClipboardObservable.clear(),this.onControlPickedObservable.clear(),this.onBeginRenderObservable.clear(),this.onEndRenderObservable.clear(),this.onBeginLayoutObservable.clear(),this.onEndLayoutObservable.clear(),this.onGuiReadyObservable.clear(),super.dispose())}_onResize(){const e=this.getScene();if(!e)return;const t=e.getEngine(),i=this.getSize();let s=t.getRenderWidth()*this._renderScale,r=t.getRenderHeight()*this._renderScale;this._renderAtIdealSize&&(this._idealWidth?(r=r*this._idealWidth/s,s=this._idealWidth):this._idealHeight&&(s=s*this._idealHeight/r,r=this._idealHeight)),i.width===s&&i.height===r||(this.scaleTo(s,r),this.markAsDirty(),(this._idealWidth||this._idealHeight)&&this._rootContainer._markAllAsDirty()),this.invalidateRect(0,0,i.width-1,i.height-1)}_getGlobalViewport(){const e=this.getSize(),t=this._fullscreenViewport.toGlobal(e.width,e.height),i=Math.round(t.width*(1/this.rootContainer.scaleX)),s=Math.round(t.height*(1/this.rootContainer.scaleY));return t.x+=(t.width-i)/2,t.y+=(t.height-s)/2,t.width=i,t.height=s,t}getProjectedPosition(e,t){const i=this.getProjectedPositionWithZ(e,t);return new ue(i.x,i.y)}getProjectedPositionWithZ(e,t){const i=this.getScene();if(!i)return de.Zero();const s=this._getGlobalViewport(),r=de.Project(e,t,i.getTransformMatrix(),s);return new de(r.x,r.y,r.z)}_checkUpdate(e,t){if(!this._layerToDispose||e.layerMask&this._layerToDispose.layerMask){if(this._isFullscreen&&this._linkedControls.length){const e=this.getScene();if(!e)return;const t=this._getGlobalViewport();for(const i of this._linkedControls){if(!i.isVisible)continue;const s=i._linkedMesh;if(!s||s.isDisposed()){hs.SetImmediate((()=>{i.linkWithMesh(null)}));continue}const r=s.getBoundingInfo?s.getBoundingInfo().boundingSphere.center:de.ZeroReadOnly,n=de.Project(r,s.getWorldMatrix(),e.getTransformMatrix(),t);n.z<0||n.z>1?i.notRenderable=!0:(i.notRenderable=!1,this.useInvalidateRectOptimization&&i.invalidateRect(),i._moveToProjectedPosition(n))}}(this._isDirty||this._rootContainer.isDirty)&&(this._isDirty=!1,this._render(t),t||this.update(this.applyYInversionOnUpdate,this.premulAlpha,Cw.AllowGPUOptimizations))}}_render(e){const t=this.getSize(),i=t.width,s=t.height,r=this.getContext();if(r.font="18px Arial",r.strokeStyle="white",this.onGuiReadyObservable.hasObservers()&&this._checkGuiIsReady(),this._rootChildrenHaveChanged){const e=this.getScene()?.activeCamera;e&&(this._rootChildrenHaveChanged=!1,this._checkUpdate(e,!0))}this.onBeginLayoutObservable.notifyObservers(this);const n=new DD(0,0,i,s);this._numLayoutCalls=0,this._rootContainer._layout(n,r),this.onEndLayoutObservable.notifyObservers(this),this._isDirty=!1,e||(this._invalidatedRectangle?this._clearMeasure.copyFrom(this._invalidatedRectangle):this._clearMeasure.copyFromFloats(0,0,i,s),r.clearRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),this._background&&(r.save(),r.fillStyle=this._background,r.fillRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),r.restore()),this.onBeginRenderObservable.notifyObservers(this),this._numRenderCalls=0,this._rootContainer._render(r,this._invalidatedRectangle),this.onEndRenderObservable.notifyObservers(this),this._invalidatedRectangle=null)}_changeCursor(e){this._rootElement&&(this._rootElement.style.cursor=e,this._cursorChanged=!0)}_registerLastControlDown(e,t){this._lastControlDown[t]=e,this.onControlPickedObservable.notifyObservers(e)}_doPicking(e,t,i,s,r,n,o,a){const l=this.getScene();if(!l)return;const h=l.getEngine(),c=this.getSize();if(this._isFullscreen){const i=l.cameraToUseForPointers||l.activeCamera;if(!i)return;const s=i.viewport;e*=c.width/(h.getRenderWidth()*s.width),t*=c.height/(h.getRenderHeight()*s.height)}if(this._capturingControl[r])return this._capturingControl[r].isPointerBlocker&&(this._shouldBlockPointer=!0),void this._capturingControl[r]._processObservables(s,e,t,i,r,n);this._cursorChanged=!1,this._rootContainer._processPicking(e,t,i,s,r,n,o,a)||(l.doNotHandleCursors||this._changeCursor(""),s===Ms.POINTERMOVE&&this._lastControlOver[r]&&(this._lastControlOver[r]._onPointerOut(this._lastControlOver[r],i),delete this._lastControlOver[r])),this._cursorChanged||l.doNotHandleCursors||this._changeCursor(""),this._manageFocus()}_cleanControlAfterRemovalFromList(e,t){for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&e[i]===t&&delete e[i]}_cleanControlAfterRemoval(e){this._cleanControlAfterRemovalFromList(this._lastControlDown,e),this._cleanControlAfterRemovalFromList(this._lastControlOver,e)}pick(e,t,i=null){this._isFullscreen&&this._scene&&this._translateToPicking(this._scene,new jr(0,0,0,0),i,e,t)}_translateToPicking(e,t,i,s=e.pointerX,r=e.pointerY){const n=e.cameraToUseForPointers||e.activeCamera,o=e.getEngine(),a=e.cameraToUseForPointers;if(n)if(n.rigCameras.length){const i=new jr(0,0,1,1);n.rigCameras.forEach((n=>{n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),i);const a=s/o.getHardwareScalingLevel()-i.x,l=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-i.y-i.height);a<0||l<0||s>i.width||r>i.height||(e.cameraToUseForPointers=n,t.x=i.x,t.y=i.y,t.width=i.width,t.height=i.height)}))}else n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),t);else t.x=0,t.y=0,t.width=o.getRenderWidth(),t.height=o.getRenderHeight();const l=s/o.getHardwareScalingLevel()-t.x,h=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-t.y-t.height);if(this._shouldBlockPointer=!1,i){const e=i.event.pointerId||this._defaultMousePointerId;this._doPicking(l,h,i,i.type,e,i.event.button,i.event.deltaX,i.event.deltaY),(this._shouldBlockPointer&&!(i.type&this.skipBlockEvents)||this._capturingControl[e])&&(i.skipOnPointerObservable=!0)}else this._doPicking(l,h,null,Ms.POINTERMOVE,this._defaultMousePointerId,0);e.cameraToUseForPointers=a}attach(){const e=this.getScene();if(!e)return;const t=new jr(0,0,0,0);this._prePointerObserver=e.onPrePointerObservable.add((i=>{if((!e.isPointerCaptured(i.event.pointerId)||i.type!==Ms.POINTERUP||this._capturedPointerIds.has(i.event.pointerId))&&(i.type===Ms.POINTERMOVE||i.type===Ms.POINTERUP||i.type===Ms.POINTERDOWN||i.type===Ms.POINTERWHEEL)){if(i.type===Ms.POINTERMOVE){if(e.isPointerCaptured(i.event.pointerId))return;i.event.pointerId&&(this._defaultMousePointerId=i.event.pointerId)}this._translateToPicking(e,t,i)}})),this._attachPickingToSceneRender(e,(()=>this._translateToPicking(e,t,null)),!1),this._attachToOnPointerOut(e),this._attachToOnBlur(e)}registerClipboardEvents(){self.addEventListener("copy",this._onClipboardCopy,!1),self.addEventListener("cut",this._onClipboardCut,!1),self.addEventListener("paste",this._onClipboardPaste,!1)}unRegisterClipboardEvents(){self.removeEventListener("copy",this._onClipboardCopy),self.removeEventListener("cut",this._onClipboardCut),self.removeEventListener("paste",this._onClipboardPaste)}_transformUvs(e){const t=this.getTextureMatrix();let i;if(t.isIdentityAs3x2())i=e;else{const s=ge.Matrix[0];t.getRowToRef(0,ge.Vector4[0]),t.getRowToRef(1,ge.Vector4[1]),t.getRowToRef(2,ge.Vector4[2]);const r=ge.Vector4[0],n=ge.Vector4[1],o=ge.Vector4[2];s.setRowFromFloats(0,r.x,r.y,0,0),s.setRowFromFloats(1,n.x,n.y,0,0),s.setRowFromFloats(2,0,0,1,0),s.setRowFromFloats(3,o.x,o.y,0,1),i=ge.Vector2[0],ue.TransformToRef(e,s,i)}if((this.wrapU===Vo.WRAP_ADDRESSMODE||this.wrapU===Vo.MIRROR_ADDRESSMODE)&&i.x>1){let e=i.x-Math.trunc(i.x);this.wrapU===Vo.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.x=e}if((this.wrapV===Vo.WRAP_ADDRESSMODE||this.wrapV===Vo.MIRROR_ADDRESSMODE)&&i.y>1){let e=i.y-Math.trunc(i.y);this.wrapV===Vo.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.y=e}return i}attachToMesh(e,t=!0){const i=this.getScene();i&&(this._pointerObserver&&i.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=i.onPointerObservable.add((t=>{if(t.type!==Ms.POINTERMOVE&&t.type!==Ms.POINTERUP&&t.type!==Ms.POINTERDOWN&&t.type!==Ms.POINTERWHEEL)return;t.type===Ms.POINTERMOVE&&t.event.pointerId&&(this._defaultMousePointerId=t.event.pointerId);const i=t.event.pointerId||this._defaultMousePointerId;if(t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh===e){let e=t.pickInfo.getTextureCoordinates();if(e){e=this._transformUvs(e);const s=this.getSize();this._doPicking(e.x*s.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*s.height,t,t.type,i,t.event.button,t.event.deltaX,t.event.deltaY)}}else if(t.type===Ms.POINTERUP){if(this._lastControlDown[i]&&this._lastControlDown[i]._forcePointerUp(i),delete this._lastControlDown[i],this.focusedControl){const e=this.focusedControl.keepsFocusWith();let t=!0;if(e)for(const s of e){if(this===s._host)continue;const e=s._host;if(e._lastControlOver[i]&&e._lastControlOver[i].isAscendant(s)){t=!1;break}}t&&(this.focusedControl=null)}}else t.type===Ms.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i],t,!0),delete this._lastControlOver[i])})),e.enablePointerMoveEvents=t,this._attachPickingToSceneRender(i,(()=>{const t=this._defaultMousePointerId,s=i?.pick(i.pointerX,i.pointerY);if(s&&s.hit&&s.pickedMesh===e){let e=s.getTextureCoordinates();if(e){e=this._transformUvs(e);const i=this.getSize();this._doPicking(e.x*i.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*i.height,null,Ms.POINTERMOVE,t,0)}}else this._lastControlOver[t]&&this._lastControlOver[t]._onPointerOut(this._lastControlOver[t],null,!0),delete this._lastControlOver[t]}),!0),this._attachToOnPointerOut(i),this._attachToOnBlur(i))}moveFocusToControl(e){this.focusedControl=e,this._lastPickedControl=e,this._blockNextFocusCheck=!0}_manageFocus(){if(this._blockNextFocusCheck)return this._blockNextFocusCheck=!1,void(this._lastPickedControl=this._focusedControl);if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}}_attachPickingToSceneRender(e,t,i){this._sceneRenderObserver=e.onBeforeRenderObservable.add((()=>{this.checkPointerEveryFrame&&(this._linkedControls.length>0||i)&&t()}))}_attachToOnPointerOut(e){this._canvasPointerOutObserver=e.getEngine().onCanvasPointerOutObservable.add((e=>{this._lastControlOver[e.pointerId]&&this._lastControlOver[e.pointerId]._onPointerOut(this._lastControlOver[e.pointerId],null),delete this._lastControlOver[e.pointerId],this._lastControlDown[e.pointerId]&&this._lastControlDown[e.pointerId]!==this._capturingControl[e.pointerId]&&(this._lastControlDown[e.pointerId]._forcePointerUp(e.pointerId),delete this._lastControlDown[e.pointerId])}))}_attachToOnBlur(e){this._canvasBlurObserver=e.getEngine().onCanvasBlurObservable.add((()=>{Object.entries(this._lastControlDown).forEach((([,e])=>{e._onCanvasBlur()})),this.focusedControl=null,this._lastControlDown={}}))}serializeContent(){const e=this.getSize(),t={root:{},width:e.width,height:e.height};return this._rootContainer.serialize(t.root),t}parseSerializedObject(e,t){if(this._rootContainer=BD.Parse(e.root,this),t){const t=e.width,i=e.height;"number"==typeof t&&"number"==typeof i&&t>=0&&i>=0?this.scaleTo(t,i):this.scaleTo(1920,1080)}}clone(e,t){const i=this.getScene();if(!i)return this;const s=this.getSize(),r=this.serializeContent();let n;return n=this._isFullscreen?Cw.CreateFullscreenUI(e??"Clone of "+this.name):t?Cw.CreateForMesh(t,s.width,s.height):new Cw(e??"Clone of "+this.name,s.width,s.height,i,!this.noMipmap,this.samplingMode),n.parseSerializedObject(r),n}static async ParseFromSnippetAsync(e,t,i){const s=i??Cw.CreateFullscreenUI("ADT from snippet");if("_BLANK"===e)return s;const r=await Cw._LoadURLContentAsync(Cw.SnippetUrl+"/"+e.replace(/#/g,"/"),!0);return s.parseSerializedObject(r,t),s}parseFromSnippetAsync(e,t){return Cw.ParseFromSnippetAsync(e,t,this)}static async ParseFromFileAsync(e,t,i){const s=i??Cw.CreateFullscreenUI("ADT from URL"),r=await Cw._LoadURLContentAsync(e);return s.parseSerializedObject(r,t),s}parseFromURLAsync(e,t){return Cw.ParseFromFileAsync(e,t,this)}static _LoadURLContentAsync(e,t=!1){return""===e?Promise.reject("No URL provided"):new Promise(((i,s)=>{const r=new At;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let e;if(t){const t=JSON.parse(JSON.parse(r.responseText).jsonPayload);e=t.encodedGui?new TextDecoder("utf-8").decode(Jt(t.encodedGui)):t.gui}else e=r.responseText;const s=JSON.parse(e);i(s)}else s("Unable to load")})),r.open("GET",e),r.send()}))}static _Overlaps(e,t){return!(e.centerX>t.centerX+t.widthInPixels||e.centerX+e.widthInPixelst.centerY+t.heightInPixels)}static CreateForMesh(e,t=1024,i=1024,s=!0,r=!1,n,o=this._CreateMaterial){const a=ns(),l=new Cw(`AdvancedDynamicTexture for ${e.name} [${a}]`,t,i,e.getScene(),!0,Vo.TRILINEAR_SAMPLINGMODE,n);return o(e,a,l,r),l.attachToMesh(e,s),l}static _CreateMaterial(e,t,i,s){const r=te("BABYLON.StandardMaterial");if(!r)throw"StandardMaterial needs to be imported before as it contains a side-effect required by your code.";const n=new r(`AdvancedDynamicTextureMaterial for ${e.name} [${t}]`,e.getScene());n.backFaceCulling=!1,n.diffuseColor=Ce.Black(),n.specularColor=Ce.Black(),s?(n.diffuseTexture=i,n.emissiveTexture=i,i.hasAlpha=!0):(n.emissiveTexture=i,n.opacityTexture=i),e.material=n}static CreateForMeshTexture(e,t=1024,i=1024,s=!0,r){const n=new Cw(e.name+" AdvancedDynamicTexture",t,i,e.getScene(),!0,Vo.TRILINEAR_SAMPLINGMODE,r);return n.attachToMesh(e,s),n}static CreateFullscreenUI(e,t=!0,i=null,s=Vo.BILINEAR_SAMPLINGMODE,r=!1){const n=new Cw(e,0,0,i,!1,s),o=n.getScene(),a=new Xg(e+"_layer",null,o,!t);if(a.texture=n,n._layerToDispose=a,n._isFullscreen=!0,r&&o){const e=1/o.getEngine().getHardwareScalingLevel();n._rootContainer.scaleX=e,n._rootContainer.scaleY=e}return n.attach(),n}scale(e){super.scale(e),this.markAsDirty()}scaleTo(e,t){super.scaleTo(e,t),this.markAsDirty()}_checkGuiIsReady(){this.guiIsReady()&&(this.onGuiReadyObservable.notifyObservers(this),this.onGuiReadyObservable.clear())}guiIsReady(){return this._rootContainer.isReady()}}Cw.SnippetUrl=Yd.SnippetUrl,Cw.AllowGPUOptimizations=!0;class Ew{get renderTimeCounter(){return this._renderTime}get layoutTimeCounter(){return this._layoutTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeginRenderObserver=this.texture.onBeginRenderObservable.add((()=>{this._renderTime.beginMonitoring()})),this._onEndRenderObserver=this.texture.onEndRenderObservable.add((()=>{this._renderTime.endMonitoring(!0)}))):(this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null))}get captureLayoutTime(){return this._captureLayoutTime}set captureLayoutTime(e){e!==this._captureLayoutTime&&(this._captureLayoutTime=e,e?(this._onBeginLayoutObserver=this.texture.onBeginLayoutObservable.add((()=>{this._layoutTime.beginMonitoring()})),this._onEndLayoutObserver=this.texture.onEndLayoutObservable.add((()=>{this._layoutTime.endMonitoring(!0)}))):(this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null))}constructor(e){this.texture=e,this._captureRenderTime=!1,this._renderTime=new tr,this._captureLayoutTime=!1,this._layoutTime=new tr,this._onBeginRenderObserver=null,this._onEndRenderObserver=null,this._onBeginLayoutObserver=null,this._onEndLayoutObserver=null}dispose(){this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null,this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null,this.texture=null}}const Aw="XmlLoader Exception : XML file is malformed or corrupted.";class Pw{constructor(e=null){this._nodes={},this._nodeTypes={element:1,attribute:2,text:3},this._isLoaded=!1,this._objectAttributes={textHorizontalAlignment:1,textVerticalAlignment:2,horizontalAlignment:3,verticalAlignment:4,stretch:5},e&&(this._parentClass=e)}_getChainElement(e){let t=window;this._parentClass&&(t=this._parentClass);let i=e;i=i.split(".");for(let e=0;e0&&u>d)throw"XmlLoader Exception : In the Grid element, the number of columns is defined in the first row, do not add more columns in the subsequent rows.";if(0==c){if(!n[e].attributes.getNamedItem("width"))throw"XmlLoader Exception : Width must be defined for all the grid columns in the first row";s=Number(n[e].attributes.getNamedItem("width").nodeValue),h=!!n[e].attributes.getNamedItem("isPixel")&&JSON.parse(n[e].attributes.getNamedItem("isPixel").nodeValue),t.addColumnDefinition(s,h)}a=n[e].children;for(let e=0;e{if(4===r.readyState&&200===r.status){if(!r.responseXML){if(s)return void s(Aw);throw Aw}const e=r.responseXML.documentElement;this._parseXml(e.firstChild,t),this._isLoaded=!0,i&&i()}},r.onerror=function(){s&&s("an error occurred during loading the layout")},r.open("GET",e,!0),r.send()}async loadLayoutAsync(e,t){return new Promise(((i,s)=>{this.loadLayout(e,t,i,s)}))}}class Rw extends de{constructor(e,t=0){super(e.x,e.y,e.z),this.buttonIndex=t}}class Iw{get position(){return this._node?this._node.position:de.Zero()}set position(e){this._node&&(this._node.position=e)}get scaling(){return this._node?this._node.scaling:new de(1,1,1)}set scaling(e){this._node&&(this._isScaledByManager=!1,this._node.scaling=e)}get behaviors(){return this._behaviors}addBehavior(e){if(-1!==this._behaviors.indexOf(e))return this;e.init();const t=this._host.scene;return t.isLoading?t.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}get isVisible(){return this._isVisible}set isVisible(e){if(this._isVisible===e)return;this._isVisible=e;const t=this.mesh;t&&t.setEnabled(e)}constructor(e){this.name=e,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this._isScaledByManager=!1,this.onPointerMoveObservable=new X,this.onPointerOutObservable=new X,this.onPointerDownObservable=new X,this.onPointerUpObservable=new X,this.onPointerClickObservable=new X,this.onPointerEnterObservable=new X,this._behaviors=new Array}get typeName(){return this._getTypeName()}getClassName(){return this._getTypeName()}_getTypeName(){return"Control3D"}get node(){return this._node}get mesh(){return this._node instanceof Sn?this._node:null}linkToTransformNode(e){return this._node&&(this._node.parent=e),this}_prepareNode(e){if(!this._node){if(this._node=this._createNode(e),!this.node)return;this._injectGUI3DReservedDataStore(this.node).control=this;const t=this.mesh;t&&(t.isPickable=!0,this._affectMaterial(t))}}_injectGUI3DReservedDataStore(e){return e.reservedDataStore=e.reservedDataStore??{},e.reservedDataStore.GUI3D=e.reservedDataStore.GUI3D??{},e.reservedDataStore.GUI3D}_createNode(e){return null}_affectMaterial(e){e.material=null}_isTouchButton3D(e){return void 0!==e._generatePointerEventType}_onPointerMove(e,t){this.onPointerMoveObservable.notifyObservers(t,-1,e,this)}_onPointerEnter(e){return-1===this._enterCount&&(this._enterCount=0),this._enterCount++,!(this._enterCount>1||(this.onPointerEnterObservable.notifyObservers(this,-1,e,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),0))}_onPointerOut(e){this._enterCount--,this._enterCount>0||(this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,e,this),this.pointerOutAnimation&&this.pointerOutAnimation())}_onPointerDown(e,t,i,s){return this._downCount++,this._downPointerIds[i]=this._downPointerIds[i]+1||1,1===this._downCount&&(this.onPointerDownObservable.notifyObservers(new Rw(t,s),-1,e,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_onPointerUp(e,t,i,s,r){this._downCount--,this._downPointerIds[i]--,this._downPointerIds[i]<=0&&delete this._downPointerIds[i],this._downCount<0?this._downCount=0:0==this._downCount&&(r&&(this._enterCount>0||-1===this._enterCount)&&this.onPointerClickObservable.notifyObservers(new Rw(t,s),-1,e,this),this.onPointerUpObservable.notifyObservers(new Rw(t,s),-1,e,this),this.pointerUpAnimation&&this.pointerUpAnimation())}forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,de.Zero(),e,0,!0);else{for(const e in this._downPointerIds)this._onPointerUp(this,de.Zero(),+e,0,!0);this._downCount>0&&(this._downCount=1,this._onPointerUp(this,de.Zero(),0,0,!0))}}_processObservables(e,t,i,s,r){if(this._isTouchButton3D(this)&&i&&(e=this._generatePointerEventType(e,i,this._downCount)),e===Ms.POINTERMOVE){this._onPointerMove(this,t);const e=this._host._lastControlOver[s];return e&&e!==this&&e._onPointerOut(this),e!==this&&this._onPointerEnter(this),this._host._lastControlOver[s]=this,!0}return e===Ms.POINTERDOWN?(this._onPointerDown(this,t,s,r),this._host._lastControlDown[s]=this,this._host._lastPickedControl=this,!0):(e===Ms.POINTERUP||e===Ms.POINTERDOUBLETAP)&&(this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerUp(this,t,s,r,!0),delete this._host._lastControlDown[s],!0)}_disposeNode(){this._node&&(this._node.dispose(),this._node=null)}dispose(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(const e of this._behaviors)e.detach()}}class Mw extends Iw{constructor(){super(...arguments),this._contentResolution=512,this._contentScaleRatio=2}get content(){return this._content}set content(e){this._content=e,e&&this._host&&this._host.utilityLayer&&(this._facadeTexture?this._facadeTexture.rootContainer.clearControls():(this._facadeTexture=new Cw("Facade",this._contentResolution,this._contentResolution,this._host.utilityLayer.utilityLayerScene,!0,Vo.TRILINEAR_SAMPLINGMODE),this._setFacadeTextureScaling(),this._facadeTexture.premulAlpha=!0),this._facadeTexture.addControl(e),this._applyFacade(this._facadeTexture))}_setFacadeTextureScaling(){this._facadeTexture&&(this._facadeTexture.rootContainer.scaleX=this._contentScaleRatio,this._facadeTexture.rootContainer.scaleY=this._contentScaleRatioY??this._contentScaleRatio)}get contentResolution(){return this._contentResolution}set contentResolution(e){this._contentResolution!==e&&(this._contentResolution=e,this._resetContent())}_disposeFacadeTexture(){this._facadeTexture&&(this._facadeTexture.dispose(),this._facadeTexture=null)}_resetContent(){this._disposeFacadeTexture(),this.content=this._content}_applyFacade(e){}}class Ow extends Mw{constructor(e){super(e)}_getTypeName(){return"AbstractButton3D"}_createNode(e){return new xn("button"+this.name,e)}}class Dw extends Ow{constructor(e,t){super(e),this._options={width:1,height:1,depth:.08,...t},this.pointerEnterAnimation=()=>{this.mesh&&(this._currentMaterial.emissiveColor=Ce.Red())},this.pointerOutAnimation=()=>{this._currentMaterial.emissiveColor=Ce.Black()},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_applyFacade(e){this._currentMaterial.emissiveTexture=e}_getTypeName(){return"Button3D"}_createNode(e){const t=new Array(6);for(let e=0;e<6;e++)t[e]=new _e(0,0,0,0);e.useRightHandedSystem?t[0].copyFromFloats(1,0,0,1):t[1].copyFromFloats(0,0,1,1);const i=yu(this.name+"_rootMesh",{width:this._options.width,height:this._options.height,depth:this._options.depth,faceUV:t,wrap:!0},e);return this._contentScaleRatioY=this._contentScaleRatio*this._options.width/this._options.height,this._setFacadeTextureScaling(),i}_affectMaterial(e){const t=new yc(this.name+"Material",e.getScene());t.specularColor=Ce.Black(),e.material=t,this._currentMaterial=t,this._resetContent()}dispose(){super.dispose(),this._disposeFacadeTexture(),this._currentMaterial&&this._currentMaterial.dispose()}}class ww extends Iw{get children(){return this._children}get blockLayout(){return this._blockLayout}set blockLayout(e){this._blockLayout!==e&&(this._blockLayout=e,this._blockLayout||this._arrangeChildren())}constructor(e){super(e),this._blockLayout=!1,this._children=new Array}updateLayout(){return this._arrangeChildren(),this}containsControl(e){return-1!==this._children.indexOf(e)}addControl(e){return-1!==this._children.indexOf(e)||(e.parent=this,e._host=this._host,this._children.push(e),this._host.utilityLayer&&(e._prepareNode(this._host.utilityLayer.utilityLayerScene),e.node&&(e.node.parent=this.node),this.blockLayout||this._arrangeChildren())),this}_arrangeChildren(){}_createNode(e){return new xn("ContainerNode",e)}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null,e._disposeNode()),this}_getTypeName(){return"Container3D"}dispose(){for(const e of this._children)e.dispose();this._children.length=0,super.dispose()}}ww.UNSET_ORIENTATION=0,ww.FACEORIGIN_ORIENTATION=1,ww.FACEORIGINREVERSED_ORIENTATION=2,ww.FACEFORWARD_ORIENTATION=3,ww.FACEFORWARDREVERSED_ORIENTATION=4;class Nw extends ww{get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}get columns(){return this._columns}set columns(e){this._columns!==e&&(this._columns=e,this._rowThenColum=!0,hs.SetImmediate((()=>{this._arrangeChildren()})))}get rows(){return this._rows}set rows(e){this._rows!==e&&(this._rows=e,this._rowThenColum=!1,hs.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e){super(e),this._columns=10,this._rows=0,this._rowThenColum=!0,this._orientation=ww.FACEORIGIN_ORIENTATION,this.margin=0}_arrangeChildren(){this._cellWidth=0,this._cellHeight=0;let e=0,t=0,i=0;const s=fe.Invert(this.node.computeWorldMatrix(!0));for(const e of this._children){if(!e.mesh)continue;i++,e.mesh.computeWorldMatrix(!0);const t=e.mesh.getHierarchyBoundingVectors(),r=ge.Vector3[0],n=ge.Vector3[1];t.max.subtractToRef(t.min,n),n.scaleInPlace(.5),de.TransformNormalToRef(n,s,r),this._cellWidth=Math.max(this._cellWidth,2*r.x),this._cellHeight=Math.max(this._cellHeight,2*r.y)}this._cellWidth+=2*this.margin,this._cellHeight+=2*this.margin,this._rowThenColum?(t=this._columns,e=Math.ceil(i/this._columns)):(e=this._rows,t=Math.ceil(i/this._rows));const r=.5*t*this._cellWidth,n=.5*e*this._cellHeight,o=[];let a=0;if(this._rowThenColum)for(let s=0;si));e++);else for(let s=0;si));t++);a=0;for(const e of this._children)e.mesh&&(this._mapGridNode(e,o[a]),a++);this._finalProcessing()}_finalProcessing(){}}class Fw extends Nw{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._cylindricalMapping(t);switch(e.position=s,this.orientation){case ww.FACEORIGIN_ORIENTATION:i.lookAt(new de(2*s.x,s.y,2*s.z));break;case ww.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new de(-s.x,s.y,-s.z));break;case ww.FACEFORWARD_ORIENTATION:break;case ww.FACEFORWARDREVERSED_ORIENTATION:i.rotate(_r.Y,Math.PI,lr.LOCAL)}}_cylindricalMapping(e){const t=new de(0,e.y,this._radius),i=e.x/this._radius;return fe.RotationYawPitchRollToRef(i,0,0,ge.Matrix[0]),de.TransformNormal(t,ge.Matrix[0])}}bi.ShadersStore.fluentVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 world;uniform mat4 viewProjection;varying vec2 vUV;\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float borderWidth;uniform vec3 scaleFactor;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\n#endif\nvoid main(void) {vUV=uv;\n#ifdef BORDER\nvec3 scale=scaleFactor;float minScale=min(min(scale.x,scale.y),scale.z);float maxScale=max(max(scale.x,scale.y),scale.z);float minOverMiddleScale=minScale/(scale.x+scale.y+scale.z-minScale-maxScale);float areaYZ=scale.y*scale.z;float areaXZ=scale.x*scale.z;float areaXY=scale.x*scale.y;float scaledBorderWidth=borderWidth; \nif (abs(normal.x)==1.0) \n{scale.x=scale.y;scale.y=scale.z;if (areaYZ>areaXZ && areaYZ>areaXY)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse if (abs(normal.y)==1.0) \n{scale.x=scale.z;if (areaXZ>areaXY && areaXZ>areaYZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse \n{if (areaXY>areaYZ && areaXY>areaXZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);if (scale.x>scale.y)\n{scaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);scaleInfo.y=1.0-scaledBorderWidth;}\nelse\n{scaleInfo.x=1.0-scaledBorderWidth;scaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);} \n#endif \nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;}\n";bi.ShadersStore.fluentPixelShader="precision highp float;varying vec2 vUV;uniform vec4 albedoColor;\n#ifdef INNERGLOW\nuniform vec4 innerGlowColor;\n#endif\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float edgeSmoothingValue;uniform float borderMinValue;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;uniform vec3 hoverPosition;uniform vec4 hoverColor;uniform float hoverRadius;\n#endif\n#ifdef TEXTURE\nuniform sampler2D albedoSampler;uniform mat4 textureMatrix;vec2 finalUV;\n#endif\nvoid main(void) {vec3 albedo=albedoColor.rgb;float alpha=albedoColor.a;\n#ifdef TEXTURE\nfinalUV=vec2(textureMatrix*vec4(vUV,1.0,0.0));albedo=texture2D(albedoSampler,finalUV).rgb;\n#endif\n#ifdef HOVERLIGHT\nfloat pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;albedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.);\n#else\nfloat pointToHover=1.0;\n#endif\n#ifdef BORDER \nfloat borderPower=10.0;float inverseBorderPower=1.0/borderPower;vec3 borderColor=albedo*borderPower;vec2 distanceToEdge;distanceToEdge.x=abs(vUV.x-0.5)*2.0;distanceToEdge.y=abs(vUV.y-0.5)*2.0;float borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x),\nsmoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));borderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover); \nalbedo+=borderColor;alpha=max(alpha,borderValue);\n#endif\n#ifdef INNERGLOW\nvec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);uvGlow=uvGlow*uvGlow;uvGlow=uvGlow*uvGlow;albedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y); \n#endif\ngl_FragColor=vec4(albedo,alpha);}";class Bw extends Oa{constructor(){super(),this.INNERGLOW=!1,this.BORDER=!1,this.HOVERLIGHT=!1,this.TEXTURE=!1,this.rebuild()}}class Lw extends Ra{constructor(e,t){super(e,t),this.innerGlowColorIntensity=.5,this.innerGlowColor=new Ce(1,1,1),this.albedoColor=new Ce(.3,.35,.4),this.renderBorders=!1,this.borderWidth=.5,this.edgeSmoothingValue=.02,this.borderMinValue=.1,this.renderHoverLight=!1,this.hoverRadius=.01,this.hoverColor=new Ee(.3,.3,.3,1),this.hoverPosition=de.Zero()}needAlphaBlending(){return 1!==this.alpha}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new Bw);const s=this.getScene(),r=t.materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&r._renderId===s.getRenderId())return!0;if(r._areTexturesDirty)if(r.INNERGLOW=this.innerGlowColorIntensity>0,r.BORDER=this.renderBorders,r.HOVERLIGHT=this.renderHoverLight,this._albedoTexture){if(!this._albedoTexture.isReadyOrNotBlocking())return!1;r.TEXTURE=!0}else r.TEXTURE=!1;const n=s.getEngine();if(r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=[ys.PositionKind];e.push(ys.NormalKind),e.push(ys.UVKind);const i="fluent",o=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius","textureMatrix"],a=["albedoSampler"],l=[];co({uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:r,maxSimultaneousLights:4});const h=r.toString();t.setEffect(s.getEngine().createEffect(i,{attributes:e,uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:h,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n,i)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),r.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),r.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),t.getBoundingInfo().boundingBox.extendSize.multiplyToRef(t.scaling,ge.Vector3[0]),this._activeEffect.setVector3("scaleFactor",ge.Vector3[0])),r.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition)),r.TEXTURE&&this._albedoTexture)){this._activeEffect.setTexture("albedoSampler",this._albedoTexture);const e=this._albedoTexture.getTextureMatrix();this._activeEffect.setMatrix("textureMatrix",e)}this._afterBind(t,this._activeEffect,i)}}getActiveTextures(){return super.getActiveTextures()}hasTexture(e){return!!super.hasTexture(e)}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new Lw(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GUI.FluentMaterial",e}getClassName(){return"FluentMaterial"}static Parse(e,t,i){return yt.Parse((()=>new Lw(e.name,t)),e,t,i)}}qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Lw.prototype,"innerGlowColorIntensity",void 0),qe([nt()],Lw.prototype,"innerGlowColor",void 0),qe([nt()],Lw.prototype,"albedoColor",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Lw.prototype,"renderBorders",void 0),qe([st()],Lw.prototype,"borderWidth",void 0),qe([st()],Lw.prototype,"edgeSmoothingValue",void 0),qe([st()],Lw.prototype,"borderMinValue",void 0),qe([st(),it("_markAllSubMeshesAsTexturesDirty")],Lw.prototype,"renderHoverLight",void 0),qe([st()],Lw.prototype,"hoverRadius",void 0),qe([ut()],Lw.prototype,"hoverColor",void 0),qe([lt()],Lw.prototype,"hoverPosition",void 0),qe([rt("albedoTexture")],Lw.prototype,"_albedoTexture",void 0),qe([it("_markAllSubMeshesAsTexturesAndMiscDirty")],Lw.prototype,"albedoTexture",void 0),ee("BABYLON.GUI.FluentMaterial",Lw);class kw extends Nw{get backPlateMargin(){return this._backPlateMargin}set backPlateMargin(e){this._backPlateMargin=e,this._children.length>=1&&(this.children.forEach((e=>{this._updateCurrentMinMax(e.position)})),this._updateMargins())}_createNode(e){const t=new bo(`menu_${this.name}`,e);return this._backPlate=yu("backPlate"+this.name,{size:1},e),this._backPlate.parent=t,t}_affectMaterial(e){this._backPlateMaterial=new Lw(this.name+"backPlateMaterial",e.getScene()),this._backPlateMaterial.albedoColor=new Ce(.08,.15,.55),this._backPlateMaterial.renderBorders=!0,this._backPlateMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backPlateMaterial.hoverPosition=e,this._backPlateMaterial.hoverColor.a=1):this._backPlateMaterial.hoverColor.a=0})),this._backPlate.material=this._backPlateMaterial}_mapGridNode(e,t){e.mesh&&(e.position=t.clone(),this._updateCurrentMinMax(t))}_finalProcessing(){this._updateMargins()}_updateCurrentMinMax(e){this._currentMin||(this._currentMin=e.clone(),this._currentMax=e.clone()),this._currentMin.minimizeInPlace(e),this._currentMax.maximizeInPlace(e)}_updateMargins(){if(this._children.length>0){this._currentMin.addInPlaceFromFloats(-this._cellWidth/2,-this._cellHeight/2,0),this._currentMax.addInPlaceFromFloats(this._cellWidth/2,this._cellHeight/2,0);const e=this._currentMax.subtract(this._currentMin);this._backPlate.scaling.x=e.x+this._cellWidth*this.backPlateMargin,this._backPlate.scaling.y=e.y+this._cellHeight*this.backPlateMargin,this._backPlate.scaling.z=.001;for(let t=0;t0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Pick_Radius_B144(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid main()\n{vec3 Nrm_World_Q128;Nrm_World_Q128=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q131;vec3 Tangent_World_N_Q131;float Tangent_Length_Q131;Tangent_World_Q131=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q131=length(Tangent_World_Q131);Tangent_World_N_Q131=Tangent_World_Q131/Tangent_Length_Q131;vec3 Binormal_World_Q132;vec3 Binormal_World_N_Q132;float Binormal_Length_Q132;Object_To_World_Dir_B132(vec3(0,1,0),Binormal_World_Q132,Binormal_World_N_Q132,Binormal_Length_Q132);float Anisotropy_Q133=Tangent_Length_Q131/Binormal_Length_Q132;vec3 Result_Q177;Result_Q177=mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(_Use_Global_Left_Index_));vec3 Result_Q178;Result_Q178=mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(_Use_Global_Right_Index_));float Result_Q144;Pick_Radius_B144(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q144);vec3 Dir_Q140;PickDir_B140(_Angle_,Tangent_World_N_Q131,Binormal_World_N_Q132,Dir_Q140);float Radius_Q147;float Line_Width_Q147;RelativeOrAbsoluteDetail_B147(Result_Q144,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q132,Radius_Q147,Line_Width_Q147);vec4 Out_Color_Q145=vec4(Radius_Q147,Line_Width_Q147,0,1);vec3 New_P_Q129;vec2 New_UV_Q129;float Radial_Gradient_Q129;vec3 Radial_Dir_Q129;Move_Verts_B129(Anisotropy_Q133,position,Radius_Q147,New_P_Q129,New_UV_Q129,Radial_Gradient_Q129,Radial_Dir_Q129);vec3 Pos_World_Q115;Object_To_World_Pos_B115(New_P_Q129,Pos_World_Q115);vec4 Blob_Info_Q180;\n#if BLOB_ENABLE\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q177,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q180);\n#else\nBlob_Info_Q180=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q181;\n#if BLOB_ENABLE_2\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q178,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q181);\n#else\nBlob_Info_Q181=vec4(0,0,0,0);\n#endif\nfloat Gradient1_Q130;float Gradient2_Q130;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B130(Pos_World_Q115,position,normal,cameraPosition,Radial_Gradient_Q129,Radial_Dir_Q129,tangent,Gradient1_Q130,Gradient2_Q130);\n#else\nGradient1_Q130=1.0;Gradient2_Q130=1.0;\n#endif\nvec2 Rect_UV_Q139;vec4 Rect_Parms_Q139;vec2 Scale_XY_Q139;vec2 Line_UV_Q139;Round_Rect_Vertex_B139(New_UV_Q129,Radius_Q147,0.0,Anisotropy_Q133,Gradient1_Q130,Gradient2_Q130,Rect_UV_Q139,Rect_Parms_Q139,Scale_XY_Q139,Line_UV_Q139);vec3 Line_Vertex_Q135;Line_Vertex_B135(Scale_XY_Q139,Line_UV_Q139,0.0,_Rate_,_Highlight_Transform_,Line_Vertex_Q135);vec3 Position=Pos_World_Q115;vec3 Normal=Dir_Q140;vec2 UV=Rect_UV_Q139;vec3 Tangent=Line_Vertex_Q135;vec3 Binormal=Nrm_World_Q128;vec4 Color=Out_Color_Q145;vec4 Extra1=Rect_Parms_Q139;vec4 Extra2=Blob_Info_Q180;vec4 Extra3=Blob_Info_Q181;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class Uw extends Oa{constructor(){super(),this.BLOB_ENABLE=!0,this.BLOB_ENABLE_2=!0,this.SMOOTH_EDGES=!0,this.IRIDESCENT_MAP_ENABLE=!0,this._needNormals=!0,this.rebuild()}}class Gw extends Ra{constructor(e,t){super(e,t),this.radius=.03,this.lineWidth=.01,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Ee(.0392157,.0666667,.207843,1),this.lineColor=new Ee(.14902,.133333,.384314,1),this.blobIntensity=.98,this.blobFarSize=.04,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.blobNearSize=.22,this.blobPulse=0,this.blobFade=0,this.blobNearSize2=.22,this.blobPulse2=0,this.blobFade2=0,this._rate=.135,this.highlightColor=new Ee(.98,.98,.98,1),this.highlightWidth=.25,this._highlightTransform=new _e(1,1,0,0),this._highlight=1,this.iridescenceIntensity=0,this.iridescenceEdgeIntensity=1,this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.globalLeftIndexTipPosition=de.Zero(),this._globalLeftIndexTipPosition4=_e.Zero(),this.globalRightIndexTipPosition=de.Zero(),this._globalRightIndexTipPosition4=_e.Zero(),this.alphaMode=Yd.ALPHA_DISABLE,this.backFaceCulling=!1,this._blobTexture=new Vo(Gw.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE),this._iridescentMap=new Vo(Gw.IM_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new Uw);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="fluentBackplate",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Angle_","_Fade_Out_","_Reflected_","_Frequency_","_Vertical_Offset_","_Iridescent_Map_","_Use_Global_Left_Index_","_Use_Global_Right_Index_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position"],h=["_Blob_Texture_","_Iridescent_Map_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera?.position??de.ZeroReadOnly),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",1),this._activeEffect.setFloat("_Radius_Top_Right_",1),this._activeEffect.setFloat("_Radius_Bottom_Left_",1),this._activeEffect.setFloat("_Radius_Bottom_Right_",1),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMap),this._activeEffect.setFloat("_Use_Global_Left_Index_",1),this._activeEffect.setFloat("_Use_Global_Right_Index_",1),this._globalLeftIndexTipPosition4.set(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this._globalLeftIndexTipPosition4),this._globalRightIndexTipPosition4.set(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this._globalRightIndexTipPosition4),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._blobTexture.dispose(),this._iridescentMap.dispose()}clone(e){return yt.Clone((()=>new Gw(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentBackplateMaterial",e}getClassName(){return"FluentBackplateMaterial"}static Parse(e,t,i){return yt.Parse((()=>new Gw(e.name,t)),e,t,i)}}Gw.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-blob.png",Gw.IM_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-iridescence.png",qe([st()],Gw.prototype,"radius",void 0),qe([st()],Gw.prototype,"lineWidth",void 0),qe([st()],Gw.prototype,"absoluteSizes",void 0),qe([st()],Gw.prototype,"baseColor",void 0),qe([st()],Gw.prototype,"lineColor",void 0),qe([st()],Gw.prototype,"blobIntensity",void 0),qe([st()],Gw.prototype,"blobFarSize",void 0),qe([st()],Gw.prototype,"blobNearDistance",void 0),qe([st()],Gw.prototype,"blobFarDistance",void 0),qe([st()],Gw.prototype,"blobFadeLength",void 0),qe([st()],Gw.prototype,"blobNearSize",void 0),qe([st()],Gw.prototype,"blobPulse",void 0),qe([st()],Gw.prototype,"blobFade",void 0),qe([st()],Gw.prototype,"blobNearSize2",void 0),qe([st()],Gw.prototype,"blobPulse2",void 0),qe([st()],Gw.prototype,"blobFade2",void 0),qe([st()],Gw.prototype,"highlightColor",void 0),qe([st()],Gw.prototype,"highlightWidth",void 0),qe([st()],Gw.prototype,"iridescenceIntensity",void 0),qe([st()],Gw.prototype,"iridescenceEdgeIntensity",void 0),qe([st()],Gw.prototype,"fadeOut",void 0),qe([lt()],Gw.prototype,"globalLeftIndexTipPosition",void 0),qe([lt()],Gw.prototype,"globalRightIndexTipPosition",void 0),ee("BABYLON.GUI.FluentBackplateMaterial",Gw);class zw extends Iw{set renderingGroupId(e){this._model.renderingGroupId=e}get renderingGroupId(){return this._model.renderingGroupId}get material(){return this._material}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=t}_getTypeName(){return"HolographicBackplate"}_createNode(e){const t=yu((this.name??"HolographicBackplate")+"_CollisionMesh",{width:1,height:1,depth:1},e);return t.isPickable=!0,t.visibility=0,Pa.ImportMeshAsync(void 0,zw.MODEL_BASE_URL,zw.MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_frontPlate`,i.isPickable=!1,i.parent=t,this._material&&(i.material=this._material),this._model=i})),t}_createMaterial(e){this._material=new Gw(this.name+" Material",e.getScene())}_affectMaterial(e){this._shareMaterials?this._host._touchSharedMaterials.fluentBackplateMaterial?this._material=this._host._touchSharedMaterials.fluentBackplateMaterial:(this._createMaterial(e),this._host._touchSharedMaterials.fluentBackplateMaterial=this._material):this._createMaterial(e)}dispose(){super.dispose(),this.shareMaterials||this._material.dispose(),this._model.dispose()}}zw.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",zw.MODEL_FILENAME="mrtk-fluent-backplate.glb";class Ww extends Dw{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=ta("",{size:1},this._backPlate._scene);const t=ta("",{size:1,sideOrientation:bo.DOUBLESIDE},this._backPlate._scene),i=new yc("",this._backPlate._scene);i.diffuseColor=Ce.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=de.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=de.Up().scale(.7).add(de.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=Cw.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new UD,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new qo,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!0)},this.pointerOutAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!1)}}_getTypeName(){return"HolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new WD;if(e.isVertical=!0,Vt()&&document.createElement&&this._imageUrl){const t=new GD;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new UD;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this._frontPlate&&(this.content=e)}_createNode(e){return this._backPlate=yu(this.name+"BackMesh",{width:1,height:1,depth:.08},e),this._frontPlate=yu(this.name+"FrontMesh",{width:1,height:1,depth:.08},e),this._frontPlate.parent=this._backPlate,this._frontPlate.position=de.Forward(e.useRightHandedSystem).scale(-.08),this._frontPlate.isPickable=!1,this._frontPlate.setEnabled(!1),this._textPlate=super._createNode(e),this._textPlate.parent=this._backPlate,this._textPlate.position=de.Forward(e.useRightHandedSystem).scale(-.08),this._textPlate.isPickable=!1,this._backPlate}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e}_createBackMaterial(e){this._backMaterial=new Lw(this.name+"Back Material",e.getScene()),this._backMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backMaterial.hoverPosition=e,this._backMaterial.hoverColor.a=1):this._backMaterial.hoverColor.a=0}))}_createFrontMaterial(e){this._frontMaterial=new Lw(this.name+"Front Material",e.getScene()),this._frontMaterial.innerGlowColorIntensity=0,this._frontMaterial.alpha=.5,this._frontMaterial.renderBorders=!0}_createPlateMaterial(e){this._plateMaterial=new yc(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ce.Black()}_affectMaterial(e){this._shareMaterials?(this._host._sharedMaterials.backFluentMaterial?this._backMaterial=this._host._sharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._sharedMaterials.backFluentMaterial=this._backMaterial),this._host._sharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._sharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._sharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._frontPlate.material=this._frontMaterial,this._textPlate.material=this._plateMaterial,this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}bi.ShadersStore.fluentButtonPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform bool _Relative_Width_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool Enable_Fade;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool _Use_Blob_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Holo_Edge_Fragment_B35(\nvec4 Edges,\nfloat Edge_Width,\nout float NotEdge)\n{vec2 c=vec2(min(Edges.r,Edges.g),min(Edges.b,Edges.a));vec2 df=fwidth(c)*Edge_Width;vec2 g=clamp(c/df,0.0,1.0);NotEdge=g.x*g.y;}\nvoid Blob_Fragment_B39(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvec2 FilterStep(vec2 Edge,vec2 X)\n{vec2 dX=max(fwidth(X),vec2(0.00001,0.00001));return clamp( (X+dX-max(Edge,X-dX))/(dX*2.0),0.0,1.0);}\nvoid Wireframe_Fragment_B59(\nvec3 Widths,\nvec2 UV,\nfloat Proximity,\nvec4 Edge_Color,\nout vec4 Wireframe)\n{vec2 c=min(UV,vec2(1.0,1.0)-UV);vec2 g=FilterStep(Widths.xy*0.5,c); \nWireframe=(1.0-min(g.x,g.y))*Proximity*Edge_Color;}\nvoid Proximity_B53(\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec3 Position,\nvec3 Show_Selection,\nvec4 Extra1,\nfloat Dist_To_Face,\nfloat Intensity,\nout float Proximity)\n{vec2 delta1=Extra1.xy;vec2 delta2=Extra1.zw;float d2=sqrt(min(dot(delta1,delta1),dot(delta2,delta2))+Dist_To_Face*Dist_To_Face);Proximity=Intensity*Proximity_Max_Intensity*(1.0-clamp(d2/Proximity_Near_Radius,0.0,1.0))*(1.0-Show_Selection.x)+Show_Selection.x;}\nvoid To_XYZ_B46(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid main()\n{float NotEdge_Q35;\n#if ENABLE_FADE\nHolo_Edge_Fragment_B35(vColor,_Fade_Width_,NotEdge_Q35);\n#else\nNotEdge_Q35=1.0;\n#endif\nvec4 Blob_Color_Q39;float k=dot(vUV,vUV);vec2 blobTextureCoord=vec2(vec2(sqrt(k),vTangent.x).x,1.0-vec2(sqrt(k),vTangent.x).y);vec4 blobColor=mix(vec4(1.0,1.0,1.0,1.0)*step(1.0-vTangent.x,clamp(sqrt(k)+0.1,0.0,1.0)),texture(_Blob_Texture_,blobTextureCoord),float(_Use_Blob_Texture_));Blob_Color_Q39=vTangent.y*blobColor*(1.0-clamp(k,0.0,1.0));float Is_Quad_Q24;Is_Quad_Q24=vNormal.z;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));float X_Q46;float Y_Q46;float Z_Q46;To_XYZ_B46(vBinormal,X_Q46,Y_Q46,Z_Q46);float Proximity_Q53;Proximity_B53(Blob_Position_Q41,Blob_Position_Q42,_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vPosition,vBinormal,vExtra1,Y_Q46,Z_Q46,Proximity_Q53);vec4 Wireframe_Q59;Wireframe_Fragment_B59(vNormal,vUV,Proximity_Q53,_Edge_Color_,Wireframe_Q59);vec4 Wire_Or_Blob_Q23=mix(Wireframe_Q59,Blob_Color_Q39,Is_Quad_Q24);vec4 Result_Q22;Result_Q22=mix(Wire_Or_Blob_Q23,vec4(0.3,0.3,0.3,0.3),float(_Show_Frame_));vec4 Final_Color_Q37=NotEdge_Q35*Result_Q22;vec4 Out_Color=Final_Color_Q37;float Clip_Threshold=0.0;bool To_sRGB=false;gl_FragColor=Out_Color;}";bi.ShadersStore.fluentButtonVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool _Enable_Fade_;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;void Blob_Vertex_B47(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nvec3 Active_Face_Center,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal);Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B66(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Up,\nout vec4 Extra1,\nout float Distance_To_Face,\nout float Intensity)\n{vec3 Active_Face_Dir_X=normalize(cross(Active_Face_Dir,Up));vec3 Active_Face_Dir_Y=cross(Active_Face_Dir,Active_Face_Dir_X);float distz1,distz2;Extra1.xy=ProjectProximity(Blob_Position,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz1)/Relative_Scale;Extra1.zw=ProjectProximity(Blob_Position_2,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz2)/Relative_Scale;Distance_To_Face=dot(Active_Face_Dir,Position-Active_Face_Center);Intensity=1.0-clamp(min(distz1,distz2)/Proximity_Far_Distance,0.0,1.0);}\nvoid Holo_Edge_Vertex_B44(\nvec3 Incident,\nvec3 Normal,\nvec2 UV,\nvec3 Tangent,\nvec3 Bitangent,\nbool Smooth_Active_Face,\nfloat Active,\nout vec4 Holo_Edges)\n{float NdotI=dot(Incident,Normal);vec2 flip=(UV-vec2(0.5,0.5));float udot=dot(Incident,Tangent)*flip.x*NdotI;float uval=1.0-float(udot>0.0);float vdot=-dot(Incident,Bitangent)*flip.y*NdotI;float vval=1.0-float(vdot>0.0);float Smooth_And_Active=step(1.0,float(Smooth_Active_Face && Active>0.0));uval=mix(uval,max(1.0,uval),Smooth_And_Active); \nvval=mix(vval,max(1.0,vval),Smooth_And_Active);Holo_Edges=vec4(1.0,1.0,1.0,1.0)-vec4(uval*UV.x,uval*(1.0-UV.x),vval*UV.y,vval*(1.0-UV.y));}\nvoid Object_To_World_Pos_B13(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B38(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=float(Blob_Enable_1);float b2=float(Blob_Enable_2);Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Wireframe_Vertex_B51(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Edge_Width,\nvec2 Face_Size,\nout vec3 Wire_Vx_Pos,\nout vec2 UV,\nout vec2 Widths)\n{Widths.xy=Edge_Width/Face_Size;float x=dot(Position,Tangent);float y=dot(Position,Bitangent);float dx=0.5-abs(x);float newx=(0.5-dx*Widths.x*2.0)*sign(x);float dy=0.5-abs(y);float newy=(0.5-dy*Widths.y*2.0)*sign(y);Wire_Vx_Pos=Normal*0.5+newx*Tangent+newy*Bitangent;UV.x=dot(Wire_Vx_Pos,Tangent)+0.5;UV.y=dot(Wire_Vx_Pos,Bitangent)+0.5;}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B48(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float Active=max(0.0,dot(Active_Face_Dir,Normal));Show_Selection=mix(max(select1,select2),1.0,Selected)*Active;}\nvoid Proximity_Visibility_B54(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Input_Width,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nout float Width)\n{vec3 boxEdges=(world*vec4(vec3(0.5,0.5,0.5),0.0)).xyz;float boxMaxSize=length(boxEdges);float d1=dot(Proximity_Center-Active_Face_Center,Active_Face_Dir);vec3 blob1=Proximity_Center-d1*Active_Face_Dir;float d2=dot(Proximity_Center_2-Active_Face_Center,Active_Face_Dir);vec3 blob2=Proximity_Center_2-d2*Active_Face_Dir;vec3 delta1=blob1-Active_Face_Center;vec3 delta2=blob2-Active_Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=Input_Width*(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));}\nvoid Object_To_World_Dir_B67(\nvec3 Dir_Object,\nout vec3 Dir_World)\n{Dir_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid main()\n{vec3 Active_Face_Center_Q49;Active_Face_Center_Q49=(world*vec4(_Active_Face_Dir_*0.5,1.0)).xyz;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));vec3 Active_Face_Dir_Q64=normalize((world*vec4(_Active_Face_Dir_,0.0)).xyz);float Relative_Scale_Q57;\n#if RELATIVE_WIDTH\nRelative_Scale_Q57=length((world*vec4(vec3(0,1,0),0.0)).xyz);\n#else\nRelative_Scale_Q57=1.0;\n#endif\nvec3 Tangent_World_Q30;Tangent_World_Q30=(world*vec4(tangent,0.0)).xyz;vec3 Binormal_World_Q31;Binormal_World_Q31=(world*vec4((cross(normal,tangent)),0.0)).xyz;vec3 Normal_World_Q60;Normal_World_Q60=(world*vec4(normal,0.0)).xyz;vec3 Result_Q18=0.5*normal;vec3 Dir_World_Q67;Object_To_World_Dir_B67(_Active_Face_Up_,Dir_World_Q67);float Product_Q56=_Edge_Width_*Relative_Scale_Q57;vec3 Normal_World_N_Q29=normalize(Normal_World_Q60);vec3 Tangent_World_N_Q28=normalize(Tangent_World_Q30);vec3 Binormal_World_N_Q32=normalize(Binormal_World_Q31);vec3 Position_Q38;float Near_Size_Q38;float Inner_Fade_Q38;float Blob_Enable_Q38;float Fade_Q38;float Pulse_Q38;Choose_Blob_B38(color,Blob_Position_Q41,Blob_Position_Q42,_Blob_Enable_,_Blob_Enable_2_,_Blob_Near_Size_,_Blob_Near_Size_2_,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q38,Near_Size_Q38,Inner_Fade_Q38,Blob_Enable_Q38,Fade_Q38,Pulse_Q38);vec3 Face_Center_Q33;Face_Center_Q33=(world*vec4(Result_Q18,1.0)).xyz;vec2 Face_Size_Q50=vec2(length(Tangent_World_Q30),length(Binormal_World_Q31));float Show_Selection_Q48;Selection_Vertex_B48(Blob_Position_Q41,Blob_Position_Q42,Face_Center_Q33,Face_Size_Q50,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,Active_Face_Dir_Q64,Show_Selection_Q48);vec3 Normalized_Q72=normalize(Dir_World_Q67);float Active_Q34=max(0.0,dot(Active_Face_Dir_Q64,Normal_World_N_Q29));float Width_Q54;Proximity_Visibility_B54(Show_Selection_Q48,Blob_Position_Q41,Blob_Position_Q42,Product_Q56,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Active_Face_Center_Q49,Active_Face_Dir_Q64,Width_Q54);vec3 Wire_Vx_Pos_Q51;vec2 UV_Q51;vec2 Widths_Q51;Wireframe_Vertex_B51(position,normal,tangent,(cross(normal,tangent)),Width_Q54,Face_Size_Q50,Wire_Vx_Pos_Q51,UV_Q51,Widths_Q51);vec3 Vec3_Q27=vec3(Widths_Q51.x,Widths_Q51.y,color.r);vec3 Pos_World_Q13;Object_To_World_Pos_B13(Wire_Vx_Pos_Q51,Pos_World_Q13);vec3 Incident_Q36=normalize(Pos_World_Q13-cameraPosition);vec3 Out_Position_Q47;vec2 Out_UV_Q47;vec3 Blob_Info_Q47;Blob_Vertex_B47(Pos_World_Q13,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,Position_Q38,_Blob_Intensity_,Near_Size_Q38,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q33,Face_Size_Q50,UV_Q51,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q38,Active_Face_Center_Q49,Pulse_Q38,Fade_Q38,Blob_Enable_Q38,Out_Position_Q47,Out_UV_Q47,Blob_Info_Q47);vec4 Extra1_Q66;float Distance_To_Face_Q66;float Intensity_Q66;Proximity_Vertex_B66(Blob_Position_Q41,Blob_Position_Q42,Active_Face_Center_Q49,Active_Face_Dir_Q64,Pos_World_Q13,_Proximity_Far_Distance_,Relative_Scale_Q57,_Proximity_Anisotropy_,Normalized_Q72,Extra1_Q66,Distance_To_Face_Q66,Intensity_Q66);vec4 Holo_Edges_Q44;Holo_Edge_Vertex_B44(Incident_Q36,Normal_World_N_Q29,uv,Tangent_World_Q30,Binormal_World_Q31,_Smooth_Active_Face_,Active_Q34,Holo_Edges_Q44);vec3 Vec3_Q19=vec3(Show_Selection_Q48,Distance_To_Face_Q66,Intensity_Q66);vec3 Position=Out_Position_Q47;vec2 UV=Out_UV_Q47;vec3 Tangent=Blob_Info_Q47;vec3 Binormal=Vec3_Q19;vec3 Normal=Vec3_Q27;vec4 Extra1=Extra1_Q66;vec4 Color=Holo_Edges_Q44;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;}";class Hw extends Oa{constructor(){super(),this.RELATIVE_WIDTH=!0,this.ENABLE_FADE=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class Xw extends Ra{constructor(e,t){super(e,t),this.edgeWidth=.04,this.edgeColor=new Ee(.592157,.592157,.592157,1),this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=1.5,this.proximityAnisotropy=1,this.selectionFuzz=.5,this.selected=0,this.selectionFade=0,this.selectionFadeSize=.3,this.selectedDistance=.08,this.selectedFadeLength=.08,this.blobIntensity=.5,this.blobFarSize=.05,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.leftBlobEnable=!0,this.leftBlobNearSize=.025,this.leftBlobPulse=0,this.leftBlobFade=1,this.leftBlobInnerFade=.01,this.rightBlobEnable=!0,this.rightBlobNearSize=.025,this.rightBlobPulse=0,this.rightBlobFade=1,this.rightBlobInnerFade=.01,this.activeFaceDir=new de(0,0,-1),this.activeFaceUp=new de(0,1,0),this.enableFade=!0,this.fadeWidth=1.5,this.smoothActiveFace=!0,this.showFrame=!1,this.useBlobTexture=!0,this.globalLeftIndexTipPosition=de.Zero(),this.globalRightIndexTipPosition=de.Zero(),this.alphaMode=Yd.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Vo(Xw.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new Hw);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!0,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="fluentButton",a=s.toString(),l=["world","viewProjection","cameraPosition","_Edge_Width_","_Edge_Color_","_Relative_Width_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Active_Face_Dir_","_Active_Face_Up_","_Enable_Fade_","_Fade_Width_","_Smooth_Active_Face_","_Show_Frame_","_Use_Blob_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Blob_Texture_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setColor4("_Edge_Color_",new Ce(this.edgeColor.r,this.edgeColor.g,this.edgeColor.b),this.edgeColor.a),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Blob_Enable_",this.leftBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.leftBlobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.leftBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.leftBlobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.leftBlobFade),this._activeEffect.setFloat("_Blob_Enable_2_",this.rightBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.rightBlobNearSize),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.rightBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_2_",this.rightBlobPulse),this._activeEffect.setFloat("_Blob_Fade_2_",this.rightBlobFade),this._activeEffect.setVector3("_Active_Face_Dir_",this.activeFaceDir),this._activeEffect.setVector3("_Active_Face_Up_",this.activeFaceUp),this._activeEffect.setFloat("_Fade_Width_",this.fadeWidth),this._activeEffect.setFloat("_Smooth_Active_Face_",this.smoothActiveFace?1:0),this._activeEffect.setFloat("_Show_Frame_",this.showFrame?1:0),this._activeEffect.setFloat("_Use_Blob_Texture_",this.useBlobTexture?1:0),this._activeEffect.setFloat("Use_Global_Left_Index",1),this._activeEffect.setFloat("Use_Global_Right_Index",1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",new _e(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1)),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",new _e(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new Xw(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentButtonMaterial",e}getClassName(){return"FluentButtonMaterial"}static Parse(e,t,i){return yt.Parse((()=>new Xw(e.name,t)),e,t,i)}}Xw.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-button-blob.png",qe([st()],Xw.prototype,"edgeWidth",void 0),qe([ut()],Xw.prototype,"edgeColor",void 0),qe([st()],Xw.prototype,"proximityMaxIntensity",void 0),qe([st()],Xw.prototype,"proximityFarDistance",void 0),qe([st()],Xw.prototype,"proximityNearRadius",void 0),qe([st()],Xw.prototype,"proximityAnisotropy",void 0),qe([st()],Xw.prototype,"selectionFuzz",void 0),qe([st()],Xw.prototype,"selected",void 0),qe([st()],Xw.prototype,"selectionFade",void 0),qe([st()],Xw.prototype,"selectionFadeSize",void 0),qe([st()],Xw.prototype,"selectedDistance",void 0),qe([st()],Xw.prototype,"selectedFadeLength",void 0),qe([st()],Xw.prototype,"blobIntensity",void 0),qe([st()],Xw.prototype,"blobFarSize",void 0),qe([st()],Xw.prototype,"blobNearDistance",void 0),qe([st()],Xw.prototype,"blobFarDistance",void 0),qe([st()],Xw.prototype,"blobFadeLength",void 0),qe([st()],Xw.prototype,"leftBlobEnable",void 0),qe([st()],Xw.prototype,"leftBlobNearSize",void 0),qe([st()],Xw.prototype,"leftBlobPulse",void 0),qe([st()],Xw.prototype,"leftBlobFade",void 0),qe([st()],Xw.prototype,"leftBlobInnerFade",void 0),qe([st()],Xw.prototype,"rightBlobEnable",void 0),qe([st()],Xw.prototype,"rightBlobNearSize",void 0),qe([st()],Xw.prototype,"rightBlobPulse",void 0),qe([st()],Xw.prototype,"rightBlobFade",void 0),qe([st()],Xw.prototype,"rightBlobInnerFade",void 0),qe([lt()],Xw.prototype,"activeFaceDir",void 0),qe([lt()],Xw.prototype,"activeFaceUp",void 0),qe([st()],Xw.prototype,"enableFade",void 0),qe([st()],Xw.prototype,"fadeWidth",void 0),qe([st()],Xw.prototype,"smoothActiveFace",void 0),qe([st()],Xw.prototype,"showFrame",void 0),qe([st()],Xw.prototype,"useBlobTexture",void 0),qe([lt()],Xw.prototype,"globalLeftIndexTipPosition",void 0),qe([lt()],Xw.prototype,"globalRightIndexTipPosition",void 0),ee("BABYLON.GUI.FluentButtonMaterial",Xw);class Yw extends Dw{constructor(e,t){super(e),this._isNearPressed=!1,this._interactionSurfaceHeight=0,this._isToggleButton=!1,this._toggleState=!1,this._toggleButtonCallback=()=>{this._onToggle(!this._toggleState)},this.onToggleObservable=new X,this.collidableFrontDirection=de.Zero(),t&&(this.collisionMesh=t)}get isActiveNearInteraction(){return this._isNearPressed}set collidableFrontDirection(e){if(this._collidableFrontDirection=e.normalize(),this._collisionMesh){const e=ge.Matrix[0];e.copyFrom(this._collisionMesh.getWorldMatrix()),e.invert(),de.TransformNormalToRef(this._collidableFrontDirection,e,this._collidableFrontDirection),this._collidableFrontDirection.normalize()}}get collidableFrontDirection(){if(this._collisionMesh){const e=ge.Vector3[0];return de.TransformNormalToRef(this._collidableFrontDirection,this._collisionMesh.getWorldMatrix(),e),e.normalize()}return this._collidableFrontDirection}set collisionMesh(e){this._collisionMesh&&(this._collisionMesh.isNearPickable=!1,this._collisionMesh.reservedDataStore?.GUI3D&&(this._collisionMesh.reservedDataStore.GUI3D={}),this._collisionMesh.getChildMeshes().forEach((e=>{e.isNearPickable=!1,e.reservedDataStore?.GUI3D&&(e.reservedDataStore.GUI3D={})}))),this._collisionMesh=e,this._injectGUI3DReservedDataStore(this._collisionMesh).control=this,this._collisionMesh.isNearPickable=!0,this._collisionMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this,e.isNearPickable=!0})),this.collidableFrontDirection=e.forward}set isToggleButton(e){e!==this._isToggleButton&&(this._isToggleButton=e,e?this.onPointerUpObservable.add(this._toggleButtonCallback):(this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this._toggleState&&this._onToggle(!1)))}get isToggleButton(){return this._isToggleButton}set isToggled(e){this._isToggleButton&&this._toggleState!==e&&this._onToggle(e)}get isToggled(){return this._toggleState}_onToggle(e){this._toggleState=e,this.onToggleObservable.notifyObservers(e)}_isInteractionInFrontOfButton(e){return this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition())>0}getPressDepth(e){if(!this._isNearPressed)return 0;const t=this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition());return this._interactionSurfaceHeight-t}_getInteractionHeight(e,t){const i=this.collidableFrontDirection;if(0===i.length())return de.Distance(e,t);const s=de.Dot(t,i);return de.Dot(e,i)-s}_generatePointerEventType(e,t,i){if(e===Ms.POINTERDOWN||e===Ms.POINTERMOVE){if(!this._isInteractionInFrontOfButton(t))return Ms.POINTERMOVE;this._isNearPressed=!0,this._interactionSurfaceHeight=this._getInteractionHeight(t,this._collisionMesh.getAbsolutePosition())}if(e===Ms.POINTERUP){if(0==i)return Ms.POINTERMOVE;this._isNearPressed=!1}return e}_getTypeName(){return"TouchButton3D"}_createNode(e){return super._createNode(e)}dispose(){super.dispose(),this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this.onToggleObservable.clear(),this._collisionMesh&&this._collisionMesh.dispose()}}class Qw extends Yw{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=ta("",{size:1},this._backPlate._scene);const t=ta("",{size:1,sideOrientation:bo.DOUBLESIDE},this._backPlate._scene),i=new yc("",this._backPlate._scene);i.diffuseColor=Ce.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=de.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=de.Up().scale(.7).add(de.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=Cw.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new UD,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new qo,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._isBackplateVisible=!0,this._frontPlateDepth=.5,this._backPlateDepth=.04,this._backplateColor=new Ce(.08,.15,.55),this._backplateToggledColor=new Ce(.25,.4,.95),this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontMaterial.leftBlobEnable=!0,this._frontMaterial.rightBlobEnable=!0},this.pointerOutAnimation=()=>{this._frontMaterial.leftBlobEnable=!1,this._frontMaterial.rightBlobEnable=!1},this.pointerDownAnimation=()=>{this._frontPlate&&!this.isActiveNearInteraction&&(this._frontPlate.scaling.z=.2*this._frontPlateDepth,this._frontPlate.position=de.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-.2*this._frontPlateDepth)/2),this._textPlate.position=de.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+.2*this._frontPlateDepth)/2))},this.pointerUpAnimation=()=>{this._frontPlate&&(this._frontPlate.scaling.z=this._frontPlateDepth,this._frontPlate.position=de.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-this._frontPlateDepth)/2),this._textPlate.position=de.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+this._frontPlateDepth)/2))},this.onPointerMoveObservable.add((e=>{if(this._frontPlate&&this.isActiveNearInteraction){const t=de.Zero();if(this._backPlate.getWorldMatrix().decompose(t,void 0,void 0)){let i=this._getInteractionHeight(e,this._backPlate.getAbsolutePosition())/t.z;i=xe.Clamp(i-this._backPlateDepth/2,.2*this._frontPlateDepth,this._frontPlateDepth),this._frontPlate.scaling.z=i,this._frontPlate.position=de.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-i)/2),this._textPlate.position=de.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+i)/2)}}})),this._pointerHoverObserver=this.onPointerMoveObservable.add((e=>{this._frontMaterial.globalLeftIndexTipPosition=e}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new WD;if(e.isVertical=!0,Vt()&&document.createElement&&this._imageUrl){const t=new GD;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new UD;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this.content=e}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=yu(`${this.name}_collisionMesh`,{width:1,height:1,depth:this._frontPlateDepth},e);t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=de.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),Pa.ImportMeshAsync(void 0,Qw.MODEL_BASE_URL,Qw.MODEL_FILENAME,e).then((i=>{const s=yu("${this.name}_alphaMesh",{width:1,height:1,depth:1},e);s.isPickable=!1,s.material=new yc("${this.name}_alphaMesh_material",e),s.material.alpha=.15;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.z=this._frontPlateDepth,s.parent=r,r.parent=t,this._frontMaterial&&(r.material=this._frontMaterial),this._frontPlate=r})),this._backPlate=yu(`${this.name}_backPlate`,{width:1,height:1,depth:this._backPlateDepth},e),this._backPlate.position=de.Forward(e.useRightHandedSystem).scale(this._backPlateDepth/2),this._backPlate.isPickable=!1,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.position=de.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),this._backPlate.addChild(t),this._backPlate.addChild(this._textPlate);const i=new xn("{this.name}_root",e);return this._backPlate.setParent(i),this.collisionMesh=t,this.collidableFrontDirection=this._backPlate.forward.negate(),i}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=new Ce(.4,.4,.4)}_createBackMaterial(e){this._backMaterial=new Lw(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.albedoColor=this._backplateColor,this._backMaterial.renderBorders=!0,this._backMaterial.renderHoverLight=!1}_createFrontMaterial(e){this._frontMaterial=new Xw(this.name+"Front Material",e.getScene())}_createPlateMaterial(e){this._plateMaterial=new yc(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ce.Black()}_onToggle(e){this._backMaterial&&(this._backMaterial.albedoColor=e?this._backplateToggledColor:this._backplateColor),super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.backFluentMaterial?this._backMaterial=this._host._touchSharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.backFluentMaterial=this._backMaterial),this._host._touchSharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._touchSharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerMoveObservable.remove(this._pointerHoverObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}Qw.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",Qw.MODEL_FILENAME="mrtk-fluent-button.glb";class jw{constructor(){this.followBehaviorEnabled=!1,this.sixDofDragBehaviorEnabled=!0,this.surfaceMagnetismBehaviorEnabled=!0,this._followBehavior=new la,this._sixDofDragBehavior=new oa,this._surfaceMagnetismBehavior=new aa}get name(){return"Default"}get followBehavior(){return this._followBehavior}get sixDofDragBehavior(){return this._sixDofDragBehavior}get surfaceMagnetismBehavior(){return this._surfaceMagnetismBehavior}init(){}attach(e,t,i){this._scene=e.getScene(),this.attachedNode=e,this._addObservables(),this._followBehavior.attach(e),this._sixDofDragBehavior.attach(e),this._sixDofDragBehavior.draggableMeshes=t||null,this._sixDofDragBehavior.faceCameraOnDragStart=!0,this._surfaceMagnetismBehavior.attach(e,this._scene),i&&(this._surfaceMagnetismBehavior.meshes=i),this._surfaceMagnetismBehavior.enabled=!1}detach(){this.attachedNode=null,this._removeObservables(),this._followBehavior.detach(),this._sixDofDragBehavior.detach(),this._surfaceMagnetismBehavior.detach()}_addObservables(){this._onBeforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{this._followBehavior._enabled=!this._sixDofDragBehavior.isMoving&&this.followBehaviorEnabled})),this._onDragObserver=this._sixDofDragBehavior.onDragObservable.add((e=>{this._sixDofDragBehavior.disableMovement=this._surfaceMagnetismBehavior.findAndUpdateTarget(e.pickInfo)}))}_removeObservables(){this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._sixDofDragBehavior.onDragObservable.remove(this._onDragObserver)}}bi.ShadersStore.handleVertexShader="precision highp float;attribute vec3 position;uniform vec3 positionOffset;uniform mat4 worldViewProjection;uniform float scale;void main(void) {vec4 vPos=vec4((vec3(position)+positionOffset)*scale,1.0);gl_Position=worldViewProjection*vPos;}";bi.ShadersStore.handlePixelShader="uniform vec3 color;void main(void) {gl_FragColor=vec4(color,1.0);}";class Kw extends Yu{get hover(){return this._hover}set hover(e){this._hover=e,this._updateInterpolationTarget()}get drag(){return this._drag}set drag(e){this._drag=e,this._updateInterpolationTarget()}constructor(e,t){super(e,t,"handle",{attributes:["position"],uniforms:["worldViewProjection","color","scale","positionOffset"],needAlphaBlending:!1,needAlphaTesting:!1}),this._hover=!1,this._drag=!1,this._color=new Ce,this._scale=1,this._lastTick=-1,this.animationLength=100,this.hoverColor=new Ce(0,.467,.84),this.baseColor=new Ce(1,1,1),this.hoverScale=.75,this.baseScale=.35,this.dragScale=.55,this._positionOffset=de.Zero(),this._updateInterpolationTarget(),this._lastTick=Date.now(),this._onBeforeRender=this.getScene().onBeforeRenderObservable.add((()=>{const e=Date.now(),t=e-this._lastTick,i=this._targetScale-this._scale,s=Ae.Color3[0].copyFrom(this._targetColor).subtractToRef(this._color,Ae.Color3[0]);this._scale=this._scale+i*t/this.animationLength,s.scaleToRef(t/this.animationLength,s),this._color.addToRef(s,this._color),this.setColor3("color",this._color),this.setFloat("scale",this._scale),this.setVector3("positionOffset",this._positionOffset),this._lastTick=e}))}_updateInterpolationTarget(){this.drag?(this._targetColor=this.hoverColor,this._targetScale=this.dragScale):this.hover?(this._targetColor=this.hoverColor,this._targetScale=this.hoverScale):(this._targetColor=this.baseColor,this._targetScale=this.baseScale)}dispose(){super.dispose(),this.getScene().onBeforeRenderObservable.remove(this._onBeforeRender)}}var $w;!function(e){e[e.IDLE=0]="IDLE",e[e.HOVER=1]="HOVER",e[e.DRAG=2]="DRAG"}($w||($w={}));class qw{get state(){return this._state}get gizmo(){return this._gizmo}set hover(e){e?this._state|=$w.HOVER:this._state&=~$w.HOVER,this._updateMaterial()}set drag(e){e?this._state|=$w.DRAG:this._state&=~$w.DRAG,this._updateMaterial()}constructor(e,t){this._state=$w.IDLE,this._materials=[],this._scene=t,this._gizmo=e,this.node=this.createNode(),this.node.reservedDataStore={handle:this}}_createMaterial(e){const t=new Kw("handle",this._scene);return e&&(t._positionOffset=e),t}_updateMaterial(){const e=this._state;for(const e of this._materials)e.hover=!1,e.drag=!1;if(e&$w.DRAG)for(const e of this._materials)e.drag=!0;else if(e&$w.HOVER)for(const e of this._materials)e.hover=!0}setDragBehavior(e,t,i){const s=new na;this._dragBehavior=s,this._dragStartObserver=s.onDragStartObservable.add(e),this._draggingObserver=s.onDragObservable.add(t),this._dragEndObserver=s.onDragEndObservable.add(i),this._dragBehavior.attach(this.node)}dispose(){this._dragBehavior.onDragStartObservable.remove(this._dragStartObserver),this._dragBehavior.onDragObservable.remove(this._draggingObserver),this._dragBehavior.onDragEndObservable.remove(this._dragEndObserver),this._dragBehavior.detach();for(const e of this._materials)e.dispose();this.node.dispose()}}class Zw extends qw{createNode(){const e=yu("sideVert",{width:1,height:10,depth:.1},this._scene),t=new xn("side",this._scene);e.parent=t;const i=this._createMaterial();return e.material=i,e.isNearGrabbable=!0,this._materials.push(i),t}}class Jw extends qw{createNode(){const e=yu("angleHor",{width:3,height:1,depth:.1},this._scene),t=yu("angleVert",{width:1,height:3,depth:.1},this._scene),i=new xn("angle",this._scene);return e.parent=i,t.parent=i,e.material=this._createMaterial(new de(1,0,0)),t.material=this._createMaterial(new de(0,1,0)),t.isNearGrabbable=!0,e.isNearGrabbable=!0,this._materials.push(e.material),this._materials.push(t.material),i}}class eN extends fu{set attachedSlate(e){e?(this.attachedMesh=e.mesh,this.updateBoundingBox(),this._pickedPointObserver=e._host.onPickingObservable.add((e=>{if(!this._handleHovered||e&&e.parent===this._handleHovered.node||(this._handleHovered.hover=!1,this._handleHovered=null),e&&e.parent&&e.parent.reservedDataStore&&e.parent.reservedDataStore.handle){const t=e.parent.reservedDataStore.handle;t.gizmo===this&&(this._handleHovered=t,this._handleHovered.hover=!0)}}))):this._attachedSlate&&this._attachedSlate._host.onPickingObservable.remove(this._pickedPointObserver),this._attachedSlate=e}get attachedSlate(){return this._attachedSlate}constructor(e){super(e),this._boundingDimensions=new de(0,0,0),this._renderObserver=null,this._tmpQuaternion=new pe,this._tmpVector=new de(0,0,0),this._corners=[],this._sides=[],this._boundingBoxGizmo={min:new de,max:new de},this._margin=.35,this._handleSize=.075,this._attachedSlate=null,this._existingSlateScale=new de,this.fixedScreenSize=!1,this.fixedScreenSizeDistanceFactor=10,this._createNode(),this.updateScale=!1,this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingSlateScale.equals(this.attachedMesh.scaling)&&this.updateBoundingBox()}))}_createNode(){this._handlesParent=new xn("handlesParent",this.gizmoLayer.utilityLayerScene),this._handlesParent.rotationQuaternion=pe.Identity();const e=[{dimensions:new de(-1,-1,0),origin:new de(1,0,0)},{dimensions:new de(1,-1,0),origin:new de(0,0,0)},{dimensions:new de(1,1,0),origin:new de(0,1,0)},{dimensions:new de(-1,1,0),origin:new de(1,1,0)}];for(let t=0;t<4;t++){const i=new Jw(this,this.gizmoLayer.utilityLayerScene);this._corners.push(i),i.node.rotation.z=Math.PI/2*t,i.node.parent=this._handlesParent,this._assignDragBehaviorCorners(i,((e,t,i,s)=>this._moveHandle(e,t,i,s,!0)),e[t])}for(let e=0;e<4;e++){const t=new Zw(this,this.gizmoLayer.utilityLayerScene);this._sides.push(t),t.node.rotation.z=Math.PI/2*e,t.node.parent=this._handlesParent,this._assignDragBehaviorSides(t,e%2==0?new de(0,1,0):new de(1,0,0))}this._handlesParent.parent=this._rootMesh}_keepAspectRatio(e,t,i=!1){const s=ge.Vector3[0];s.copyFromFloats(t,1,0).normalize(),i&&(s.y*=-1);const r=de.Dot(e,s);e.copyFrom(s).scaleInPlace(r)}_clampDimensions(e,t,i,s=!1){const r=ge.Vector3[0];r.copyFrom(e).multiplyInPlace(i);const n=ge.Vector3[1];if(n.copyFromFloats(Math.max(this._attachedSlate.minDimensions.x,r.x+t.x),Math.max(this._attachedSlate.minDimensions.y,r.y+t.y),0),s){const e=t.x/t.y;n.x=Math.max(n.x,n.y*e),n.y=Math.max(n.y,n.x/e)}r.copyFrom(n).subtractInPlace(t),e.x=Math.sign(e.x)*Math.abs(r.x),e.y=Math.sign(e.y)*Math.abs(r.y)}_moveHandle(e,t,i,s,r){if(!this._attachedSlate)return;if(r){const e=t.x/t.y;this._keepAspectRatio(i,e,s.dimensions.x*s.dimensions.y<0)}this._clampDimensions(i,t,s.dimensions,r);const n=ge.Vector3[0],o=ge.Vector3[1];n.copyFrom(i).multiplyInPlace(s.origin),o.copyFrom(i).multiplyInPlace(s.dimensions),this._attachedSlate.origin.copyFrom(e).addInPlace(n),this._attachedSlate.dimensions.set(t.x+o.x,t.y+o.y)}_assignDragBehaviorCorners(e,t,i){const s=new de,r=new de,n=new de,o=new fe,a=new de;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(s.set(this.attachedSlate.dimensions.x,this.attachedSlate.dimensions.y,K),r.copyFrom(this.attachedSlate.origin),n.copyFrom(e.position),o.copyFrom(this.attachedMesh.computeWorldMatrix(!0)),o.invert(),this.attachedSlate._followButton.isToggled=!1,de.TransformNormalToRef(de.Forward(),this.attachedMesh.getWorldMatrix(),a),a.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{this.attachedSlate&&this.attachedMesh&&(((e,t,i,s)=>{e.subtractToRef(i,ge.Vector3[0]);const r=de.Dot(ge.Vector3[0],t);ge.Vector3[1].copyFrom(t).scaleInPlace(r),ge.Vector3[0].subtractInPlace(ge.Vector3[1]),ge.Vector3[0].addToRef(i,s)})(e.position,a,n,this._tmpVector),this._tmpVector.subtractInPlace(n),de.TransformNormalToRef(this._tmpVector,o,this._tmpVector),t(r,s,this._tmpVector,i),this.attachedSlate._positionElements(),this.updateBoundingBox())}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_assignDragBehaviorSides(e,t){const i=new pe,s=new de,r=new de,n=new de,o=new de;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(i.copyFrom(this.attachedMesh.rotationQuaternion),s.copyFrom(e.position),n.copyFrom(this.attachedMesh.getAbsolutePivotPoint()),r.copyFrom(s).subtractInPlace(n).normalize(),this.attachedSlate._followButton.isToggled=!1,de.TransformNormalToRef(t,this.attachedMesh.getWorldMatrix(),o),o.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{if(this.attachedSlate&&this.attachedMesh){this._tmpVector.copyFrom(e.position),this._tmpVector.subtractInPlace(n),this._tmpVector.normalize();const s=-de.GetAngleBetweenVectorsOnPlane(this._tmpVector,r,o);pe.RotationAxisToRef(t,s,this._tmpQuaternion),i.multiplyToRef(this._tmpQuaternion,this.attachedMesh.rotationQuaternion)}}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_attachedNodeChanged(e){e&&this.updateBoundingBox()}updateBoundingBox(){if(this.attachedMesh){Jo._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=pe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._boundingBoxGizmo.min=t.min,this._boundingBoxGizmo.max=t.max,this._updateHandlesPosition(),this._updateHandlesScaling(),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),Jo._RestorePivotPoint(this.attachedMesh),this.attachedMesh.setParent(e),this.attachedMesh.computeWorldMatrix(!0),this._existingSlateScale.copyFrom(this.attachedMesh.scaling)}}_updateHandlesPosition(){const e=this._boundingBoxGizmo.min.clone(),t=this._boundingBoxGizmo.max.clone(),i=this._corners[0].node.scaling.length();e.x-=this._margin*i,e.y-=this._margin*i,t.x+=this._margin*i,t.y+=this._margin*i;const s=e.add(t).scaleInPlace(.5);this._corners[0].node.position.copyFromFloats(e.x,e.y,0),this._corners[1].node.position.copyFromFloats(t.x,e.y,0),this._corners[2].node.position.copyFromFloats(t.x,t.y,0),this._corners[3].node.position.copyFromFloats(e.x,t.y,0),this._sides[0].node.position.copyFromFloats(e.x,s.y,0),this._sides[1].node.position.copyFromFloats(s.x,e.y,0),this._sides[2].node.position.copyFromFloats(t.x,s.y,0),this._sides[3].node.position.copyFromFloats(s.x,t.y,0)}_updateHandlesScaling(){if(this._attachedSlate&&this._attachedSlate.mesh){const e=this._attachedSlate.mesh.scaling.x*this._attachedSlate.dimensions.x,t=this._attachedSlate.mesh.scaling.y*this._attachedSlate.dimensions.y,i=Math.min(e,t)*this._handleSize;for(let e=0;ei?this.minDimensions.x/e.x:this.minDimensions.y/e.y}this._dimensions.copyFrom(e).scaleInPlace(t),this._updatePivot(),this._positionElements()}get titleBarHeight(){return this._titleBarHeight}set titleBarHeight(e){this._titleBarHeight=e}set renderingGroupId(e){this._titleBar.renderingGroupId=e,this._titleBarTitle.renderingGroupId=e,this._contentPlate.renderingGroupId=e,this._backPlate.renderingGroupId=e}get renderingGroupId(){return this._titleBar.renderingGroupId}set title(e){this._titleText=e,this._titleTextComponent&&(this._titleTextComponent.text=e)}get title(){return this._titleText}constructor(e){super(e),this.titleBarMargin=.005,this.origin=new de(0,0,0),this._dimensions=new ue(21.875,12.5),this._titleBarHeight=.625,this._titleText="",this._contentScaleRatio=1,this.minDimensions=new ue(15.625,6.25),this.defaultDimensions=this._dimensions.clone(),this._followButton=new Qw("followButton"+this.name),this._followButton.isToggleButton=!0,this._closeButton=new Qw("closeButton"+this.name),this._contentViewport=new jr(0,0,1,1),this._contentDragBehavior=new sa({dragPlaneNormal:new de(0,0,-1)})}_applyFacade(e){this._contentMaterial.albedoTexture=e,this._resetContentPositionAndZoom(),this._applyContentViewport(),e.attachToMesh(this._contentPlate,!0)}_addControl(e){e._host=this._host,this._host.utilityLayer&&e._prepareNode(this._host.utilityLayer.utilityLayerScene)}_getTypeName(){return"HolographicSlate"}_positionElements(){const e=this._followButton,t=this._closeButton,i=this._titleBar,s=this._titleBarTitle,r=this._contentPlate,n=this._backPlate;if(e&&t&&i){t.scaling.setAll(this.titleBarHeight),e.scaling.setAll(this.titleBarHeight),t.position.copyFromFloats(this.dimensions.x-this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin),e.position.copyFromFloats(this.dimensions.x-3*this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin);const o=this.dimensions.y-this.titleBarHeight-this.titleBarMargin,a=r.getScene().useRightHandedSystem;i.scaling.set(this.dimensions.x,this.titleBarHeight,K),s.scaling.set(this.dimensions.x-2*this.titleBarHeight,this.titleBarHeight,K),r.scaling.copyFromFloats(this.dimensions.x,o,K),n.scaling.copyFromFloats(this.dimensions.x,o,K),i.position.copyFromFloats(this.dimensions.x/2,-this.titleBarHeight/2,0).addInPlace(this.origin),s.position.copyFromFloats(this.dimensions.x/2-this.titleBarHeight,-this.titleBarHeight/2,a?K:-K).addInPlace(this.origin),r.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),0).addInPlace(this.origin),n.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),a?-K:K).addInPlace(this.origin),this._titleTextComponent.host.scaleTo(tN._DEFAULT_TEXT_RESOLUTION_Y*s.scaling.x/s.scaling.y,tN._DEFAULT_TEXT_RESOLUTION_Y);const l=this.dimensions.x/o;this._contentViewport.width=this._contentScaleRatio,this._contentViewport.height=this._contentScaleRatio/l,this._applyContentViewport(),this._gizmo&&this._gizmo.updateBoundingBox()}}_applyContentViewport(){if(this._contentPlate?.material&&this._contentPlate.material.albedoTexture){const e=this._contentPlate.material.albedoTexture;e.uScale=this._contentScaleRatio,e.vScale=this._contentScaleRatio/this._contentViewport.width*this._contentViewport.height,e.uOffset=this._contentViewport.x,e.vOffset=this._contentViewport.y}}_resetContentPositionAndZoom(){this._contentViewport.x=0,this._contentViewport.y=1-this._contentViewport.height/this._contentViewport.width,this._contentScaleRatio=1}_updatePivot(){if(!this.mesh)return;const e=new de(.5*this.dimensions.x,.5*-this.dimensions.y,K);e.addInPlace(this.origin),e.z=0;const t=new de(0,0,0);de.TransformCoordinatesToRef(t,this.mesh.computeWorldMatrix(!0),t),this.mesh.setPivotPoint(e);const i=new de(0,0,0);de.TransformCoordinatesToRef(i,this.mesh.computeWorldMatrix(!0),i),this.mesh.position.addInPlace(t).subtractInPlace(i)}_createNode(e){const t=new bo("slate_"+this.name,e);this._titleBar=yu("titleBar_"+this.name,{size:1},e),this._titleBarTitle=ta("titleText_"+this.name,{size:1},e),this._titleBarTitle.parent=t,this._titleBarTitle.isPickable=!1;const i=Cw.CreateForMesh(this._titleBarTitle);if(this._titleTextComponent=new UD("titleText_"+this.name,this._titleText),this._titleTextComponent.textWrapping=VD.Ellipsis,this._titleTextComponent.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,this._titleTextComponent.color="white",this._titleTextComponent.fontSize=tN._DEFAULT_TEXT_RESOLUTION_Y/2,this._titleTextComponent.paddingLeft=tN._DEFAULT_TEXT_RESOLUTION_Y/4,i.addControl(this._titleTextComponent),e.useRightHandedSystem){const t=new _e(0,0,1,1);this._contentPlate=ta("contentPlate_"+this.name,{size:1,sideOrientation:cn.BACKSIDE,frontUVs:t},e),this._backPlate=ta("backPlate_"+this.name,{size:1,sideOrientation:cn.FRONTSIDE},e)}else{const t=new _e(0,0,1,1);this._contentPlate=ta("contentPlate_"+this.name,{size:1,sideOrientation:cn.FRONTSIDE,frontUVs:t},e),this._backPlate=ta("backPlate_"+this.name,{size:1,sideOrientation:cn.BACKSIDE},e)}this._titleBar.parent=t,this._titleBar.isNearGrabbable=!0,this._contentPlate.parent=t,this._backPlate.parent=t,this._attachContentPlateBehavior(),this._addControl(this._followButton),this._addControl(this._closeButton);const s=this._followButton,r=this._closeButton;return s.node.parent=t,r.node.parent=t,this._positionElements(),this._followButton.imageUrl=tN.ASSETS_BASE_URL+tN.FOLLOW_ICON_FILENAME,this._closeButton.imageUrl=tN.ASSETS_BASE_URL+tN.CLOSE_ICON_FILENAME,this._followButton.isBackplateVisible=!1,this._closeButton.isBackplateVisible=!1,this._followButton.onToggleObservable.add((e=>{this._defaultBehavior.followBehaviorEnabled=e,this._defaultBehavior.followBehaviorEnabled&&this._defaultBehavior.followBehavior.recenter()})),this._closeButton.onPointerClickObservable.add((()=>{this.dispose()})),t.rotationQuaternion=pe.Identity(),t.isVisible=!1,t}_attachContentPlateBehavior(){this._contentDragBehavior.attach(this._contentPlate),this._contentDragBehavior.moveAttached=!1,this._contentDragBehavior.useObjectOrientationForDragging=!0,this._contentDragBehavior.updateDragPlane=!1;const e=new de,t=new de,i=new de,s=new de,r=new ue;let n,o;this._contentDragBehavior.onDragStartObservable.add((r=>{this.node&&(n=this._contentViewport.clone(),o=this.node.computeWorldMatrix(!0),e.copyFrom(r.dragPlanePoint),t.set(this.dimensions.x,this.dimensions.y,K),t.y-=this.titleBarHeight+this.titleBarMargin,de.TransformNormalToRef(t,o,t),i.copyFromFloats(0,1,0),de.TransformNormalToRef(i,o,i),s.copyFromFloats(1,0,0),de.TransformNormalToRef(s,o,s),i.normalize(),i.scaleInPlace(1/de.Dot(i,t)),s.normalize(),s.scaleInPlace(1/de.Dot(s,t)))}));const a=new de;this._contentDragBehavior.onDragObservable.add((t=>{a.copyFrom(t.dragPlanePoint),a.subtractInPlace(e),r.copyFromFloats(de.Dot(a,s),de.Dot(a,i)),this._contentViewport.x=xe.Clamp(n.x-a.x,0,1-this._contentViewport.width*this._contentScaleRatio),this._contentViewport.y=xe.Clamp(n.y-a.y,0,1-this._contentViewport.height*this._contentScaleRatio),this._applyContentViewport()}))}_affectMaterial(e){this._titleBarMaterial=new Gw(`${this.name} plateMaterial`,e.getScene()),this._contentMaterial=new Lw(`${this.name} contentMaterial`,e.getScene()),this._contentMaterial.renderBorders=!0,this._backMaterial=new Gw(`${this.name} backPlate`,e.getScene()),this._backMaterial.lineWidth=K,this._backMaterial.radius=.005,this._backMaterial.backFaceCulling=!0,this._titleBar.material=this._titleBarMaterial,this._contentPlate.material=this._contentMaterial,this._backPlate.material=this._backMaterial,this._resetContent(),this._applyContentViewport()}_prepareNode(e){super._prepareNode(e),this._gizmo=new eN(this._host.utilityLayer),this._gizmo.attachedSlate=this,this._defaultBehavior=new jw,this._defaultBehavior.attach(this.node,[this._titleBar]),this._defaultBehavior.sixDofDragBehavior.onDragStartObservable.add((()=>{this._followButton.isToggled=!1})),this._positionChangedObserver=this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.add((()=>{this._gizmo.updateBoundingBox()})),this._updatePivot(),this.resetDefaultAspectAndPose(!1)}resetDefaultAspectAndPose(e=!0){if(!this._host||!this._host.utilityLayer||!this.node)return;const t=this._host.utilityLayer.utilityLayerScene,i=t.activeCamera;if(i){const s=i.getWorldMatrix(),r=de.TransformNormal(de.Backward(t.useRightHandedSystem),s);this.origin.setAll(0),this._gizmo.updateBoundingBox();const n=this.node.getAbsolutePivotPoint();this.node.position.copyFrom(i.position).subtractInPlace(r).subtractInPlace(n),this.node.rotationQuaternion=pe.FromLookDirectionLH(r,new de(0,1,0)),e&&(this.dimensions=this.defaultDimensions)}}dispose(){super.dispose(),this._titleBarMaterial.dispose(),this._contentMaterial.dispose(),this._titleBar.dispose(),this._titleBarTitle.dispose(),this._contentPlate.dispose(),this._backPlate.dispose(),this._followButton.dispose(),this._closeButton.dispose(),this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.remove(this._positionChangedObserver),this._defaultBehavior.detach(),this._gizmo.dispose(),this._contentDragBehavior.detach()}}tN.ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",tN.CLOSE_ICON_FILENAME="IconClose.png",tN.FOLLOW_ICON_FILENAME="IconFollowMe.png",tN._DEFAULT_TEXT_RESOLUTION_Y=102.4;class iN extends Dw{constructor(e,t){super(t),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"MeshButton3D"}_createNode(e){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}class sN extends kw{get defaultBehavior(){return this._defaultBehavior}get isPinned(){return this._isPinned}set isPinned(e){this._pinButton.isToggled===e?(this._isPinned=e,this._defaultBehavior.followBehaviorEnabled=!e):this._pinButton.isToggled=e}_createPinButton(e){const t=new Qw("pin"+this.name,!1);return t.imageUrl=sN._ASSETS_BASE_URL+sN._PIN_ICON_FILENAME,t.parent=this,t._host=this._host,t.isToggleButton=!0,t.onToggleObservable.add((e=>{this.isPinned=e})),this._host.utilityLayer&&(t._prepareNode(this._host.utilityLayer.utilityLayerScene),t.scaling.scaleInPlace(kw.MENU_BUTTON_SCALE),t.node&&(t.node.parent=e)),t}_createNode(e){const t=super._createNode(e);return this._pinButton=this._createPinButton(t),this.isPinned=!1,this._defaultBehavior.attach(t,[this._backPlate]),this._defaultBehavior.followBehavior.ignoreCameraPitchAndRoll=!0,this._defaultBehavior.followBehavior.pitchOffset=-15,this._defaultBehavior.followBehavior.minimumDistance=.3,this._defaultBehavior.followBehavior.defaultDistance=.4,this._defaultBehavior.followBehavior.maximumDistance=.6,this._backPlate.isNearGrabbable=!0,t.isVisible=!1,t}_finalProcessing(){super._finalProcessing(),this._pinButton.position.copyFromFloats((this._backPlate.scaling.x+kw.MENU_BUTTON_SCALE)/2,this._backPlate.scaling.y/2,0)}constructor(e){super(e),this._isPinned=!1,this._defaultBehavior=new jw,this._dragObserver=this._defaultBehavior.sixDofDragBehavior.onDragObservable.add((()=>{this.isPinned=!0})),this.backPlateMargin=1}dispose(){super.dispose(),this._defaultBehavior.sixDofDragBehavior.onDragObservable.remove(this._dragObserver),this._defaultBehavior.detach()}}sN._ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",sN._PIN_ICON_FILENAME="IconPin.png";class rN extends Nw{_mapGridNode(e,t){const i=e.mesh;if(!i)return;e.position=t.clone();const s=ge.Vector3[0];switch(s.copyFrom(t),this.orientation){case ww.FACEORIGIN_ORIENTATION:case ww.FACEFORWARD_ORIENTATION:s.addInPlace(new de(0,0,1)),i.lookAt(s);break;case ww.FACEFORWARDREVERSED_ORIENTATION:case ww.FACEORIGINREVERSED_ORIENTATION:s.addInPlace(new de(0,0,-1)),i.lookAt(s)}}}class nN extends Nw{constructor(){super(...arguments),this._iteration=100}get iteration(){return this._iteration}set iteration(e){this._iteration!==e&&(this._iteration=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh,s=this._scatterMapping(t);if(i){switch(this.orientation){case ww.FACEORIGIN_ORIENTATION:case ww.FACEFORWARD_ORIENTATION:i.lookAt(new de(0,0,1));break;case ww.FACEFORWARDREVERSED_ORIENTATION:case ww.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new de(0,0,-1))}e.position=s}}_scatterMapping(e){return e.x=(1-2*Math.random())*this._cellWidth,e.y=(1-2*Math.random())*this._cellHeight,e}_finalProcessing(){const e=[];for(const t of this._children)t.mesh&&e.push(t.mesh);for(let t=0;t{const i=e.position.lengthSquared(),s=t.position.lengthSquared();return is?-1:0}));const t=Math.pow(this.margin,2),i=Math.max(this._cellWidth,this._cellHeight),s=ge.Vector2[0],r=ge.Vector3[0];for(let n=0;n0.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B50(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid50(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B65(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B74(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B64(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B108(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B114(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B75(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B36(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B37(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B105(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q85;XY_Q85=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q27;vec3 Tangent_World_N_Q27;float Tangent_Length_Q27;Tangent_World_Q27=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q27=length(Tangent_World_Q27);Tangent_World_N_Q27=Tangent_World_Q27/Tangent_Length_Q27;vec3 Normal_World_Q60;vec3 Normal_World_N_Q60;float Normal_Length_Q60;Object_To_World_Dir_B60(vec3(0,0,1),Normal_World_Q60,Normal_World_N_Q60,Normal_Length_Q60);float X_Q78;float Y_Q78;float Z_Q78;To_XYZ_B78(position,X_Q78,Y_Q78,Z_Q78);vec3 Nrm_World_Q26;Nrm_World_Q26=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q28;vec3 Binormal_World_N_Q28;float Binormal_Length_Q28;Object_To_World_Dir_B28(vec3(0,1,0),Binormal_World_Q28,Binormal_World_N_Q28,Binormal_Length_Q28);float Anisotropy_Q29=Tangent_Length_Q27/Binormal_Length_Q28;float Result_Q69;Pick_Radius_B69(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q69);float Anisotropy_Q53=Binormal_Length_Q28/Normal_Length_Q60;bool Not_Greater_Than_Q37;bool Greater_Than_Q37;Greater_Than_B37(Z_Q78,0.0,Not_Greater_Than_Q37,Greater_Than_Q37);vec4 Linear_Q101;Linear_Q101.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q101.a=_Left_Color_.a;vec4 Linear_Q102;Linear_Q102.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q102.a=_Right_Color_.a;vec3 Difference_Q61=vec3(0,0,0)-Normal_World_N_Q60;vec4 Out_Color_Q34=vec4(X_Q78,Y_Q78,Z_Q78,1);float Result_Q36;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_,_Bevel_Front_,Result_Q36);float Result_Q94;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q94);vec3 New_P_Q130;vec2 New_UV_Q130;float Radial_Gradient_Q130;vec3 Radial_Dir_Q130;vec3 New_Normal_Q130;Move_Verts_B130(Anisotropy_Q29,position,Result_Q69,Result_Q36,normal,Anisotropy_Q53,Result_Q94,New_P_Q130,New_UV_Q130,Radial_Gradient_Q130,Radial_Dir_Q130,New_Normal_Q130);float X_Q98;float Y_Q98;X_Q98=New_UV_Q130.x;Y_Q98=New_UV_Q130.y;vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q130,Pos_World_Q12);vec3 Nrm_World_Q32;Object_To_World_Normal_B32(New_Normal_Q130,Nrm_World_Q32);vec4 Blob_Info_Q23;\n#if BLOB_ENABLE\nBlob_Vertex_B23(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q23);\n#else\nBlob_Info_Q23=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q24;\n#if BLOB_ENABLE_2\nBlob_Vertex_B24(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q24);\n#else\nBlob_Info_Q24=vec4(0,0,0,0);\n#endif\nfloat Out_Q105;Remap_Range_B105(0.0,1.0,0.0,1.0,X_Q98,Out_Q105);float X_Q86;float Y_Q86;float Z_Q86;To_XYZ_B78(Nrm_World_Q32,X_Q86,Y_Q86,Z_Q86);vec4 Color_At_T_Q97=mix(Linear_Q101,Linear_Q102,Out_Q105);float Minus_F_Q87=-Z_Q86;float R_Q99;float G_Q99;float B_Q99;float A_Q99;R_Q99=Color_At_T_Q97.r; G_Q99=Color_At_T_Q97.g; B_Q99=Color_At_T_Q97.b; A_Q99=Color_At_T_Q97.a;float ClampF_Q88=clamp(0.0,Minus_F_Q87,1.0);float Result_Q93;Conditional_Float_B93(_Decal_Front_Only_,ClampF_Q88,1.0,Result_Q93);vec4 Vec4_Q89=vec4(Result_Q93,Radial_Gradient_Q130,G_Q99,B_Q99);vec3 Position=Pos_World_Q12;vec3 Normal=Nrm_World_Q32;vec2 UV=XY_Q85;vec3 Tangent=Tangent_World_N_Q27;vec3 Binormal=Difference_Q61;vec4 Color=Out_Color_Q34;vec4 Extra1=Vec4_Q89;vec4 Extra2=Blob_Info_Q23;vec4 Extra3=Blob_Info_Q24;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class oN extends Oa{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class aN extends Ra{constructor(e,t){super(e,t),this.radius=.6,this.bevelFront=.6,this.bevelFrontStretch=.077,this.bevelBack=0,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=1.102,this.sunTheta=.76,this.sunPhi=.526,this.indirectDiffuse=.658,this.albedo=new Ee(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=0,this.leftGradientColor=new Ee(.0117647,.505882,.996078,1),this.rightGradientColor=new Ee(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.13,this.skyColor=new Ee(.0117647,.964706,.996078,1),this.horizonColor=new Ee(.0117647,.333333,.996078,1),this.groundColor=new Ee(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new de(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new de(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Vo("",this.getScene()),this.leftIndexPosition=new de(0,0,1),this.rightIndexPosition=new de(-1,-1,-1),this.leftIndexMiddlePosition=new de(0,0,0),this.rightIndexMiddlePosition=new de(0,0,0),this.decalScaleXY=new ue(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new _e(.5,0,-.55,1),this.globaRightIndexTipPosition=new _e(0,0,0,1),this.globalLeftThumbTipPosition=new _e(.5,0,-.55,1),this.globalRightThumbTipPosition=new _e(0,0,0,1),this.globalLeftIndexMiddlePosition=new _e(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new _e(0,0,0,1),this.alphaMode=Yd.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Vo(aN.BLUE_GRADIENT_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE),this._decalTexture=new Vo("",this.getScene()),this._reflectionMapTexture=new Vo("",this.getScene()),this._indirectEnvTexture=new Vo("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new oN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlSliderBar",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return yt.Clone((()=>new aN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderBarMaterial",e}getClassName(){return"MRDLSliderBarMaterial"}static Parse(e,t,i){return yt.Parse((()=>new aN(e.name,t)),e,t,i)}}aN.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",qe([st()],aN.prototype,"radius",void 0),qe([st()],aN.prototype,"bevelFront",void 0),qe([st()],aN.prototype,"bevelFrontStretch",void 0),qe([st()],aN.prototype,"bevelBack",void 0),qe([st()],aN.prototype,"bevelBackStretch",void 0),qe([st()],aN.prototype,"radiusTopLeft",void 0),qe([st()],aN.prototype,"radiusTopRight",void 0),qe([st()],aN.prototype,"radiusBottomLeft",void 0),qe([st()],aN.prototype,"radiusBottomRight",void 0),qe([st()],aN.prototype,"bulgeEnabled",void 0),qe([st()],aN.prototype,"bulgeHeight",void 0),qe([st()],aN.prototype,"bulgeRadius",void 0),qe([st()],aN.prototype,"sunIntensity",void 0),qe([st()],aN.prototype,"sunTheta",void 0),qe([st()],aN.prototype,"sunPhi",void 0),qe([st()],aN.prototype,"indirectDiffuse",void 0),qe([st()],aN.prototype,"albedo",void 0),qe([st()],aN.prototype,"specular",void 0),qe([st()],aN.prototype,"shininess",void 0),qe([st()],aN.prototype,"sharpness",void 0),qe([st()],aN.prototype,"subsurface",void 0),qe([st()],aN.prototype,"leftGradientColor",void 0),qe([st()],aN.prototype,"rightGradientColor",void 0),qe([st()],aN.prototype,"reflection",void 0),qe([st()],aN.prototype,"frontReflect",void 0),qe([st()],aN.prototype,"edgeReflect",void 0),qe([st()],aN.prototype,"power",void 0),qe([st()],aN.prototype,"skyColor",void 0),qe([st()],aN.prototype,"horizonColor",void 0),qe([st()],aN.prototype,"groundColor",void 0),qe([st()],aN.prototype,"horizonPower",void 0),qe([st()],aN.prototype,"width",void 0),qe([st()],aN.prototype,"fuzz",void 0),qe([st()],aN.prototype,"minFuzz",void 0),qe([st()],aN.prototype,"clipFade",void 0),qe([st()],aN.prototype,"hueShift",void 0),qe([st()],aN.prototype,"saturationShift",void 0),qe([st()],aN.prototype,"valueShift",void 0),qe([st()],aN.prototype,"blobPosition",void 0),qe([st()],aN.prototype,"blobIntensity",void 0),qe([st()],aN.prototype,"blobNearSize",void 0),qe([st()],aN.prototype,"blobFarSize",void 0),qe([st()],aN.prototype,"blobNearDistance",void 0),qe([st()],aN.prototype,"blobFarDistance",void 0),qe([st()],aN.prototype,"blobFadeLength",void 0),qe([st()],aN.prototype,"blobPulse",void 0),qe([st()],aN.prototype,"blobFade",void 0),qe([st()],aN.prototype,"blobPosition2",void 0),qe([st()],aN.prototype,"blobNearSize2",void 0),qe([st()],aN.prototype,"blobPulse2",void 0),qe([st()],aN.prototype,"blobFade2",void 0),qe([st()],aN.prototype,"blobTexture",void 0),qe([st()],aN.prototype,"leftIndexPosition",void 0),qe([st()],aN.prototype,"rightIndexPosition",void 0),qe([st()],aN.prototype,"leftIndexMiddlePosition",void 0),qe([st()],aN.prototype,"rightIndexMiddlePosition",void 0),qe([st()],aN.prototype,"decalScaleXY",void 0),qe([st()],aN.prototype,"decalFrontOnly",void 0),qe([st()],aN.prototype,"rimIntensity",void 0),qe([st()],aN.prototype,"rimHueShift",void 0),qe([st()],aN.prototype,"rimSaturationShift",void 0),qe([st()],aN.prototype,"rimValueShift",void 0),qe([st()],aN.prototype,"iridescenceIntensity",void 0),ee("BABYLON.GUI.MRDLSliderBarMaterial",aN);bi.ShadersStore.mrdlSliderThumbPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Bevel_Front_;uniform float _Bevel_Front_Stretch_;uniform float _Bevel_Back_;uniform float _Bevel_Back_Stretch_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform bool _Bulge_Enabled_;uniform float _Bulge_Height_;uniform float _Bulge_Radius_;uniform float _Sun_Intensity_;uniform float _Sun_Theta_;uniform float _Sun_Phi_;uniform float _Indirect_Diffuse_;uniform vec4 _Albedo_;uniform float _Specular_;uniform float _Shininess_;uniform float _Sharpness_;uniform float _Subsurface_;uniform vec4 _Left_Color_;uniform vec4 _Right_Color_;uniform float _Reflection_;uniform float _Front_Reflect_;uniform float _Edge_Reflect_;uniform float _Power_;uniform vec4 _Sky_Color_;uniform vec4 _Horizon_Color_;uniform vec4 _Ground_Color_;uniform float _Horizon_Power_;uniform sampler2D _Reflection_Map_;uniform sampler2D _Indirect_Environment_;uniform float _Width_;uniform float _Fuzz_;uniform float _Min_Fuzz_;uniform float _Clip_Fade_;uniform float _Hue_Shift_;uniform float _Saturation_Shift_;uniform float _Value_Shift_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Left_Index_Pos_;uniform vec3 _Right_Index_Pos_;uniform vec3 _Left_Index_Middle_Pos_;uniform vec3 _Right_Index_Middle_Pos_;uniform sampler2D _Decal_;uniform vec2 _Decal_Scale_XY_;uniform bool _Decal_Front_Only_;uniform float _Rim_Intensity_;uniform sampler2D _Rim_Texture_;uniform float _Rim_Hue_Shift_;uniform float _Rim_Saturation_Shift_;uniform float _Rim_Value_Shift_;uniform float _Iridescence_Intensity_;uniform sampler2D _Iridescence_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform vec4 Global_Left_Index_Middle_Position;uniform vec4 Global_Right_Index_Middle_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Blob_Fragment_B180(\nsampler2D Blob_Texture,\nvec4 Blob_Info1,\nvec4 Blob_Info2,\nout vec4 Blob_Color)\n{float k1=dot(Blob_Info1.xy,Blob_Info1.xy);float k2=dot(Blob_Info2.xy,Blob_Info2.xy);vec3 closer=k10.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B200(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid200(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B215(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B224(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B214(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B258(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B264(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B225(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B186(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B187(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B255(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q235;XY_Q235=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q177;vec3 Tangent_World_N_Q177;float Tangent_Length_Q177;Tangent_World_Q177=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q177=length(Tangent_World_Q177);Tangent_World_N_Q177=Tangent_World_Q177/Tangent_Length_Q177;vec3 Normal_World_Q210;vec3 Normal_World_N_Q210;float Normal_Length_Q210;Object_To_World_Dir_B210(vec3(0,0,1),Normal_World_Q210,Normal_World_N_Q210,Normal_Length_Q210);float X_Q228;float Y_Q228;float Z_Q228;To_XYZ_B228(position,X_Q228,Y_Q228,Z_Q228);vec3 Nrm_World_Q176;Nrm_World_Q176=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q178;vec3 Binormal_World_N_Q178;float Binormal_Length_Q178;Object_To_World_Dir_B178(vec3(0,1,0),Binormal_World_Q178,Binormal_World_N_Q178,Binormal_Length_Q178);float Anisotropy_Q179=Tangent_Length_Q177/Binormal_Length_Q178;float Result_Q219;Pick_Radius_B219(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q219);float Anisotropy_Q203=Binormal_Length_Q178/Normal_Length_Q210;bool Not_Greater_Than_Q187;bool Greater_Than_Q187;Greater_Than_B187(Z_Q228,0.0,Not_Greater_Than_Q187,Greater_Than_Q187);vec4 Linear_Q251;Linear_Q251.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q251.a=_Left_Color_.a;vec4 Linear_Q252;Linear_Q252.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q252.a=_Right_Color_.a;vec3 Difference_Q211=vec3(0,0,0)-Normal_World_N_Q210;vec4 Out_Color_Q184=vec4(X_Q228,Y_Q228,Z_Q228,1);float Result_Q186;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_,_Bevel_Front_,Result_Q186);float Result_Q244;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q244);vec3 New_P_Q280;vec2 New_UV_Q280;float Radial_Gradient_Q280;vec3 Radial_Dir_Q280;vec3 New_Normal_Q280;Move_Verts_B280(Anisotropy_Q179,position,Result_Q219,Result_Q186,normal,Anisotropy_Q203,Result_Q244,New_P_Q280,New_UV_Q280,Radial_Gradient_Q280,Radial_Dir_Q280,New_Normal_Q280);float X_Q248;float Y_Q248;X_Q248=New_UV_Q280.x;Y_Q248=New_UV_Q280.y;vec3 Pos_World_Q162;Object_To_World_Pos_B162(New_P_Q280,Pos_World_Q162);vec3 Nrm_World_Q182;Object_To_World_Normal_B182(New_Normal_Q280,Nrm_World_Q182);vec4 Blob_Info_Q173;\n#if BLOB_ENABLE\nBlob_Vertex_B173(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q173);\n#else\nBlob_Info_Q173=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q174;\n#if BLOB_ENABLE_2\nBlob_Vertex_B174(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q174);\n#else\nBlob_Info_Q174=vec4(0,0,0,0);\n#endif\nfloat Out_Q255;Remap_Range_B255(0.0,1.0,0.0,1.0,X_Q248,Out_Q255);float X_Q236;float Y_Q236;float Z_Q236;To_XYZ_B228(Nrm_World_Q182,X_Q236,Y_Q236,Z_Q236);vec4 Color_At_T_Q247=mix(Linear_Q251,Linear_Q252,Out_Q255);float Minus_F_Q237=-Z_Q236;float R_Q249;float G_Q249;float B_Q249;float A_Q249;R_Q249=Color_At_T_Q247.r; G_Q249=Color_At_T_Q247.g; B_Q249=Color_At_T_Q247.b; A_Q249=Color_At_T_Q247.a;float ClampF_Q238=clamp(0.0,Minus_F_Q237,1.0);float Result_Q243;Conditional_Float_B243(_Decal_Front_Only_,ClampF_Q238,1.0,Result_Q243);vec4 Vec4_Q239=vec4(Result_Q243,Radial_Gradient_Q280,G_Q249,B_Q249);vec3 Position=Pos_World_Q162;vec3 Normal=Nrm_World_Q182;vec2 UV=XY_Q235;vec3 Tangent=Tangent_World_N_Q177;vec3 Binormal=Difference_Q211;vec4 Color=Out_Color_Q184;vec4 Extra1=Vec4_Q239;vec4 Extra2=Blob_Info_Q173;vec4 Extra3=Blob_Info_Q174;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class lN extends Oa{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class hN extends Ra{constructor(e,t){super(e,t),this.radius=.157,this.bevelFront=.065,this.bevelFrontStretch=.077,this.bevelBack=.031,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=2,this.sunTheta=.937,this.sunPhi=.555,this.indirectDiffuse=1,this.albedo=new Ee(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=.31,this.leftGradientColor=new Ee(.0117647,.505882,.996078,1),this.rightGradientColor=new Ee(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.1,this.skyColor=new Ee(.0117647,.960784,.996078,1),this.horizonColor=new Ee(.0117647,.333333,.996078,1),this.groundColor=new Ee(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new de(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new de(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Vo("",this.getScene()),this.leftIndexPosition=new de(0,0,1),this.rightIndexPosition=new de(-1,-1,-1),this.leftIndexMiddlePosition=new de(0,0,0),this.rightIndexMiddlePosition=new de(0,0,0),this.decalScaleXY=new ue(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new _e(.5,0,-.55,1),this.globaRightIndexTipPosition=new _e(0,0,0,1),this.globalLeftThumbTipPosition=new _e(.5,0,-.55,1),this.globalRightThumbTipPosition=new _e(0,0,0,1),this.globalLeftIndexMiddlePosition=new _e(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new _e(0,0,0,1),this.alphaMode=Yd.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Vo(hN.BLUE_GRADIENT_TEXTURE_URL,t,!0,!1,Vo.NEAREST_SAMPLINGMODE),this._decalTexture=new Vo("",this.getScene()),this._reflectionMapTexture=new Vo("",this.getScene()),this._indirectEnvTexture=new Vo("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new lN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlSliderThumb",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return yt.Clone((()=>new hN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderThumbMaterial",e}getClassName(){return"MRDLSliderThumbMaterial"}static Parse(e,t,i){return yt.Parse((()=>new hN(e.name,t)),e,t,i)}}hN.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",qe([st()],hN.prototype,"radius",void 0),qe([st()],hN.prototype,"bevelFront",void 0),qe([st()],hN.prototype,"bevelFrontStretch",void 0),qe([st()],hN.prototype,"bevelBack",void 0),qe([st()],hN.prototype,"bevelBackStretch",void 0),qe([st()],hN.prototype,"radiusTopLeft",void 0),qe([st()],hN.prototype,"radiusTopRight",void 0),qe([st()],hN.prototype,"radiusBottomLeft",void 0),qe([st()],hN.prototype,"radiusBottomRight",void 0),qe([st()],hN.prototype,"bulgeEnabled",void 0),qe([st()],hN.prototype,"bulgeHeight",void 0),qe([st()],hN.prototype,"bulgeRadius",void 0),qe([st()],hN.prototype,"sunIntensity",void 0),qe([st()],hN.prototype,"sunTheta",void 0),qe([st()],hN.prototype,"sunPhi",void 0),qe([st()],hN.prototype,"indirectDiffuse",void 0),qe([st()],hN.prototype,"albedo",void 0),qe([st()],hN.prototype,"specular",void 0),qe([st()],hN.prototype,"shininess",void 0),qe([st()],hN.prototype,"sharpness",void 0),qe([st()],hN.prototype,"subsurface",void 0),qe([st()],hN.prototype,"leftGradientColor",void 0),qe([st()],hN.prototype,"rightGradientColor",void 0),qe([st()],hN.prototype,"reflection",void 0),qe([st()],hN.prototype,"frontReflect",void 0),qe([st()],hN.prototype,"edgeReflect",void 0),qe([st()],hN.prototype,"power",void 0),qe([st()],hN.prototype,"skyColor",void 0),qe([st()],hN.prototype,"horizonColor",void 0),qe([st()],hN.prototype,"groundColor",void 0),qe([st()],hN.prototype,"horizonPower",void 0),qe([st()],hN.prototype,"width",void 0),qe([st()],hN.prototype,"fuzz",void 0),qe([st()],hN.prototype,"minFuzz",void 0),qe([st()],hN.prototype,"clipFade",void 0),qe([st()],hN.prototype,"hueShift",void 0),qe([st()],hN.prototype,"saturationShift",void 0),qe([st()],hN.prototype,"valueShift",void 0),qe([st()],hN.prototype,"blobPosition",void 0),qe([st()],hN.prototype,"blobIntensity",void 0),qe([st()],hN.prototype,"blobNearSize",void 0),qe([st()],hN.prototype,"blobFarSize",void 0),qe([st()],hN.prototype,"blobNearDistance",void 0),qe([st()],hN.prototype,"blobFarDistance",void 0),qe([st()],hN.prototype,"blobFadeLength",void 0),qe([st()],hN.prototype,"blobPulse",void 0),qe([st()],hN.prototype,"blobFade",void 0),qe([st()],hN.prototype,"blobPosition2",void 0),qe([st()],hN.prototype,"blobNearSize2",void 0),qe([st()],hN.prototype,"blobPulse2",void 0),qe([st()],hN.prototype,"blobFade2",void 0),qe([st()],hN.prototype,"blobTexture",void 0),qe([st()],hN.prototype,"leftIndexPosition",void 0),qe([st()],hN.prototype,"rightIndexPosition",void 0),qe([st()],hN.prototype,"leftIndexMiddlePosition",void 0),qe([st()],hN.prototype,"rightIndexMiddlePosition",void 0),qe([st()],hN.prototype,"decalScaleXY",void 0),qe([st()],hN.prototype,"decalFrontOnly",void 0),qe([st()],hN.prototype,"rimIntensity",void 0),qe([st()],hN.prototype,"rimHueShift",void 0),qe([st()],hN.prototype,"rimSaturationShift",void 0),qe([st()],hN.prototype,"rimValueShift",void 0),qe([st()],hN.prototype,"iridescenceIntensity",void 0),ee("BABYLON.GUI.MRDLSliderThumbMaterial",hN);bi.ShadersStore.mrdlBackplatePixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;void FastLinearTosRGB_B353(\nvec4 Linear,\nout vec4 sRGB)\n{sRGB.rgb=sqrt(clamp(Linear.rgb,0.0,1.0));sRGB.a=Linear.a;}\nvoid Round_Rect_Fragment_B332(\nfloat Radius,\nfloat Line_Width,\nvec4 Line_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Line_Visibility,\nvec4 Rect_Parms,\nvec4 Fill_Color,\nout vec4 Color)\n{float d=length(max(abs(UV)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);float g=min(Rect_Parms.z,Rect_Parms.w);float dgrad=max(fwidth(g)*Filter_Width,0.00001);float Inside_Rect=clamp(g/dgrad,0.0,1.0);float inner=clamp((d+dx*0.5-max(Radius-Line_Width,d-dx*0.5))/dx,0.0,1.0);Color=clamp(mix(Fill_Color,Line_Color,inner),0.0,1.0)*Inside_Rect;}\nvoid Iridescence_B343(\nvec3 Position,\nvec3 Normal,\nvec2 UV,\nvec3 Axis,\nvec3 Eye,\nvec4 Tint,\nsampler2D Texture,\nbool Reflected,\nfloat Frequency,\nfloat Vertical_Offset,\nout vec4 Color)\n{vec3 i=normalize(Position-Eye);vec3 r=reflect(i,Normal);float idota=dot(i,Axis);float idotr=dot(i,r);float x=Reflected ? idotr : idota;vec2 xy;xy.x=fract((x*Frequency+1.0)*0.5+UV.y*Vertical_Offset);xy.y=0.5;Color=texture(Texture,xy);Color.rgb*=Tint.rgb;}\nvoid Scale_RGB_B346(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Scale_RGB_B344(\nfloat Scalar,\nvec4 Color,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Line_Fragment_B362(\nvec4 Base_Color,\nvec4 Highlight_Color,\nfloat Highlight_Width,\nvec3 Line_Vertex,\nfloat Highlight,\nout vec4 Line_Color)\n{float k2=1.0-clamp(abs(Line_Vertex.y/Highlight_Width),0.0,1.0);Line_Color=mix(Base_Color,Highlight_Color,Highlight*k2);}\nvoid Edge_B356(\nvec4 RectParms,\nfloat Radius,\nfloat Line_Width,\nvec2 UV,\nfloat Edge_Width,\nfloat Edge_Power,\nout float Result)\n{float d=length(max(abs(UV)-RectParms.xy,0.0));float edge=1.0-clamp((1.0-d/(Radius-Line_Width))/Edge_Width,0.0,1.0);Result=pow(edge,Edge_Power);}\nvoid Gradient_B355(\nvec4 Gradient_Color,\nvec4 Top_Left,\nvec4 Top_Right,\nvec4 Bottom_Left,\nvec4 Bottom_Right,\nvec2 UV,\nout vec4 Result)\n{vec3 top=Top_Left.rgb+(Top_Right.rgb-Top_Left.rgb)*UV.x;vec3 bottom=Bottom_Left.rgb+(Bottom_Right.rgb-Bottom_Left.rgb)*UV.x;Result.rgb=Gradient_Color.rgb*(bottom+(top-bottom)*UV.y);Result.a=1.0;}\nvoid main()\n{float X_Q338;float Y_Q338;float Z_Q338;float W_Q338;X_Q338=vExtra2.x;Y_Q338=vExtra2.y;Z_Q338=vExtra2.z;W_Q338=vExtra2.w;vec4 Color_Q343;\n#if IRIDESCENCE_ENABLE\nIridescence_B343(vPosition,vNormal,vUV,vBinormal,cameraPosition,_Iridescence_Tint_,_Iridescent_Map_,_Reflected_,_Frequency_,_Vertical_Offset_,Color_Q343);\n#else\nColor_Q343=vec4(0,0,0,0);\n#endif\nvec4 Result_Q344;Scale_RGB_B344(_Iridescence_Intensity_,Color_Q343,Result_Q344);vec4 Line_Color_Q362;Line_Fragment_B362(_Line_Color_,_Highlight_Color_,_Highlight_Width_,vTangent,_Highlight_,Line_Color_Q362);float Result_Q356;\n#if EDGE_ONLY\nEdge_B356(vExtra1,Z_Q338,W_Q338,vUV,_Edge_Width_,_Edge_Power_,Result_Q356);\n#else\nResult_Q356=1.0;\n#endif\nvec2 Vec2_Q339=vec2(X_Q338,Y_Q338);vec4 Result_Q355;Gradient_B355(_Gradient_Color_,_Top_Left_,_Top_Right_,_Bottom_Left_,_Bottom_Right_,Vec2_Q339,Result_Q355);vec4 Linear_Q348;Linear_Q348.rgb=clamp(Result_Q355.rgb*Result_Q355.rgb,0.0,1.0);Linear_Q348.a=Result_Q355.a;vec4 Result_Q346;Scale_RGB_B346(Linear_Q348,Result_Q356,Result_Q346);vec4 Sum_Q345=Result_Q346+Result_Q344;vec4 Color_At_T_Q347=mix(Line_Color_Q362,Result_Q346,_Line_Gradient_Blend_);vec4 Base_And_Iridescent_Q350;Base_And_Iridescent_Q350=_Base_Color_+vec4(Sum_Q345.rgb,0.0);vec4 Sum_Q349=Color_At_T_Q347+_Iridescence_Edge_Intensity_*Color_Q343;vec4 Result_Q351=Sum_Q349; Result_Q351.a=1.0;vec4 Color_Q332;Round_Rect_Fragment_B332(Z_Q338,W_Q338,Result_Q351,_Filter_Width_,vUV,1.0,vExtra1,Base_And_Iridescent_Q350,Color_Q332);vec4 Result_Q354=_Fade_Out_*Color_Q332;vec4 sRGB_Q353;FastLinearTosRGB_B353(Result_Q354,sRGB_Q353);vec4 Out_Color=sRGB_Q353;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";bi.ShadersStore.mrdlBackplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec3 tangent;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;void Object_To_World_Pos_B314(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Round_Rect_Vertex_B357(\nvec2 UV,\nfloat Radius,\nfloat Margin,\nfloat Anisotropy,\nfloat Gradient1,\nfloat Gradient2,\nvec3 Normal,\nvec4 Color_Scale_Translate,\nout vec2 Rect_UV,\nout vec4 Rect_Parms,\nout vec2 Scale_XY,\nout vec2 Line_UV,\nout vec2 Color_UV_Info)\n{Scale_XY=vec2(Anisotropy,1.0);Line_UV=(UV-vec2(0.5,0.5));Rect_UV=Line_UV*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius)-vec2(Margin,Margin);Rect_Parms.z=Gradient1; \nRect_Parms.w=Gradient2;Color_UV_Info=(Line_UV+vec2(0.5,0.5))*Color_Scale_Translate.xy+Color_Scale_Translate.zw;}\nvoid Line_Vertex_B333(\nvec2 Scale_XY,\nvec2 UV,\nfloat Time,\nfloat Rate,\nvec4 Highlight_Transform,\nout vec3 Line_Vertex)\n{float angle2=(Rate*Time)*2.0*3.1416;float sinAngle2=sin(angle2);float cosAngle2=cos(angle2);vec2 xformUV=UV*Highlight_Transform.xy+Highlight_Transform.zw;Line_Vertex.x=0.0;Line_Vertex.y=cosAngle2*xformUV.x-sinAngle2*xformUV.y;Line_Vertex.z=0.0; }\nvoid PickDir_B334(\nfloat Degrees,\nvec3 DirX,\nvec3 DirY,\nout vec3 Dir)\n{float a=Degrees*3.14159/180.0;Dir=cos(a)*DirX+sin(a)*DirY;}\nvoid Move_Verts_B327(\nfloat Anisotropy,\nvec3 P,\nfloat Radius,\nout vec3 New_P,\nout vec2 New_UV,\nout float Radial_Gradient,\nout vec3 Radial_Dir)\n{vec2 UV=P.xy*2.0+0.5;vec2 center=clamp(UV,0.0,1.0);vec2 delta=UV-center;vec2 r2=2.0*vec2(Radius/Anisotropy,Radius);New_UV=center+r2*(UV-2.0*center+0.5);New_P=vec3(New_UV-0.5,P.z);Radial_Gradient=1.0-length(delta)*2.0;Radial_Dir=vec3(delta*r2,0.0);}\nvoid Pick_Radius_B336(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Edge_AA_Vertex_B328(\nvec3 Position_World,\nvec3 Position_Object,\nvec3 Normal_Object,\nvec3 Eye,\nfloat Radial_Gradient,\nvec3 Radial_Dir,\nvec3 Tangent,\nout float Gradient1,\nout float Gradient2)\n{vec3 I=(Eye-Position_World);vec3 T=(vec4(Tangent,0.0)).xyz;float g=(dot(T,I)<0.0) ? 0.0 : 1.0;if (Normal_Object.z==0.0) { \nGradient1=Position_Object.z>0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Object_To_World_Dir_B330(\nvec3 Dir_Object,\nout vec3 Binormal_World,\nout vec3 Binormal_World_N,\nout float Binormal_Length)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;Binormal_Length=length(Binormal_World);Binormal_World_N=Binormal_World/Binormal_Length;}\nvoid RelativeOrAbsoluteDetail_B341(\nfloat Nominal_Radius,\nfloat Nominal_LineWidth,\nbool Absolute_Measurements,\nfloat Height,\nout float Radius,\nout float Line_Width)\n{float scale=Absolute_Measurements ? 1.0/Height : 1.0;Radius=Nominal_Radius*scale;Line_Width=Nominal_LineWidth*scale;}\nvoid main()\n{vec3 Nrm_World_Q326;Nrm_World_Q326=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q329;vec3 Tangent_World_N_Q329;float Tangent_Length_Q329;Tangent_World_Q329=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q329=length(Tangent_World_Q329);Tangent_World_N_Q329=Tangent_World_Q329/Tangent_Length_Q329;vec3 Binormal_World_Q330;vec3 Binormal_World_N_Q330;float Binormal_Length_Q330;Object_To_World_Dir_B330(vec3(0,1,0),Binormal_World_Q330,Binormal_World_N_Q330,Binormal_Length_Q330);float Radius_Q341;float Line_Width_Q341;RelativeOrAbsoluteDetail_B341(_Radius_,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q330,Radius_Q341,Line_Width_Q341);vec3 Dir_Q334;PickDir_B334(_Angle_,Tangent_World_N_Q329,Binormal_World_N_Q330,Dir_Q334);float Result_Q336;Pick_Radius_B336(Radius_Q341,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q336);float Anisotropy_Q331=Tangent_Length_Q329/Binormal_Length_Q330;vec4 Out_Color_Q337=vec4(Result_Q336,Line_Width_Q341,0,1);vec3 New_P_Q327;vec2 New_UV_Q327;float Radial_Gradient_Q327;vec3 Radial_Dir_Q327;Move_Verts_B327(Anisotropy_Q331,position,Result_Q336,New_P_Q327,New_UV_Q327,Radial_Gradient_Q327,Radial_Dir_Q327);vec3 Pos_World_Q314;Object_To_World_Pos_B314(New_P_Q327,Pos_World_Q314);float Gradient1_Q328;float Gradient2_Q328;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B328(Pos_World_Q314,position,normal,cameraPosition,Radial_Gradient_Q327,Radial_Dir_Q327,tangent,Gradient1_Q328,Gradient2_Q328);\n#else\nGradient1_Q328=1.0;Gradient2_Q328=1.0;\n#endif\nvec2 Rect_UV_Q357;vec4 Rect_Parms_Q357;vec2 Scale_XY_Q357;vec2 Line_UV_Q357;vec2 Color_UV_Info_Q357;Round_Rect_Vertex_B357(New_UV_Q327,Result_Q336,0.0,Anisotropy_Q331,Gradient1_Q328,Gradient2_Q328,normal,vec4(1,1,0,0),Rect_UV_Q357,Rect_Parms_Q357,Scale_XY_Q357,Line_UV_Q357,Color_UV_Info_Q357);vec3 Line_Vertex_Q333;Line_Vertex_B333(Scale_XY_Q357,Line_UV_Q357,(20.0),_Rate_,_Highlight_Transform_,Line_Vertex_Q333);float X_Q359;float Y_Q359;X_Q359=Color_UV_Info_Q357.x;Y_Q359=Color_UV_Info_Q357.y;vec4 Vec4_Q358=vec4(X_Q359,Y_Q359,Result_Q336,Line_Width_Q341);vec3 Position=Pos_World_Q314;vec3 Normal=Nrm_World_Q326;vec2 UV=Rect_UV_Q357;vec3 Tangent=Line_Vertex_Q333;vec3 Binormal=Dir_Q334;vec4 Color=Out_Color_Q337;vec4 Extra1=Rect_Parms_Q357;vec4 Extra2=Vec4_Q358;vec4 Extra3=vec4(0,0,0,0);gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vExtra1=Extra1;vExtra2=Extra2;}";class cN extends Oa{constructor(){super(),this.IRIDESCENCE_ENABLE=!0,this.SMOOTH_EDGES=!0,this._needNormals=!0,this.rebuild()}}class uN extends Ra{constructor(e,t){super(e,t),this.radius=.3,this.lineWidth=.003,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Ee(0,0,0,1),this.lineColor=new Ee(.2,.262745,.4,1),this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this._rate=0,this.highlightColor=new Ee(.239216,.435294,.827451,1),this.highlightWidth=0,this._highlightTransform=new _e(1,1,0,0),this._highlight=1,this.iridescenceIntensity=.45,this.iridescenceEdgeIntensity=1,this.iridescenceTint=new Ee(1,1,1,1),this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.gradientColor=new Ee(.74902,.74902,.74902,1),this.topLeftGradientColor=new Ee(.00784314,.294118,.580392,1),this.topRightGradientColor=new Ee(.305882,0,1,1),this.bottomLeftGradientColor=new Ee(.133333,.258824,.992157,1),this.bottomRightGradientColor=new Ee(.176471,.176471,.619608,1),this.edgeWidth=.5,this.edgePower=1,this.edgeLineGradientBlend=.5,this.alphaMode=Yd.ALPHA_DISABLE,this.backFaceCulling=!1,this._iridescentMapTexture=new Vo(uN.IRIDESCENT_MAP_TEXTURE_URL,this.getScene(),!0,!1,Vo.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new cN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlBackplate",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Iridescence_Tint_","_Iridescent_Map_","_Angle_","_Reflected_","_Frequency_","_Vertical_Offset_","_Gradient_Color_","_Top_Left_","_Top_Right_","_Bottom_Left_","_Bottom_Right_","_Edge_Width_","_Edge_Power_","_Line_Gradient_Blend_","_Fade_Out_"],h=["_Iridescent_Map_"],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setDirectColor4("_Iridescence_Tint_",this.iridescenceTint),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMapTexture),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setDirectColor4("_Gradient_Color_",this.gradientColor),this._activeEffect.setDirectColor4("_Top_Left_",this.topLeftGradientColor),this._activeEffect.setDirectColor4("_Top_Right_",this.topRightGradientColor),this._activeEffect.setDirectColor4("_Bottom_Left_",this.bottomLeftGradientColor),this._activeEffect.setDirectColor4("_Bottom_Right_",this.bottomRightGradientColor),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setFloat("_Edge_Power_",this.edgePower),this._activeEffect.setFloat("_Line_Gradient_Blend_",this.edgeLineGradientBlend),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new uN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLBackplateMaterial",e}getClassName(){return"MRDLBackplateMaterial"}static Parse(e,t,i){return yt.Parse((()=>new uN(e.name,t)),e,t,i)}}uN.IRIDESCENT_MAP_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-backplate-iridescence.png",qe([st()],uN.prototype,"radius",void 0),qe([st()],uN.prototype,"lineWidth",void 0),qe([st()],uN.prototype,"absoluteSizes",void 0),qe([st()],uN.prototype,"baseColor",void 0),qe([st()],uN.prototype,"lineColor",void 0),qe([st()],uN.prototype,"radiusTopLeft",void 0),qe([st()],uN.prototype,"radiusTopRight",void 0),qe([st()],uN.prototype,"radiusBottomLeft",void 0),qe([st()],uN.prototype,"radiusBottomRight",void 0),qe([st()],uN.prototype,"highlightColor",void 0),qe([st()],uN.prototype,"highlightWidth",void 0),qe([st()],uN.prototype,"iridescenceIntensity",void 0),qe([st()],uN.prototype,"iridescenceEdgeIntensity",void 0),qe([st()],uN.prototype,"iridescenceTint",void 0),qe([st()],uN.prototype,"fadeOut",void 0),qe([st()],uN.prototype,"gradientColor",void 0),qe([st()],uN.prototype,"topLeftGradientColor",void 0),qe([st()],uN.prototype,"topRightGradientColor",void 0),qe([st()],uN.prototype,"bottomLeftGradientColor",void 0),qe([st()],uN.prototype,"bottomRightGradientColor",void 0),qe([st()],uN.prototype,"edgeWidth",void 0),qe([st()],uN.prototype,"edgePower",void 0),qe([st()],uN.prototype,"edgeLineGradientBlend",void 0),ee("BABYLON.GUI.MRDLBackplateMaterial",uN);class dN extends Iw{constructor(e,t){super(e),this.onValueChangedObservable=new X,this._sliderBackplateVisible=t||!1,this._minimum=0,this._maximum=100,this._step=0,this._value=50}get mesh(){return this.node?this._sliderThumb:null}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=Math.max(e,0),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=Math.max(e,this._minimum),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get step(){return this._step}set step(e){this._step!==e&&(this._step=Math.max(Math.min(e,this._maximum-this._minimum),0))}get value(){return this._value}set value(e){this._value!==e&&(this._value=Math.max(Math.min(e,this._maximum),this._minimum),this._sliderThumb&&(this._sliderThumb.position.x=this._convertToPosition(this.value)),this.onValueChangedObservable.notifyObservers(this._value))}get start(){return this.node?this._sliderBar.position.x-this._sliderBar.scaling.x/2:-.5}get end(){return this.node?this._sliderBar.position.x+this._sliderBar.scaling.x/2:.5}get sliderBarMaterial(){return this._sliderBarMaterial}get sliderThumbMaterial(){return this._sliderThumbMaterial}get sliderBackplateMaterial(){return this._sliderBackplateMaterial}get sliderBar(){return this._sliderBar}get sliderThumb(){return this._sliderThumb}get sliderBackplate(){return this._sliderBackplate}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this.node?.setEnabled(e))}_createNode(e){const t=yu(`${this.name}_sliderbackplate`,{width:1,height:1,depth:1},e);return t.isPickable=!1,t.visibility=0,t.scaling=new de(1,.5,.8),Pa.ImportMeshAsync(void 0,dN.MODEL_BASE_URL,dN.MODEL_FILENAME,e).then((e=>{e.meshes.forEach((e=>{e.isPickable=!1}));const i=e.meshes[1],s=e.meshes[1].clone(`${this.name}_sliderbar`,t),r=e.meshes[1].clone(`${this.name}_sliderthumb`,t);i.visibility=0,this._sliderBackplateVisible&&(i.visibility=1,i.name=`${this.name}_sliderbackplate`,i.scaling.x=1,i.scaling.z=.2,i.parent=t,this._sliderBackplateMaterial&&(i.material=this._sliderBackplateMaterial),this._sliderBackplate=i),s&&(s.parent=t,s.position.z=-.1,s.scaling=new de(.8,.04,.3),this._sliderBarMaterial&&(s.material=this._sliderBarMaterial),this._sliderBar=s),r&&(r.parent=t,r.isPickable=!0,r.position.z=-.115,r.scaling=new de(.025,.3,.6),r.position.x=this._convertToPosition(this.value),r.addBehavior(this._createBehavior()),this._sliderThumbMaterial&&(r.material=this._sliderThumbMaterial),this._sliderThumb=r),this._injectGUI3DReservedDataStore(t).control=this,t.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this}))})),this._affectMaterial(t),t}_affectMaterial(e){this._sliderBackplateMaterial=this._sliderBackplateMaterial??new uN(`${this.name}_sliderbackplate_material`,e.getScene()),this._sliderBarMaterial=this._sliderBarMaterial??new aN(`${this.name}_sliderbar_material`,e.getScene()),this._sliderThumbMaterial=this._sliderThumbMaterial??new hN(`${this.name}_sliderthumb_material`,e.getScene())}_createBehavior(){const e=new sa({dragAxis:de.Right()});return e.moveAttached=!1,e.onDragStartObservable.add((()=>{this._draggedPosition=this._sliderThumb.position.x})),e.onDragObservable.add((e=>{this._draggedPosition+=e.dragDistance/this.scaling.x,this.value=this._convertToValue(this._draggedPosition)})),e}_convertToPosition(e){const t=(e-this.minimum)/(this.maximum-this.minimum)*(this.end-this.start)+this.start;return Math.min(Math.max(t,this.start),this.end)}_convertToValue(e){let t=(e-this.start)/(this.end-this.start)*(this.maximum-this.minimum);return t=this.step?Math.round(t/this.step)*this.step:t,Math.max(Math.min(this.minimum+t,this._maximum),this._minimum)}dispose(){super.dispose(),this._sliderBar?.dispose(),this._sliderThumb?.dispose(),this._sliderBarMaterial?.dispose(),this._sliderThumbMaterial?.dispose(),this._sliderBackplate?.dispose(),this._sliderBackplateMaterial?.dispose()}}dN.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",dN.MODEL_FILENAME="mrtk-fluent-backplate.glb";class _N extends Nw{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._sphericalMapping(t);switch(e.position=s,this.orientation){case ww.FACEORIGIN_ORIENTATION:i.lookAt(new de(2*s.x,2*s.y,2*s.z));break;case ww.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new de(-s.x,-s.y,-s.z));break;case ww.FACEFORWARD_ORIENTATION:break;case ww.FACEFORWARDREVERSED_ORIENTATION:i.rotate(_r.Y,Math.PI,lr.LOCAL)}}_sphericalMapping(e){const t=new de(0,0,this._radius),i=e.y/this._radius,s=-e.x/this._radius;return fe.RotationYawPitchRollToRef(s,i,0,ge.Matrix[0]),de.TransformNormal(t,ge.Matrix[0])}}class pN extends ww{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,hs.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e=!1){super(),this._isVertical=!1,this.margin=.1,this._isVertical=e}_arrangeChildren(){let e=0,t=0,i=0;const s=[],r=fe.Invert(this.node.computeWorldMatrix(!0));for(const n of this._children){if(!n.mesh)continue;i++,n.mesh.computeWorldMatrix(!0),n.mesh.getWorldMatrix().multiplyToRef(r,ge.Matrix[0]);const o=n.mesh.getBoundingInfo().boundingBox,a=de.TransformNormal(o.extendSize,ge.Matrix[0]);s.push(a),this._isVertical?t+=a.y:e+=a.x}let n;this._isVertical?t+=(i-1)*this.margin/2:e+=(i-1)*this.margin/2,n=this._isVertical?-t:-e;let o=0;for(const e of this._children){if(!e.mesh)continue;i--;const t=s[o++];this._isVertical?(e.position.y=n+t.y,e.position.x=0,n+=2*t.y):(e.position.x=n+t.x,e.position.y=0,n+=2*t.x),n+=i>0?this.margin:0}}}class fN extends Yw{constructor(e,t){super(t,e),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"TouchMeshButton3D"}_createNode(){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}bi.ShadersStore.mrdlBackglowPixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;float BiasFunc(float b,float v) {return pow(v,log(clamp(b,0.001,0.999))/log(0.5));}\nvoid Fuzzy_Round_Rect_B33(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius_X,\nfloat Radius_Y,\nfloat Line_Width,\nvec2 UV,\nfloat Outer_Fuzz,\nfloat Max_Outer_Fuzz,\nout float Rect_Distance,\nout float Inner_Distance)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius_X,Radius_Y),halfSize),vec2(0.001,0.001));float radius=min(r.x,r.y)-Max_Outer_Fuzz;vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);float d=distance(nearestp,v);Inner_Distance=clamp(1.0-(radius-d)/Line_Width,0.0,1.0);Rect_Distance=clamp(1.0-(d-radius)/Outer_Fuzz,0.0,1.0)*Inner_Distance;}\nvoid main()\n{float X_Q42;float Y_Q42;X_Q42=vNormal.x;Y_Q42=vNormal.y;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Sqrt_F_Q27=sqrt(MaxAB_Q24);float Power_Q43=pow(MaxAB_Q24,_Intensity_Fade_In_Exponent_);float Value_At_T_Q26=mix(_Outer_Fuzz_Start_,_Outer_Fuzz_End_,Sqrt_F_Q27);float Product_Q23=_Max_Intensity_*Power_Q43;float Rect_Distance_Q33;float Inner_Distance_Q33;Fuzzy_Round_Rect_B33(X_Q42,Y_Q42,_Bevel_Radius_,_Bevel_Radius_,_Line_Width_,vUV,Value_At_T_Q26,_Outer_Fuzz_Start_,Rect_Distance_Q33,Inner_Distance_Q33);float Power_Q44=pow(Inner_Distance_Q33,_Blend_Exponent_);float Result_Q45=pow(BiasFunc(_Bias_,Rect_Distance_Q33),_Falloff_);vec4 Color_At_T_Q25=mix(_Inner_Color_,_Color_,Power_Q44);float Product_Q22=Result_Q45*Product_Q23;vec4 Result_Q28=Product_Q22*Color_At_T_Q25;vec4 Out_Color=Result_Q28;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}";bi.ShadersStore.mrdlBackglowVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;varying vec3 vNormal;varying vec2 vUV;void main()\n{vec3 Dir_World_Q41=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q40=(world*vec4((cross(normal,tangent)),0.0)).xyz;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Length_Q16=length(Dir_World_Q41);float Length_Q17=length(Dir_World_Q40);bool Greater_Than_Q37=MaxAB_Q24>0.0;vec3 Sizes_Q35;vec2 XY_Q35;Sizes_Q35=(_Absolute_Sizes_ ? vec3(Length_Q16,Length_Q17,0) : vec3(Length_Q16/Length_Q17,1,0));XY_Q35=(uv-vec2(0.5,0.5))*Sizes_Q35.xy;vec3 Result_Q38=Greater_Than_Q37 ? position : vec3(0,0,0);vec3 Pos_World_Q39=(world*vec4(Result_Q38,1.0)).xyz;vec3 Position=Pos_World_Q39;vec3 Normal=Sizes_Q35;vec2 UV=XY_Q35;vec3 Tangent=vec3(0,0,0);vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;}";class mN extends Oa{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class gN extends Ra{constructor(e,t){super(e,t),this.bevelRadius=.16,this.lineWidth=.16,this.absoluteSizes=!1,this.tuningMotion=0,this.motion=1,this.maxIntensity=.7,this.intensityFadeInExponent=2,this.outerFuzzStart=.04,this.outerFuzzEnd=.04,this.color=new Ee(.682353,.698039,1,1),this.innerColor=new Ee(.356863,.392157,.796078,1),this.blendExponent=1.5,this.falloff=2,this.bias=.5,this.alphaMode=Yd.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new mN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlBackglow",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Bevel_Radius_","_Line_Width_","_Absolute_Sizes_","_Tuning_Motion_","_Motion_","_Max_Intensity_","_Intensity_Fade_In_Exponent_","_Outer_Fuzz_Start_","_Outer_Fuzz_End_","_Color_","_Inner_Color_","_Blend_Exponent_","_Falloff_","_Bias_"],h=[],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Bevel_Radius_",this.bevelRadius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Tuning_Motion_",this.tuningMotion),this._activeEffect.setFloat("_Motion_",this.motion),this._activeEffect.setFloat("_Max_Intensity_",this.maxIntensity),this._activeEffect.setFloat("_Intensity_Fade_In_Exponent_",this.intensityFadeInExponent),this._activeEffect.setFloat("_Outer_Fuzz_Start_",this.outerFuzzStart),this._activeEffect.setFloat("_Outer_Fuzz_End_",this.outerFuzzEnd),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setDirectColor4("_Inner_Color_",this.innerColor),this._activeEffect.setFloat("_Blend_Exponent_",this.blendExponent),this._activeEffect.setFloat("_Falloff_",this.falloff),this._activeEffect.setFloat("_Bias_",this.bias),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new gN(e,this.getScene())),this)}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.MRDLBackglowMaterial",e}getClassName(){return"MRDLBackglowMaterial"}static Parse(e,t,i){return yt.Parse((()=>new gN(e.name,t)),e,t,i)}}qe([st()],gN.prototype,"bevelRadius",void 0),qe([st()],gN.prototype,"lineWidth",void 0),qe([st()],gN.prototype,"absoluteSizes",void 0),qe([st()],gN.prototype,"tuningMotion",void 0),qe([st()],gN.prototype,"motion",void 0),qe([st()],gN.prototype,"maxIntensity",void 0),qe([st()],gN.prototype,"intensityFadeInExponent",void 0),qe([st()],gN.prototype,"outerFuzzStart",void 0),qe([st()],gN.prototype,"outerFuzzEnd",void 0),qe([st()],gN.prototype,"color",void 0),qe([st()],gN.prototype,"innerColor",void 0),qe([st()],gN.prototype,"blendExponent",void 0),qe([st()],gN.prototype,"falloff",void 0),qe([st()],gN.prototype,"bias",void 0),ee("BABYLON.GUI.MRDLBackglowMaterial",gN);bi.ShadersStore.mrdlFrontplatePixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;void Scale_Color_B54(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=Scalar*Color;}\nvoid Scale_RGB_B50(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Proximity_Fragment_B51(\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec4 Deltas,\nfloat Show_Selection,\nfloat Distance_Fade1,\nfloat Distance_Fade2,\nfloat Strength,\nout float Proximity)\n{float proximity1=(1.0-clamp(length(Deltas.xy)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade1;float proximity2=(1.0-clamp(length(Deltas.zw)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade2;Proximity=Strength*(Proximity_Max_Intensity*max(proximity1,proximity2) *(1.0-Show_Selection)+Show_Selection);}\nvoid Blob_Fragment_B56(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvoid Round_Rect_Fragment_B61(\nfloat Radius,\nvec4 Line_Color,\nfloat Filter_Width,\nfloat Line_Visibility,\nvec4 Fill_Color,\nbool Smooth_Edges,\nvec4 Rect_Parms,\nout float Inside_Rect)\n{float d=length(max(abs(Rect_Parms.zw)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);Inside_Rect=Smooth_Edges ? clamp((Radius-d)/dx,0.0,1.0) : 1.0-step(Radius,d);}\nvoid main()\n{float Is_Quad_Q53;Is_Quad_Q53=vNormal.z;vec4 Blob_Color_Q56;Blob_Fragment_B56(vUV,vTangent,_Blob_Texture_,Blob_Color_Q56);float X_Q52;float Y_Q52;float Z_Q52;float W_Q52;X_Q52=vExtra3.x;Y_Q52=vExtra3.y;Z_Q52=vExtra3.z;W_Q52=vExtra3.w;float Proximity_Q51;Proximity_Fragment_B51(_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vExtra2,X_Q52,Y_Q52,Z_Q52,1.0,Proximity_Q51);float Inside_Rect_Q61;Round_Rect_Fragment_B61(W_Q52,vec4(1,1,1,1),_Filter_Width_,1.0,vec4(0,0,0,0),_Smooth_Edges_,vExtra1,Inside_Rect_Q61);vec4 Result_Q50;Scale_RGB_B50(_Edge_Color_,Proximity_Q51,Result_Q50);vec4 Result_Q47=Inside_Rect_Q61*Blob_Color_Q56;vec4 Color_At_T_Q48=mix(Result_Q50,Result_Q47,Is_Quad_Q53);vec4 Result_Q54;Scale_Color_B54(Color_At_T_Q48,_Fade_Out_,Result_Q54);vec4 Out_Color=Result_Q54;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";bi.ShadersStore.mrdlFrontplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;void Blob_Vertex_B40(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nfloat DistanceOffset,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info,\nout vec2 Blob_Relative_UV)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal)+DistanceOffset*Blob_Far_Distance;Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);Blob_Relative_UV=blobClipped/Face_Size.y;}\nvoid Round_Rect_Vertex_B36(\nvec2 UV,\nvec3 Tangent,\nvec3 Binormal,\nfloat Radius,\nfloat Anisotropy,\nvec2 Blob_Center_UV,\nout vec2 Rect_UV,\nout vec2 Scale_XY,\nout vec4 Rect_Parms)\n{Scale_XY=vec2(Anisotropy,1.0);Rect_UV=(UV-vec2(0.5,0.5))*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius);Rect_Parms.zw=Blob_Center_UV;}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B33(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Normal,\nvec3 Tangent,\nvec3 Binormal,\nout vec4 Extra,\nout float Distance_To_Face,\nout float Distance_Fade1,\nout float Distance_Fade2)\n{float distz1,distz2;Extra.xy=ProjectProximity(Blob_Position,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz1)/Relative_Scale;Extra.zw=ProjectProximity(Blob_Position_2,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz2)/Relative_Scale;Distance_To_Face=dot(Normal,Position-Face_Center);Distance_Fade1=1.0-clamp(distz1/Proximity_Far_Distance,0.0,1.0);Distance_Fade2=1.0-clamp(distz2/Proximity_Far_Distance,0.0,1.0);}\nvoid Object_To_World_Pos_B12(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B27(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=Blob_Enable_1 ? 1.0 : 0.0;float b2=Blob_Enable_2 ? 1.0 : 0.0;Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Move_Verts_B32(\nvec2 UV,\nfloat Radius,\nfloat Anisotropy,\nfloat Line_Width,\nfloat Visible,\nout vec3 New_P,\nout vec2 New_UV)\n{vec2 xy=2.0*UV-vec2(0.5,0.5);vec2 center=clamp(xy,0.0,1.0);vec2 delta=2.0*(xy-center);float deltaLength=length(delta);vec2 aniso=vec2(1.0/Anisotropy,1.0);center=(center-vec2(0.5,0.5))*(1.0-2.0*Radius*aniso);New_UV=vec2((2.0-2.0*deltaLength)*Visible,0.0);float deltaRadius= (Radius-Line_Width*New_UV.x);New_P.xy=(center+deltaRadius/deltaLength *aniso*delta);New_P.z=0.0;}\nvoid Object_To_World_Dir_B14(\nvec3 Dir_Object,\nout vec3 Binormal_World)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid Proximity_Visibility_B55(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Face_Center,\nvec3 Normal,\nvec2 Face_Size,\nfloat Gaze,\nout float Width)\n{float boxMaxSize=length(Face_Size)*0.5;float d1=dot(Proximity_Center-Face_Center,Normal);vec3 blob1=Proximity_Center-d1*Normal;float d2=dot(Proximity_Center_2-Face_Center,Normal);vec3 blob2=Proximity_Center_2-d2*Normal;vec3 delta1=blob1-Face_Center;vec3 delta2=blob2-Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));Width=max(Gaze,Width);}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B31(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);Show_Selection=mix(max(select1,select2),1.0,Selected);}\nvoid main()\n{vec3 Vec3_Q29=vec3(vec2(0,0).x,vec2(0,0).y,color.r);vec3 Nrm_World_Q24;Nrm_World_Q24=normalize((world*vec4(normal,0.0)).xyz);vec3 Face_Center_Q30;Face_Center_Q30=(world*vec4(vec3(0,0,0),1.0)).xyz;vec3 Tangent_World_Q13;Tangent_World_Q13=(world*vec4(tangent,0.0)).xyz;vec3 Result_Q42;Result_Q42=_Use_Global_Left_Index_ ? Global_Left_Index_Tip_Position.xyz : _Blob_Position_;vec3 Result_Q43;Result_Q43=_Use_Global_Right_Index_ ? Global_Right_Index_Tip_Position.xyz : _Blob_Position_2_;float Value_At_T_Q58=mix(_Blob_Near_Size_,_Blob_Pulse_Max_Size_,_Blob_Pulse_);float Value_At_T_Q59=mix(_Blob_Near_Size_2_,_Blob_Pulse_Max_Size_,_Blob_Pulse_2_);vec3 Cross_Q70=cross(normal,tangent);float Product_Q45=_Gaze_Intensity_*_Gaze_Focus_;float Step_Q46=step(0.0001,Product_Q45);vec3 Tangent_World_N_Q15=normalize(Tangent_World_Q13);vec3 Position_Q27;float Near_Size_Q27;float Inner_Fade_Q27;float Blob_Enable_Q27;float Fade_Q27;float Pulse_Q27;Choose_Blob_B27(color,Result_Q42,Result_Q43,_Blob_Enable_,_Blob_Enable_2_,Value_At_T_Q58,Value_At_T_Q59,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q27,Near_Size_Q27,Inner_Fade_Q27,Blob_Enable_Q27,Fade_Q27,Pulse_Q27);vec3 Binormal_World_Q14;Object_To_World_Dir_B14(Cross_Q70,Binormal_World_Q14);float Anisotropy_Q21=length(Tangent_World_Q13)/length(Binormal_World_Q14);vec3 Binormal_World_N_Q16=normalize(Binormal_World_Q14);vec2 Face_Size_Q35;float ScaleY_Q35;Face_Size_Q35=vec2(length(Tangent_World_Q13),length(Binormal_World_Q14));ScaleY_Q35=Face_Size_Q35.y;float Out_Radius_Q38;float Out_Line_Width_Q38;Out_Radius_Q38=_Relative_To_Height_ ? _Radius_ : _Radius_/ScaleY_Q35;Out_Line_Width_Q38=_Relative_To_Height_ ? _Line_Width_ : _Line_Width_/ScaleY_Q35;float Show_Selection_Q31;Selection_Vertex_B31(Result_Q42,Result_Q43,Face_Center_Q30,Face_Size_Q35,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,vec3(0,0,-1),Show_Selection_Q31);float MaxAB_Q41=max(Show_Selection_Q31,Product_Q45);float Width_Q55;Proximity_Visibility_B55(Show_Selection_Q31,Result_Q42,Result_Q43,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Face_Center_Q30,Nrm_World_Q24,Face_Size_Q35,Step_Q46,Width_Q55);vec3 New_P_Q32;vec2 New_UV_Q32;Move_Verts_B32(uv,Out_Radius_Q38,Anisotropy_Q21,Out_Line_Width_Q38,Width_Q55,New_P_Q32,New_UV_Q32);vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q32,Pos_World_Q12);vec3 Out_Position_Q40;vec2 Out_UV_Q40;vec3 Blob_Info_Q40;vec2 Blob_Relative_UV_Q40;Blob_Vertex_B40(Pos_World_Q12,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Position_Q27,_Blob_Intensity_,Near_Size_Q27,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q30,Face_Size_Q35,New_UV_Q32,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q27,Pulse_Q27,Fade_Q27,Blob_Enable_Q27,0.0,Out_Position_Q40,Out_UV_Q40,Blob_Info_Q40,Blob_Relative_UV_Q40);vec2 Rect_UV_Q36;vec2 Scale_XY_Q36;vec4 Rect_Parms_Q36;Round_Rect_Vertex_B36(New_UV_Q32,Tangent_World_Q13,Binormal_World_Q14,Out_Radius_Q38,Anisotropy_Q21,Blob_Relative_UV_Q40,Rect_UV_Q36,Scale_XY_Q36,Rect_Parms_Q36);vec4 Extra_Q33;float Distance_To_Face_Q33;float Distance_Fade1_Q33;float Distance_Fade2_Q33;Proximity_Vertex_B33(Result_Q42,Result_Q43,Face_Center_Q30,Pos_World_Q12,_Proximity_Far_Distance_,1.0,_Proximity_Anisotropy_,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Extra_Q33,Distance_To_Face_Q33,Distance_Fade1_Q33,Distance_Fade2_Q33);vec4 Vec4_Q37=vec4(MaxAB_Q41,Distance_Fade1_Q33,Distance_Fade2_Q33,Out_Radius_Q38);vec3 Position=Out_Position_Q40;vec3 Normal=Vec3_Q29;vec2 UV=Out_UV_Q40;vec3 Tangent=Blob_Info_Q40;vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);vec4 Extra1=Rect_Parms_Q36;vec4 Extra2=Extra_Q33;vec4 Extra3=Vec4_Q37;gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;vTangent=Tangent;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class vN extends Oa{constructor(){super(),this.SMOOTH_EDGES=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class xN extends Ra{constructor(e,t){super(e,t),this.radius=.12,this.lineWidth=.01,this.relativeToHeight=!1,this._filterWidth=1,this.edgeColor=new Ee(.53,.53,.53,1),this.blobEnable=!0,this.blobPosition=new de(100,100,100),this.blobIntensity=.5,this.blobNearSize=.032,this.blobFarSize=.048,this.blobNearDistance=.008,this.blobFarDistance=.064,this.blobFadeLength=.04,this.blobInnerFade=.01,this.blobPulse=0,this.blobFade=1,this.blobPulseMaxSize=.05,this.blobEnable2=!0,this.blobPosition2=new de(10,10.1,-.6),this.blobNearSize2=.008,this.blobInnerFade2=.1,this.blobPulse2=0,this.blobFade2=1,this.gazeIntensity=.8,this.gazeFocus=0,this.selectionFuzz=.5,this.selected=1,this.selectionFade=.2,this.selectionFadeSize=0,this.selectedDistance=.08,this.selectedFadeLength=.08,this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=.016,this.proximityAnisotropy=1,this.useGlobalLeftIndex=!0,this.useGlobalRightIndex=!0,this.fadeOut=1,this.alphaMode=Yd.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Vo(xN.BLOB_TEXTURE_URL,t,!0,!1,Vo.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new vN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlFrontplate",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Relative_To_Height_","_Filter_Width_","_Edge_Color_","_Fade_Out_","_Smooth_Edges_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Pulse_Max_Size_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Gaze_Intensity_","_Gaze_Focus_","_Blob_Texture_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","_Use_Global_Left_Index_","_Use_Global_Right_Index_"],h=[],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Relative_To_Height_",this.relativeToHeight?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Edge_Color_",this.edgeColor),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Blob_Enable_",this.blobEnable?1:0),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.blobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setFloat("_Blob_Pulse_Max_Size_",this.blobPulseMaxSize),this._activeEffect.setFloat("_Blob_Enable_2_",this.blobEnable2?1:0),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.blobInnerFade2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Gaze_Intensity_",this.gazeIntensity),this._activeEffect.setFloat("_Gaze_Focus_",this.gazeFocus),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Use_Global_Left_Index_",this.useGlobalLeftIndex?1:0),this._activeEffect.setFloat("_Use_Global_Right_Index_",this.useGlobalRightIndex?1:0),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new xN(e,this.getScene())),this)}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.MRDLFrontplateMaterial",e}getClassName(){return"MRDLFrontplateMaterial"}static Parse(e,t,i){return yt.Parse((()=>new xN(e.name,t)),e,t,i)}}xN.BLOB_TEXTURE_URL="",qe([st()],xN.prototype,"radius",void 0),qe([st()],xN.prototype,"lineWidth",void 0),qe([st()],xN.prototype,"relativeToHeight",void 0),qe([st()],xN.prototype,"edgeColor",void 0),qe([st()],xN.prototype,"blobEnable",void 0),qe([st()],xN.prototype,"blobPosition",void 0),qe([st()],xN.prototype,"blobIntensity",void 0),qe([st()],xN.prototype,"blobNearSize",void 0),qe([st()],xN.prototype,"blobFarSize",void 0),qe([st()],xN.prototype,"blobNearDistance",void 0),qe([st()],xN.prototype,"blobFarDistance",void 0),qe([st()],xN.prototype,"blobFadeLength",void 0),qe([st()],xN.prototype,"blobInnerFade",void 0),qe([st()],xN.prototype,"blobPulse",void 0),qe([st()],xN.prototype,"blobFade",void 0),qe([st()],xN.prototype,"blobPulseMaxSize",void 0),qe([st()],xN.prototype,"blobEnable2",void 0),qe([st()],xN.prototype,"blobPosition2",void 0),qe([st()],xN.prototype,"blobNearSize2",void 0),qe([st()],xN.prototype,"blobInnerFade2",void 0),qe([st()],xN.prototype,"blobPulse2",void 0),qe([st()],xN.prototype,"blobFade2",void 0),qe([st()],xN.prototype,"gazeIntensity",void 0),qe([st()],xN.prototype,"gazeFocus",void 0),qe([st()],xN.prototype,"selectionFuzz",void 0),qe([st()],xN.prototype,"selected",void 0),qe([st()],xN.prototype,"selectionFade",void 0),qe([st()],xN.prototype,"selectionFadeSize",void 0),qe([st()],xN.prototype,"selectedDistance",void 0),qe([st()],xN.prototype,"selectedFadeLength",void 0),qe([st()],xN.prototype,"proximityMaxIntensity",void 0),qe([st()],xN.prototype,"proximityFarDistance",void 0),qe([st()],xN.prototype,"proximityNearRadius",void 0),qe([st()],xN.prototype,"proximityAnisotropy",void 0),qe([st()],xN.prototype,"useGlobalLeftIndex",void 0),qe([st()],xN.prototype,"useGlobalRightIndex",void 0),ee("BABYLON.GUI.MRDLFrontplateMaterial",xN);bi.ShadersStore.mrdlInnerquadPixelShader="uniform vec3 cameraPosition;varying vec2 vUV;varying vec3 vTangent;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;float FilterStep_Bid194(float edge,float x,float filterWidth)\n{float dx=max(1.0E-5,fwidth(x)*filterWidth);return max((x+dx*0.5-max(edge,x-dx*0.5))/dx,0.0);}\nvoid Round_Rect_B194(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius,\nvec4 Rect_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Glow_Fraction,\nfloat Glow_Max,\nfloat Glow_Falloff,\nout vec4 Color)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius,Radius),halfSize),vec2(0.01,0.01));vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);vec2 delta=(v-nearestp)/max(vec2(0.01,0.01),r);float Distance=length(delta);float insideRect=1.0-FilterStep_Bid194(1.0-Glow_Fraction,Distance,Filter_Width);float glow=clamp((1.0-Distance)/Glow_Fraction,0.0,1.0);glow=pow(glow,Glow_Falloff);Color=Rect_Color*max(insideRect,glow*Glow_Max);}\nvoid main()\n{float X_Q192;float Y_Q192;float Z_Q192;X_Q192=vTangent.x;Y_Q192=vTangent.y;Z_Q192=vTangent.z;vec4 Color_Q194;Round_Rect_B194(X_Q192,1.0,Y_Q192,_Color_,_Filter_Width_,vUV,_Glow_Fraction_,_Glow_Max_,_Glow_Falloff_,Color_Q194);vec4 Out_Color=Color_Q194;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}\n";bi.ShadersStore.mrdlInnerquadVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;varying vec2 vUV;varying vec3 vTangent;void main()\n{vec3 Pos_World_Q189;Pos_World_Q189=(world*vec4(position,1.0)).xyz;vec3 Dir_World_Q190;Dir_World_Q190=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q191;Dir_World_Q191=(world*vec4((cross(normal,tangent)),0.0)).xyz;float Length_Q180=length(Dir_World_Q190);float Length_Q181=length(Dir_World_Q191);float Quotient_Q184=Length_Q180/Length_Q181;float Quotient_Q195=_Radius_/Length_Q181;vec2 Result_Q193;Result_Q193=vec2((uv.x-0.5)*Length_Q180/Length_Q181,(uv.y-0.5));float Result_Q198=_Fixed_Radius_ ? Quotient_Q195 : _Radius_;vec3 Vec3_Q183=vec3(Quotient_Q184,Result_Q198,0);vec3 Position=Pos_World_Q189;vec3 Normal=vec3(0,0,0);vec2 UV=Result_Q193;vec3 Tangent=Vec3_Q183;vec3 Binormal=vec3(0,0,0);vec4 Color=color;gl_Position=viewProjection*vec4(Position,1);vUV=UV;vTangent=Tangent;}\n";class bN extends Oa{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class TN extends Ra{constructor(e,t){super(e,t),this.color=new Ee(1,1,1,.05),this.radius=.12,this.fixedRadius=!0,this._filterWidth=1,this.glowFraction=0,this.glowMax=.5,this.glowFalloff=2,this.alphaMode=Yd.ALPHA_COMBINE,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new bN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(ro(e,s,!0,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),Kn(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[ys.PositionKind];s.NORMAL&&i.push(ys.NormalKind),s.UV1&&i.push(ys.UVKind),s.UV2&&i.push(ys.UV2Kind),s.VERTEXCOLOR&&i.push(ys.ColorKind),s.TANGENT&&i.push(ys.TangentKind),jn(i,s);const o="mrdlInnerquad",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Color_","_Radius_","_Fixed_Radius_","_Filter_Width_","_Glow_Fraction_","_Glow_Max_","_Glow_Falloff_"],h=[],c=[];co({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Fixed_Radius_",this.fixedRadius?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setFloat("_Glow_Fraction_",this.glowFraction),this._activeEffect.setFloat("_Glow_Max_",this.glowMax),this._activeEffect.setFloat("_Glow_Falloff_",this.glowFalloff),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new TN(e,this.getScene())),this)}serialize(){const e=yt.Serialize(this);return e.customType="BABYLON.MRDLInnerquadMaterial",e}getClassName(){return"MRDLInnerquadMaterial"}static Parse(e,t,i){return yt.Parse((()=>new TN(e.name,t)),e,t,i)}}qe([st()],TN.prototype,"color",void 0),qe([st()],TN.prototype,"radius",void 0),qe([st()],TN.prototype,"fixedRadius",void 0),qe([st()],TN.prototype,"glowFraction",void 0),qe([st()],TN.prototype,"glowMax",void 0),qe([st()],TN.prototype,"glowFalloff",void 0),ee("BABYLON.GUI.MRDLInnerquadMaterial",TN);class yN extends Yw{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._backGlow.renderingGroupId=e,this._innerQuad.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=ta("",{size:1},this._backPlate._scene),this._tooltipMesh.position=de.Down().scale(.7).add(de.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._frontPlateCollisionMesh,this._tooltipTexture=Cw.CreateForMesh(this._tooltipMesh);const t=new kD;t.height=.25,t.width=.8,t.cornerRadius=25,t.color="#ffffff",t.thickness=20,t.background="#060668",this._tooltipTexture.addControl(t),this._tooltipTextBlock=new UD,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=100,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new qo,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?.text||null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get subtext(){return this._subtext}set subtext(e){this._subtext!==e&&(this._subtext=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get backGlowMaterial(){return this._backGlowMaterial}get innerQuadMaterial(){return this._innerQuadMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this.width=1,this.height=1,this.radius=.14,this.textSizeInPixels=18,this.imageSizeInPixels=40,this.plateMaterialColor=new Ce(.4,.4,.4),this.frontPlateDepth=.2,this.backPlateDepth=.04,this.backGlowOffset=.1,this.flatPlaneDepth=.001,this.innerQuadRadius=this.radius-.04,this.innerQuadColor=new Ee(0,0,0,0),this.innerQuadToggledColor=new Ee(.5197843,.6485234,.9607843,.6),this.innerQuadHoverColor=new Ee(1,1,1,.05),this.innerQuadToggledHoverColor=new Ee(.5197843,.6485234,.9607843,1),this._isBackplateVisible=!0,this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(1),this.isToggleButton&&this._innerQuadMaterial&&(this.isToggled?this._innerQuadMaterial.color=this.innerQuadToggledHoverColor:this._innerQuadMaterial.color=this.innerQuadHoverColor)},this.pointerOutAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(-.8),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)},this.pointerDownAnimation=()=>{},this.pointerUpAnimation=()=>{},this._pointerClickObserver=this.onPointerClickObservable.add((()=>{this._frontPlate&&this._backGlow&&!this.isActiveNearInteraction&&this._performClickAnimation(),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)})),this._pointerEnterObserver=this.onPointerEnterObservable.add((()=>{this.pointerEnterAnimation()})),this._pointerOutObserver=this.onPointerOutObservable.add((()=>{this.pointerOutAnimation()})),this._toggleObserver=this.onToggleObservable.add((e=>{this._innerQuadMaterial.color=e?this.innerQuadToggledColor:this.innerQuadColor}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){let e;e=this._getAspectRatio()<=1?this._alignContentVertically():this._alignContentHorizontally(),this.content=e}_getAspectRatio(){return this.width/this.height}_alignContentVertically(){const e=new WD;if(e.isVertical=!0,Vt()&&document.createElement&&this._imageUrl){const t=new GD;t.source=this._imageUrl,t.heightInPixels=180,t.widthInPixels=100,t.paddingTopInPixels=40,t.paddingBottomInPixels=40,e.addControl(t)}if(this._text){const t=new UD;t.text=this._text,t.color="white",t.heightInPixels=30,t.fontSize=24,e.addControl(t)}return e}_alignContentHorizontally(){let e=240;const t=15,i=new kD;i.widthInPixels=e,i.heightInPixels=e,i.color="transparent",i.setPaddingInPixels(t,t,t,t),e-=30;const s=new WD;if(s.isVertical=!1,s.scaleY=this._getAspectRatio(),Vt()&&document.createElement&&this._imageUrl){const t=new kD(`${this.name}_image`);t.widthInPixels=this.imageSizeInPixels,t.heightInPixels=this.imageSizeInPixels,t.color="transparent",e-=this.imageSizeInPixels;const i=new GD;i.source=this._imageUrl,t.addControl(i),s.addControl(t)}if(this._text){const i=new UD(`${this.name}_text`);if(i.text=this._text,i.color="white",i.fontSize=this.textSizeInPixels,i.widthInPixels=e,this._imageUrl&&(i.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,i.paddingLeftInPixels=t),this._subtext){const r=new QD;r.addColumnDefinition(1),r.addRowDefinition(.5),r.addRowDefinition(.5),r.widthInPixels=e,r.heightInPixels=45;const n=new UD(`${this.name}_subtext`);n.text=this._subtext,n.color="#EEEEEEAB",n.fontSize=.75*this.textSizeInPixels,n.fontWeight="600",this._imageUrl&&(n.textHorizontalAlignment=BD.HORIZONTAL_ALIGNMENT_LEFT,n.paddingLeftInPixels=t),r.addControl(i,0),r.addControl(n,1),s.addControl(r)}else s.addControl(i)}return i.addControl(s),i}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=this._createBackPlate(e),i=this._createFrontPlate(e),s=this._createInnerQuad(e),r=this._createBackGlow(e);this._frontPlateCollisionMesh=i,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.scaling.x=this.width,this._textPlate.parent=i,this._backPlate=t,this._backPlate.position=de.Forward(e.useRightHandedSystem).scale(this.backPlateDepth/2),this._backPlate.isPickable=!1,this._backPlate.addChild(i),this._backPlate.addChild(s),r&&this._backPlate.addChild(r);const n=new xn(`${this.name}_root`,e);return this._backPlate.setParent(n),this.collisionMesh=i,this.collidableFrontDirection=this._backPlate.forward.negate(),n}_createBackPlate(e){const t=yu(`${this.name}_backPlate`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=.2,Pa.ImportMeshAsync(void 0,yN.MRTK_ASSET_BASE_URL,yN.BACKPLATE_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.visibility=0,this._isBackplateVisible&&(i.visibility=1,i.name=`${this.name}_backPlate`,i.isPickable=!1,i.scaling.x=this.width,i.scaling.y=this.height,i.parent=t),this._backMaterial&&(i.material=this._backMaterial),this._backPlate=i})),t}_createFrontPlate(e){const t=yu(`${this.name}_frontPlate`,{width:this.width,height:this.height,depth:this.frontPlateDepth},e);return t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=de.Forward(e.useRightHandedSystem).scale((this.backPlateDepth-this.frontPlateDepth)/2),Pa.ImportMeshAsync(void 0,yN.MRTK_ASSET_BASE_URL,yN.FRONTPLATE_MODEL_FILENAME,e).then((i=>{const s=yu(`${this.name}_collisionPlate`,{width:this.width,height:this.height},e);s.isPickable=!1,s.scaling.z=this.frontPlateDepth,s.visibility=0,s.parent=t,this._collisionPlate=s;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.x=this.width-this.backGlowOffset,r.scaling.y=this.height-this.backGlowOffset,r.position=de.Forward(e.useRightHandedSystem).scale(-.5),r.parent=s,this.isToggleButton&&(r.visibility=0),this._frontMaterial&&(r.material=this._frontMaterial),this._textPlate.scaling.x=1,this._textPlate.parent=r,this._frontPlate=r})),t}_createInnerQuad(e){const t=yu(`${this.name}_innerQuad`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-this.flatPlaneDepth,Pa.ImportMeshAsync(void 0,yN.MRTK_ASSET_BASE_URL,yN.INNERQUAD_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_innerQuad`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._innerQuadMaterial&&(i.material=this._innerQuadMaterial),this._innerQuad=i})),t}_createBackGlow(e){if(this.isToggleButton)return;const t=yu(`${this.name}_backGlow`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-2*this.flatPlaneDepth,Pa.ImportMeshAsync(void 0,yN.MRTK_ASSET_BASE_URL,yN.BACKGLOW_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_backGlow`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._backGlowMaterial&&(i.material=this._backGlowMaterial),this._backGlow=i})),t}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=this.plateMaterialColor}_performClickAnimation(){const e=new kr("Click Animation Group"),t=[{name:"backGlowMotion",mesh:this._backGlow,property:"material.motion",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[1,.0144,.0144]},{frame:40,values:[.0027713229489760476,0,0]},{frame:45,values:[.0027713229489760476]}]},{name:"_collisionPlateZSlide",mesh:this._collisionPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[de.Forward(this._collisionPlate._scene.useRightHandedSystem).scale(this.frontPlateDepth/2).z,0,0]},{frame:40,values:[0,.005403332496794331]},{frame:45,values:[0]}]},{name:"_collisionPlateZScale",mesh:this._collisionPlate,property:"scaling.z",keys:[{frame:0,values:[this.frontPlateDepth,0,0]},{frame:20,values:[this.backPlateDepth,0,0]},{frame:40,values:[this.frontPlateDepth,.0054]},{frame:45,values:[this.frontPlateDepth]}]}];for(const i of t){const t=new Nt(i.name,i.property,60,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CYCLE),s=[];for(const e of i.keys)s.push({frame:e.frame,value:e.values[0],inTangent:e.values[1],outTangent:e.values[2],interpolation:e.values[3]});t.setKeys(s),i.mesh&&e.addTargetedAnimation(t,i.mesh)}e.normalize(0,45),e.speedRatio=1,e.play()}_performEnterExitAnimation(e){const t=new kr("Enter Exit Animation Group"),i=[{name:"frontPlateFadeOut",mesh:this._frontPlate,property:"material.fadeOut",keys:[{frame:0,values:[0,0,.025045314830017686,0]},{frame:40,values:[1.00205599570012,.025045314830017686,0,0]}]},{name:"textPlateZSlide",mesh:this._textPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:40,values:[de.Forward(this._textPlate._scene.useRightHandedSystem).scale(-.15).z,0,0]}]}];for(const e of i){const i=new Nt(e.name,e.property,60,Nt.ANIMATIONTYPE_FLOAT,Nt.ANIMATIONLOOPMODE_CYCLE),s=[];for(const t of e.keys)s.push({frame:t.frame,value:t.values[0],inTangent:t.values[1],outTangent:t.values[2],interpolation:t.values[3]});i.setKeys(s),e.mesh&&t.addTargetedAnimation(i,e.mesh)}t.normalize(0,45),t.speedRatio=e,t.play()}_createBackMaterial(e){this._backMaterial=this._backMaterial??new uN(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.absoluteSizes=!0,this._backMaterial.radius=this.radius,this._backMaterial.lineWidth=.02}_createFrontMaterial(e){this._frontMaterial=this._frontMaterial??new xN(this.name+"Front Material",e.getScene()),this.frontMaterial.radius=this.innerQuadRadius,this.frontMaterial.fadeOut=0}_createBackGlowMaterial(e){const t=this.radius+.04;this._backGlowMaterial=this._backGlowMaterial??new gN(this.name+"Back Glow Material",e.getScene()),this._backGlowMaterial.bevelRadius=t,this._backGlowMaterial.lineWidth=t,this._backGlowMaterial.motion=0}_createInnerQuadMaterial(e){this._innerQuadMaterial=this._innerQuadMaterial??new TN("inner_quad",e.getScene()),this._innerQuadMaterial.radius=this.innerQuadRadius,this.isToggleButton&&(this._innerQuadMaterial.color=this.innerQuadColor)}_createPlateMaterial(e){this._plateMaterial=this._plateMaterial??new yc(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ce.Black()}_onToggle(e){super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.mrdlBackplateMaterial?this._backMaterial=this._host._touchSharedMaterials.mrdlBackplateMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.mrdlBackplateMaterial=this._backMaterial),this._host._touchSharedMaterials.mrdlFrontplateMaterial?this._frontMaterial=this._host._touchSharedMaterials.mrdlFrontplateMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.mrdlFrontplateMaterial=this._frontMaterial),this._host._touchSharedMaterials.mrdlBackglowMaterial?this._backGlowMaterial=this._host._touchSharedMaterials.mrdlBackglowMaterial:(this._createBackGlowMaterial(e),this._host._touchSharedMaterials.mrdlBackglowMaterial=this._backGlowMaterial),this._host._touchSharedMaterials.mrdlInnerQuadMaterial?this._innerQuadMaterial=this._host._touchSharedMaterials.mrdlInnerQuadMaterial:(this._createInnerQuadMaterial(e),this._host._touchSharedMaterials.mrdlInnerQuadMaterial=this._innerQuadMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e),this._createBackGlowMaterial(e),this._createInnerQuadMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._backGlow&&(this._backGlow.material=this._backGlowMaterial),this._innerQuad&&(this._innerQuad.material=this._innerQuadMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerClickObservable.remove(this._pointerClickObserver),this.onPointerEnterObservable.remove(this._pointerEnterObserver),this.onPointerOutObservable.remove(this._pointerOutObserver),this.onToggleObservable.remove(this._toggleObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._backGlowMaterial.dispose(),this._innerQuadMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}yN.MRTK_ASSET_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",yN.FRONTPLATE_MODEL_FILENAME="mrtk-fluent-frontplate.glb",yN.BACKPLATE_MODEL_FILENAME="mrtk-fluent-backplate.glb",yN.BACKGLOW_MODEL_FILENAME="mrtk-fluent-button.glb",yN.INNERQUAD_MODEL_FILENAME="SlateProximity.glb";class SN{get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get controlScaling(){return this._customControlScaling}set controlScaling(e){if(this._customControlScaling!==e&&e>0){const t=e/this._customControlScaling;this._customControlScaling=e,this._rootContainer.children.forEach((i=>{i.scaling.scaleInPlace(t),1!==e&&(i._isScaledByManager=!0)}))}}get useRealisticScaling(){return this.controlScaling===SN.MRTK_REALISTIC_SCALING}set useRealisticScaling(e){this.controlScaling=e?SN.MRTK_REALISTIC_SCALING:1}constructor(e){this._customControlScaling=1,this._lastControlOver={},this._lastControlDown={},this.onPickedPointChangedObservable=new X,this.onPickingObservable=new X,this._sharedMaterials={},this._touchSharedMaterials={},this._scene=e||se.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>{this._sceneDisposeObserver=null,this._utilityLayer=null,this.dispose()})),this._utilityLayer=uu._CreateDefaultUtilityLayerFromScene(this._scene),this._utilityLayer.onlyCheckPointerDownEvents=!1,this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.mainSceneTrackerPredicate=e=>e&&e.reservedDataStore?.GUI3D?.control?._node,this._rootContainer=new ww("RootContainer"),this._rootContainer._host=this;const t=this._utilityLayer.utilityLayerScene;this._pointerOutObserver=this._utilityLayer.onPointerOutObservable.add((e=>{this._handlePointerOut(e,!0)})),this._pointerObserver=t.onPointerObservable.add((e=>{this._doPicking(e)})),this._utilityLayer.utilityLayerScene.autoClear=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,new cu("hemi",de.Up(),this._utilityLayer.utilityLayerScene)}_handlePointerOut(e,t){const i=this._lastControlOver[e];i&&(i._onPointerOut(i),delete this._lastControlOver[e]),t&&this._lastControlDown[e]&&(this._lastControlDown[e].forcePointerUp(),delete this._lastControlDown[e]),this.onPickedPointChangedObservable.notifyObservers(null)}_doPicking(e){if(!this._utilityLayer||!this._utilityLayer.shouldRender||!this._utilityLayer.utilityLayerScene.activeCamera)return!1;const t=e.event,i=t.pointerId||0,s=t.button,r=e.pickInfo;if(r&&this.onPickingObservable.notifyObservers(r.pickedMesh),!r||!r.hit)return this._handlePointerOut(i,e.type===Ms.POINTERUP),!1;r.pickedPoint&&this.onPickedPointChangedObservable.notifyObservers(r.pickedPoint);const n=r.pickedMesh.reservedDataStore?.GUI3D?.control;return n&&!n._processObservables(e.type,r.pickedPoint,r.originMesh?.position||null,i,s)&&e.type===Ms.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i]),delete this._lastControlOver[i]),e.type===Ms.POINTERUP&&(this._lastControlDown[t.pointerId]&&(this._lastControlDown[t.pointerId].forcePointerUp(),delete this._lastControlDown[t.pointerId]),("touch"===t.pointerType||"xr"===t.pointerType&&this._scene.getEngine().hostInformation.isMobile)&&this._handlePointerOut(i,!1)),!0}get rootContainer(){return this._rootContainer}containsControl(e){return this._rootContainer.containsControl(e)}addControl(e){return this._rootContainer.addControl(e),1!==this._customControlScaling&&(e.scaling.scaleInPlace(this._customControlScaling),e._isScaledByManager=!0),this}removeControl(e){return this._rootContainer.removeControl(e),e._isScaledByManager&&(e.scaling.scaleInPlace(1/this._customControlScaling),e._isScaledByManager=!1),this}dispose(){this._rootContainer.dispose();for(const e in this._sharedMaterials)Object.prototype.hasOwnProperty.call(this._sharedMaterials,e)&&this._sharedMaterials[e].dispose();this._sharedMaterials={};for(const e in this._touchSharedMaterials)Object.prototype.hasOwnProperty.call(this._touchSharedMaterials,e)&&this._touchSharedMaterials[e].dispose();this._touchSharedMaterials={},this._pointerOutObserver&&this._utilityLayer&&(this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver),this._pointerOutObserver=null),this.onPickedPointChangedObservable.clear(),this.onPickingObservable.clear();const e=this._utilityLayer?this._utilityLayer.utilityLayerScene:null;e&&this._pointerObserver&&(e.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=null),this._scene&&this._sceneDisposeObserver&&(this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null),this._utilityLayer&&this._utilityLayer.dispose()}}function CN(e,t,i,s){const r={externalResourceFunction:s};return i&&(r.uri="file:"===t?i:t+i),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,r):GLTFValidator.validateString(e,r)}function EN(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":CN(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,s)=>{const r=e.length;e.push({resolve:i,reject:s}),postMessage({id:"getExternalResource",index:r,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}SN.MRTK_REALISTIC_SCALING=.032;class AN{static ValidateAsync(e,t,i,s){return"function"==typeof Worker?new Promise(((r,n)=>{const o=`${CN}(${EN})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),n(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":s(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),r(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),n(t.reason),l.terminate()}};if(l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:hs.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const s=e.slice();l.postMessage({id:"validate",data:s,rootUrl:t,fileName:i},[s.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=hs.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>CN(e,t,i,s))))}}function PN(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}var RN,IN,MN,ON,DN,wN,NN,FN,BN,LN,kN,VN;AN.Configuration={url:`${hs._DefaultCdnUrl}/gltf_validator.js`},function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(RN||(RN={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(IN||(IN={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(MN||(MN={}));class UN{constructor(){this.onParsedObservable=new X,this.coordinateSystemMode=RN.AUTO,this.animationStartMode=IN.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new X,this.onSkinLoadedObservable=new X,this.onTextureLoadedObservable=new X,this.onMaterialLoadedObservable=new X,this.onCameraLoadedObservable=new X,this.onCompleteObservable=new X,this.onErrorObservable=new X,this.onDisposeObservable=new X,this.onExtensionLoadedObservable=new X,this.validate=!1,this.onValidatedObservable=new X,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new X,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,s,r,n,o,a){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,s,o,a),null;this._progressCallback=r;const l=t.name||hs.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&we.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new X},r={readAsync:(i,s)=>new Promise(((r,n)=>{this._loadFile(e,t,(e=>{r(new Uint8Array(e))}),!0,(e=>{n(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+s-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new TR(r)).then((e=>{i.onCompleteObservable.notifyObservers(i),s(e)}),o?e=>o(void 0,e):void 0),i}return this._loadFile(e,t,(t=>{this._validate(e,new Uint8Array(t,0,t.byteLength),i,l),this._unpackBinaryAsync(new TR({readAsync:(e,i)=>PN(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),o?e=>o(void 0,e):void 0)}),!0,o)}return this._loadFile(e,t,(t=>{this._validate(e,t,i,l),s({json:this._parseJson(t)})}),!1,o)}_loadBinary(e,t,i,s,r,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new TR({readAsync:(e,i)=>function(e,t,i){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+i>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(e){return Promise.reject(e)}}(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,i,s,r,n){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,s,r,n))))}loadAsync(e,t,i,s,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,s,r))))}loadAssetContainerAsync(e,t,i,s,r){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const n=new Eo(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,n,t,i,s,r).then((e=>(Array.prototype.push.apply(n.geometries,e.geometries),Array.prototype.push.apply(n.meshes,e.meshes),Array.prototype.push.apply(n.particleSystems,e.particleSystems),Array.prototype.push.apply(n.skeletons,e.skeletons),Array.prototype.push.apply(n.animationGroups,e.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,a),Array.prototype.push.apply(n.lights,e.lights),Array.prototype.push.apply(n.transformNodes,e.transformNodes),Array.prototype.push.apply(n.cameras,l),Array.prototype.push.apply(n.morphTargetManagers,h),n)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+UN._MagicBase64Encoded)||e.startsWith("data:;base64,"+UN._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+UN._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+UN._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+UN._MagicBase64Encoded)||t.startsWith(";base64,"+UN._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+UN._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+UN._MagicBase64Encoded)){const i=es(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new TR({readAsync:(e,t)=>PN(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new UN}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(MN[this._state]))}_loadFile(e,t,i,s,r,n){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,s,r,n);return o.onCompleteObservable.add((e=>{this._requests.splice(this._requests.indexOf(e),1)})),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,s=0,r=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;i=i&&e._lengthComputable,s+=e._loaded,r+=e._total}this._progressCallback({lengthComputable:i,loaded:s,total:i?r:0})}_validate(e,t,i="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),AN.ValidateAsync(t,i,s,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0).then((e=>new Uint8Array(e,0,e.byteLength))))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),hs.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()})))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const i=UN._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=UN._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(UN._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:UN._CreateGLTF1Loader,2:UN._CreateGLTF2Loader}[i.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then((()=>{const t=e.readUint32();if(1179937895!==t)throw new Qt("Unexpected magic: "+t,Yt.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const s=e.readUint32();let r;switch(this.useRangeRequests||s===e.buffer.byteLength||we.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`),i){case 1:r=this._unpackBinaryV1Async(e,s);break;case 2:r=this._unpackBinaryV2Async(e,s);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),r}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),s=e.readUint32();if(0!==s)throw new Error(`Unexpected content format: ${s}`);const r=t-e.byteOffset,n={json:this._parseJson(e.readString(i)),bin:null};if(0!==r){const t=e.byteOffset;n.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:r}}return Promise.resolve(n)}_unpackBinaryV2Async(e,t){const i=1313821514,s=e.readUint32();if(e.readUint32()!==i)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then((()=>({json:this._parseJson(e.readString(s)),bin:null}))):e.loadAsync(s+8).then((()=>{const r={json:this._parseJson(e.readString(s)),bin:null},n=()=>{const s=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;r.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:s},e.skipBytes(s);break}default:e.skipBytes(s)}return e.byteOffset!==t?e.loadAsync(8).then(n):Promise.resolve(r)};return n()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minorn.byteLength)throw new Error("Buffer access is out of range");const o=n.buffer;switch(i+=n.byteOffset,r){case ON.BYTE:return new Int8Array(o,i,s);case ON.UNSIGNED_BYTE:return new Uint8Array(o,i,s);case ON.SHORT:return new Int16Array(o,i,s);case ON.UNSIGNED_SHORT:return new Uint16Array(o,i,s);default:return new Float32Array(o,i,s)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],s=t.count*GN.GetByteStrideFromType(t);return GN.GetBufferFromBufferView(e,i,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let s=0;s=this._maxPos}}const WN=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],HN=["world","view","projection","worldView","worldViewProjection","mBones"],XN=["translation","rotation","scale"],YN=["position","rotationQuaternion","scaling"],QN=(e,t,i)=>{for(const s in e){const r=e[s];i[t][s]=r}},jN=e=>{if(e)for(let t=0;t{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},$N=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=de.FromArray(e.scale||[1,1,1]),s=pe.FromArray(e.rotation||[0,0,0,1]),r=de.FromArray(e.translation||[0,0,0]);t=fe.Compose(i,s,r)}else t=fe.FromArray(e.matrix);return t},qN=(e,t,i,s)=>{for(let e=0;e{for(let i=0;i{const i=e.nodes;let s=i[t];if(s)return{node:s,id:t};for(const e in i)if(s=i[e],s.jointName===t)return{node:s,id:e};return null},eF=(e,t)=>{for(let i=0;i{if(r||(e.scene._blockEntityCollection=!!e.assetContainer,(r=new bo(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.id=s),!t.babylonNode)return r;const n=[];let o=null;const a=[],l=[],h=[],c=[];for(let t=0;t1?(u=new _o("multimat"+s,e.scene),u.subMaterials=n):u=new yc("multimat"+s,e.scene),1===n.length&&(u=n[0]),u._parentContainer=e.assetContainer,r.material||(r.material=u),new _n(s,e.scene,o,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let d=0;for(let t=0;t{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=s)},sF=(e,t,i)=>{let s=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const r=e.skins[t.skin],n=tF(e,t,t.meshes,i,t.babylonNode);n.skeleton=e.scene.getLastSkeletonById(t.skin),null===n.skeleton&&(n.skeleton=((e,t,i,s)=>{if(s||(s=new Ho(t.name||"","",e.scene)),!t.babylonSkeleton)return s;const r=[],n=[];((e,t,i,s)=>{for(const r in e.nodes){const n=e.nodes[r],o=r;if(!n.jointName||eF(i,n.jointName))continue;const a=$N(n),l=new pr(n.name||"",t,null,a);l.id=o,s.push({bone:l,node:n,id:o})}for(let e=0;e0&&(u=ZN(r,l),u&&-1===n.indexOf(u)&&n.push(u)),new pr(a.jointName||"",s,u,d).id=l}const o=s.bones;s.bones=[];for(let i=0;i{if(t.matrix){const i=new de(0,0,0),s=new pe,r=new de(0,0,0);fe.FromArray(t.matrix).decompose(r,s,i),iF(e,i,s,r)}else t.translation&&t.rotation&&t.scale&&iF(e,de.FromArray(t.translation),pe.FromArray(t.rotation),de.FromArray(t.scale));e.computeWorldMatrix(!0)})(s,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],r=t.scale||[1,1,1];iF(s,de.FromArray(e),pe.FromArray(i),de.FromArray(r))}s.updateCache(!0),t.babylonNode=s}return s},rF=(e,t,i,s=!1)=>{const r=e.nodes[t];let n=null;if(s=!(e.importOnlyMeshes&&!s&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(r.name||"")||0===e.importMeshesNames.length,!r.jointName&&s&&(n=sF(e,r,t),null!==n&&(n.id=t,n.parent=i)),r.children)for(let t=0;t{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let s=null;for(let r=0;r{for(const s in t.uniforms){const r=t.uniforms[s],n=t.parameters[r];if(e.currentIdentifier===s&&n.semantic&&!n.source&&!n.node){const e=WN.indexOf(n.semantic);if(-1!==e)return delete i[s],HN[e]}}return e.currentIdentifier},aF=e=>{for(const t in e.materials)cF.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class lF{static CreateRuntime(e,t,i){const s={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&QN(e.extensions,"extensions",s),e.extensionsUsed&&QN(e.extensionsUsed,"extensionsUsed",s),e.buffers&&((e,t)=>{for(const i in e){const s=e[i];t.buffers[i]=s,t.buffersCount++}})(e.buffers,s),e.bufferViews&&QN(e.bufferViews,"bufferViews",s),e.accessors&&QN(e.accessors,"accessors",s),e.meshes&&QN(e.meshes,"meshes",s),e.lights&&QN(e.lights,"lights",s),e.cameras&&QN(e.cameras,"cameras",s),e.nodes&&QN(e.nodes,"nodes",s),e.images&&QN(e.images,"images",s),e.textures&&QN(e.textures,"textures",s),e.shaders&&((e,t)=>{for(const i in e){const s=e[i];t.shaders[i]=s,t.shaderscount++}})(e.shaders,s),e.programs&&QN(e.programs,"programs",s),e.samplers&&QN(e.samplers,"samplers",s),e.techniques&&QN(e.techniques,"techniques",s),e.materials&&QN(e.materials,"materials",s),e.animations&&QN(e.animations,"animations",s),e.skins&&QN(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];hs.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(hs.DecodeBase64(n.uri))))):hs.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),r,void 0,!0,(e=>{e&&s(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source)return void s("");if(r.babylonTexture)return void i(null);const n=e.images[r.source];hs.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(hs.DecodeBase64(n.uri))))):hs.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&s(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture)return void s(r.babylonTexture);const n=e.samplers[r.sampler],o=n.minFilter===FN.NEAREST_MIPMAP_NEAREST||n.minFilter===FN.NEAREST_MIPMAP_LINEAR||n.minFilter===FN.LINEAR_MIPMAP_NEAREST||n.minFilter===FN.LINEAR_MIPMAP_LINEAR,a=Vo.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),u=new Vo(h,e.scene,!o,!0,a,c,c);void 0!==n.wrapS&&(u.wrapU=GN.GetWrapMode(n.wrapS)),void 0!==n.wrapT&&(u.wrapV=GN.GetWrapMode(n.wrapT)),u.name=t,r.babylonTexture=u,s(u)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(hs.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);i&&i(e)}else hs.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,(e=>{e&&s&&s(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique)return void(s&&s("No technique found."));const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const s=new yc(t,e.scene);return s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.diffuseColor=new Ce(.5,.5,.5),s.sideOrientation=uo.CounterClockWiseSideOrientation,void i(s)}const o=e.programs[n.program],a=n.states,l=Ti.ShadersStore[o.vertexShader+"VertexShader"],h=Ti.ShadersStore[o.fragmentShader+"PixelShader"];let c="",u="";const d=new zN(l),_=new zN(h),p={},f=[],m=[],g=[];for(const e in n.uniforms){const t=n.uniforms[e],i=n.parameters[t];if(p[e]=i,!i.semantic||i.node||i.source)i.type===wN.SAMPLER_2D?g.push(e):f.push(e);else{const t=WN.indexOf(i.semantic);-1!==t?(f.push(HN[t]),delete p[e]):f.push(e)}}for(const e in n.attributes){const t=n.attributes[e],i=n.parameters[t];if(i.semantic){const e=KN(i);e&&m.push(e)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==VN.IDENTIFIER){c+=d.currentString;continue}let e=!1;for(const t in n.attributes){const i=n.attributes[t],s=n.parameters[i];if(d.currentIdentifier===t&&s.semantic){c+=KN(s),e=!0;break}}e||(c+=oF(d,n,p))}for(;!_.isEnd()&&_.getNextToken();)_.currentToken===VN.IDENTIFIER?u+=oF(_,n,p):u+=_.currentString;const v={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},x={attributes:m,uniforms:f,samplers:g,needAlphaBlending:a&&a.enable&&-1!==a.enable.indexOf(3042)};Ti.ShadersStore[o.vertexShader+t+"VertexShader"]=c,Ti.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const b=new Yu(t,e.scene,v,x);if(b.onError=((e,t,i)=>(s,r)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+r+". Default material will be applied")})(o,b,s),b.onCompiled=((e,t,i,s,r,n)=>o=>{((e,t,i,s,r)=>{const n=s.values||i.parameters,o=i.uniforms;for(const i in r){const a=r[i],l=a.type;let h=n[o[i]];if(void 0===h&&(h=a.value),!h)continue;const c=e=>i=>{a.value&&e&&(t.setTexture(e,i),delete r[e])};l===wN.SAMPLER_2D?cF.LoadTextureAsync(e,s.values?h:a.value,c(i),(()=>c(null))):a.value&&GN.SetUniform(t,i,s.values?h:a.value,l)&&delete r[i]}})(e,t,i,s,r),t.onBind=o=>{((e,t,i,s,r,n,o)=>{const a=n.values||r.parameters;for(const o in i){const l=i[o],h=l.type;if(h===wN.FLOAT_MAT2||h===wN.FLOAT_MAT3||h===wN.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;GN.SetMatrix(t.scene,e,l,o,s.getEffect())}}else GN.SetMatrix(t.scene,e,l,o,s.getEffect());else{const e=a[r.uniforms[o]];if(!e)continue;if(h===wN.SAMPLER_2D){const i=t.textures[n.values?e:l.value].babylonTexture;if(null==i)continue;s.getEffect().setTexture(o,i)}else GN.SetUniform(s.getEffect(),o,e,h)}}o(s)})(o,e,r,t,i,s,n)}})(e,b,n,r,p,i),b.sideOrientation=uo.CounterClockWiseSideOrientation,a&&a.functions){const e=a.functions;e.cullFace&&e.cullFace[0]!==LN.BACK&&(b.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===kN.SRC_ALPHA&&t[1]===kN.ONE_MINUS_SRC_ALPHA&&t[2]===kN.ONE&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_COMBINE:t[0]===kN.ONE&&t[1]===kN.ONE&&t[2]===kN.ZERO&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_ONEONE:t[0]===kN.SRC_ALPHA&&t[1]===kN.ONE&&t[2]===kN.ZERO&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_ADD:t[0]===kN.ZERO&&t[1]===kN.ONE_MINUS_SRC_COLOR&&t[2]===kN.ONE&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_SUBTRACT:t[0]===kN.DST_COLOR&&t[1]===kN.ZERO&&t[2]===kN.ONE&&t[3]===kN.ONE?b.alphaMode=Yd.ALPHA_MULTIPLY:t[0]===kN.SRC_ALPHA&&t[1]===kN.ONE_MINUS_SRC_COLOR&&t[2]===kN.ONE&&t[3]===kN.ONE&&(b.alphaMode=Yd.ALPHA_MAXIMIZED))}}}class hF{static RegisterExtension(e){hF.Extensions[e.name]?hs.Error('Tool with the same name "'+e.name+'" already exists'):hF.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,o,a){return t.useRightHandedSystem=!0,cF.LoadRuntimeAsync(t,i,s,(t=>{t.assetContainer=r,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],hs.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=[],s=[];for(const e in t.nodes){const s=t.nodes[e];s.babylonNode instanceof Sn&&i.push(s.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof Ho&&s.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{aF(t),nF(t),!UN.IncrementalLoading&&n&&n(i,s)}))})),UN.IncrementalLoading&&n&&n(i,s)}),a),!0}importMeshAsync(e,t,i,s,r,n){return new Promise(((o,a)=>{this._importMeshAsync(e,t,s,r,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})}),n,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,cF.LoadRuntimeAsync(e,t,i,(e=>{cF.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{aF(e),nF(e),UN.IncrementalLoading||s()}))})),UN.IncrementalLoading&&s()}),n)}),n)}loadAsync(e,t,i,s){return new Promise(((r,n)=>{this._loadAsync(e,t,i,(()=>{r()}),s,(e=>{n(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const s=(i,s)=>{cF.LoadShaderStringAsync(e,i,(r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(Ti.ShadersStore[i+(s.type===DN.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{hs.Error("Error when loading shader program named "+i+" located at "+s.uri)}))};for(const t in e.shaders){i=!0;const r=e.shaders[t];r?s.bind(this,t,r)():hs.Error("No shader named: "+t)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(i,s)=>{cF.LoadBufferAsync(e,i,(r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[i].byteLength&&hs.Error("Buffer named "+i+" is length "+r.byteLength+". Expected: "+s.byteLength),e.loadedBufferViews[i]=r),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{hs.Error("Error when loading buffer named "+i+" located at "+s.uri)}))};for(const t in e.buffers){i=!0;const r=e.buffers[t];r?s.bind(this,t,r)():hs.Error("No buffer named: "+t)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,s,r)),(()=>{setTimeout((()=>{s&&s(lF.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){cF._ApplyExtensions((s=>s.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,s,r){cF._ApplyExtensions((n=>n.loadBufferAsync(e,t,i,s,r)),(()=>{lF.LoadBufferAsync(e,t,i,s,r)}))}static LoadTextureAsync(e,t,i,s){cF._LoadTextureBufferAsync(e,t,(r=>{r&&cF._CreateTextureAsync(e,t,r,i,s)}),s)}static LoadShaderStringAsync(e,t,i,s){cF._ApplyExtensions((r=>r.loadShaderStringAsync(e,t,i,s)),(()=>{lF.LoadShaderStringAsync(e,t,i,s)}))}static LoadMaterialAsync(e,t,i,s){cF._ApplyExtensions((r=>r.loadMaterialAsync(e,t,i,s)),(()=>{lF.LoadMaterialAsync(e,t,i,s)}))}static _LoadTextureBufferAsync(e,t,i,s){cF._ApplyExtensions((r=>r.loadTextureBufferAsync(e,t,i,s)),(()=>{lF.LoadTextureBufferAsync(e,t,i,s)}))}static _CreateTextureAsync(e,t,i,s,r){cF._ApplyExtensions((n=>n.createTextureAsync(e,t,i,s,r)),(()=>{lF.CreateTextureAsync(e,t,i,s)}))}static _ApplyExtensions(e,t){for(const t in hF.Extensions)if(e(hF.Extensions[t]))return;t()}}function uF(e,t,i,s){return de.FromArray(t,i).scaleInPlace(s)}UN._CreateGLTF1Loader=()=>new hF,hF.RegisterExtension(new class extends cF{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!(!r||-1===r.indexOf(this.name)||!t.bin||(this._bin=t.bin,s(lF.CreateRuntime(t.json,e,i)),0))}loadBufferAsync(e,t,i,s){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>s(e.message))),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],o=e.bufferViews[n.bufferView];return i(GN.GetBufferFromBufferView(e,o,0,o.byteLength,ON.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],o=GN.GetBufferFromBufferView(e,n,0,n.byteLength,ON.UNSIGNED_BYTE);return setTimeout((()=>{const e=GN.DecodeBufferToText(o);i(e)})),!0}}),hF.RegisterExtension(new class extends cF{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const t in i){const s=i[t];switch(s.type){case"ambient":{const t=new cu(s.name,new de(0,1,0),e.scene),i=s.ambient;i&&(t.diffuse=Ce.FromArray(i.color||[1,1,1]));break}case"point":{const t=new ov(s.name,new de(10,10,10),e.scene),i=s.point;i&&(t.diffuse=Ce.FromArray(i.color||[1,1,1]));break}case"directional":{const t=new lm(s.name,new de(0,-1,0),e.scene),i=s.directional;i&&(t.diffuse=Ce.FromArray(i.color||[1,1,1]));break}case"spot":{const t=s.spot;t&&(new um(s.name,new de(0,10,0),new de(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene).diffuse=Ce.FromArray(t.color||[1,1,1]));break}default:hs.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const o=new yc(t,e.scene);return o.sideOrientation=uo.CounterClockWiseSideOrientation,"CONSTANT"===n.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==n.doubleSided&&!n.doubleSided,o.alpha=void 0===n.values.transparency?1:n.values.transparency,o.specularPower=void 0===n.values.shininess?0:n.values.shininess,"string"==typeof n.values.ambient?this._loadTexture(e,n.values.ambient,o,"ambientTexture",s):o.ambientColor=Ce.FromArray(n.values.ambient||[0,0,0]),"string"==typeof n.values.diffuse?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",s):o.diffuseColor=Ce.FromArray(n.values.diffuse||[0,0,0]),"string"==typeof n.values.emission?this._loadTexture(e,n.values.emission,o,"emissiveTexture",s):o.emissiveColor=Ce.FromArray(n.values.emission||[0,0,0]),"string"==typeof n.values.specular?this._loadTexture(e,n.values.specular,o,"specularTexture",s):o.specularColor=Ce.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){lF.LoadTextureBufferAsync(e,t,(r=>{lF.CreateTextureAsync(e,t,r,(e=>i[s]=e))}),r)}});class dF{constructor(e,t,i,s){this.type=e,this.name=t,this.getValue=i,this.getStride=s}_buildAnimation(e,t,i){const s=new Nt(e,this.name,t,this.type);return s.setKeys(i),s}}class _F extends dF{buildAnimations(e,t,i,s,r){r(e._babylonTransformNode,this._buildAnimation(t,i,s))}}const pF={translation:[new _F(Nt.ANIMATIONTYPE_VECTOR3,"position",uF,(()=>3))],rotation:[new _F(Nt.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,s){return pe.FromArray(t,i).scaleInPlace(s)}),(()=>4))],scale:[new _F(Nt.ANIMATIONTYPE_VECTOR3,"scaling",uF,(()=>3))],weights:[new class extends dF{buildAnimations(e,t,i,s,r){if(e._numMorphTargets)for(let n=0;n({frame:e.frame,inTangent:e.inTangent?e.inTangent[n]:void 0,value:e.value[n],outTangent:e.outTangent?e.outTangent[n]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(n),i=o.clone();e.animations.push(i),r(e,i)}}}}(Nt.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,s){const r=new Array(e._numMorphTargets);for(let e=0;ee._numMorphTargets))]};function fF(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((s=>{const r=e[s],n=i[s];Array.isArray(r)&&Array.isArray(n)?e[s]=r.concat(...n):t(r)&&t(n)?e[s]=fF(r,n):e[s]=n})),e)),{})}class mF{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,r,n,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let n=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);n=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(r,o,n,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,i,s,r=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,(()=>{})))))}_loadAsync(e,t,i,s){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${MN[MN.LOADING]} => ${MN[MN.READY]}`,n=`${MN[MN.LOADING]} => ${MN[MN.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(MN.LOADING),this._extensionsOnLoading();const o=new Array,a=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=mF.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e{})))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=a:this._babylonScene._forceBlockMaterialDirtyMechanism(a),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(MN.READY),this._startAnimations(),s()))).then((e=>(this._parent._endPerformanceCounter(r),hs.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(n),this._parent._setState(MN.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&we.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else we.Warn("Unexpected BIN chunk")}}_setupData(){if(mF.Assign(this._gltf.accessors),mF.Assign(this._gltf.animations),mF.Assign(this._gltf.buffers),mF.Assign(this._gltf.bufferViews),mF.Assign(this._gltf.cameras),mF.Assign(this._gltf.images),mF.Assign(this._gltf.materials),mF.Assign(this._gltf.meshes),mF.Assign(this._gltf.nodes),mF.Assign(this._gltf.samplers),mF.Assign(this._gltf.scenes),mF.Assign(this._gltf.skins),mF.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const i of t.children)e[i]=t.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=void 0===s?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in gF._RegisteredExtensions){const t=gF._RegisteredExtensions[e].factory(this);t.name!==e&&we.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired)if(!this._extensions.some((t=>t.name===e&&t.enabled)))throw new Error(`Required extension ${e} is not available`)}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new bo("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case RN.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],gF._LoadTransform(t,this._rootBabylonMesh));break;case RN.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=mF.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then((()=>{}))}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{const i=t.geometry;i&&-1===e.indexOf(i)&&e.push(i)}));return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof Sn&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&"TransformNode"===i._babylonTransformNode.getClassName()&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case IN.NONE:break;case IN.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case IN.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void we.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=(()=>{})){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=s=>{if(gF.AddPointerMetadata(s,e),gF._LoadTransform(t,s),null!=t.camera){const i=mF.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=s})))}if(t.children)for(const i of t.children){const t=mF.Get(`${e}/children/${i}`,this._gltf.nodes,i);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=s})))}i(s)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new xn(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,n(i)}if(null!=t.mesh)if(null==t.skin){const i=mF.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,n))}else{const i=mF.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const s=t._babylonTransformNodeForSkin;i.metadata=fF(s.metadata,i.metadata||{});const n=mF.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${n.index}`,t,n,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=n.skeleton){const e=mF.Get(`/skins/${n.index}/skeleton`,this._gltf.nodes,n.skeleton).parent;t.index===e.index?i.parent=s.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:s,skinnedNode:i})}))})))})))}return this.logClose(),Promise.all(r).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,s){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&mF.Assign(r);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===r.length){const s=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,o,t,i,s,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new xn(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const s of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,`${o}_primitive${s.index}`,t,i,s,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return s(t._babylonTransformNode),this.logClose(),Promise.all(n).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,s,r,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!s.primitives[0].targets;let l,h;if(a&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=r._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=r._instanceData.promise;else{const n=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new bo(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?uo.CounterClockWiseSideOrientation:uo.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,r,o),n.push(this._loadVertexDataAsync(e,r,o).then((t=>this._loadMorphTargetsAsync(e,r,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=gF._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=mF.Get(`${e}/material`,this._gltf.materials,r.material);n.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(n),a&&(r._instanceData={babylonSourceMesh:o,promise:h}),l=o}return gF.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),n(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new _n(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=mF.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{o.setIndices(e)})))}const a=(t,s,a)=>{if(null==r[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s);const l=mF.Get(`${e}/attributes/${t}`,this._gltf.accessors,r[t]);n.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,s).then((e=>{if(e.getKind()===ys.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=ge.Vector3[0].copyFromFloats(...l.min),t=ge.Vector3[1].copyFromFloats(...l.max);if(l.normalized&&5126!==l.componentType){let i=1;switch(l.componentType){case 5120:i=127;break;case 5121:i=255;break;case 5122:i=32767;break;case 5123:i=65535}const s=1/i;e.scaleInPlace(s),t.scaleInPlace(s)}o._boundingInfo=new rn(e,t),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(e,l.count)}))),s==ys.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),a&&a(l)};return a("POSITION",ys.PositionKind),a("NORMAL",ys.NormalKind),a("TANGENT",ys.TangentKind),a("TEXCOORD_0",ys.UVKind),a("TEXCOORD_1",ys.UV2Kind),a("TEXCOORD_2",ys.UV3Kind),a("TEXCOORD_3",ys.UV4Kind),a("TEXCOORD_4",ys.UV5Kind),a("TEXCOORD_5",ys.UV6Kind),a("JOINTS_0",ys.MatricesIndicesKind),a("WEIGHTS_0",ys.MatricesWeightsKind),a("JOINTS_1",ys.MatricesIndicesExtraKind),a("WEIGHTS_1",ys.MatricesWeightsExtraKind),a("COLOR_0",ys.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(n).then((()=>o))}_createMorphTargets(e,t,i,s,r){if(!s.targets)return;if(null==t._numMorphTargets)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new pv(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e{n.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,s){const r=new Array,n=(s,n,o)=>{if(null==i[s])return;const a=t.getVertexBuffer(n);if(!a)return;const l=mF.Get(`${e}/${s}`,this._gltf.accessors,i[s]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return n("POSITION",ys.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,s)=>{i[s]=t[s]+e})),s.setPositions(i)})),n("NORMAL",ys.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,s)=>{i[s]=t[s]+e})),s.setNormals(i)})),n("TANGENT",ys.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let r=0;e.forEach(t.length/3*4,((e,s)=>{(s+1)%4!=0&&(i[r]=t[r]+e,r++)})),s.setTangents(i)})),Promise.all(r).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=de.Zero(),s=pe.Identity(),r=de.One();e.matrix?fe.FromArray(e.matrix).decompose(r,s,i):(e.translation&&(i=de.FromArray(e.translation)),e.rotation&&(s=pe.FromArray(e.rotation)),e.scale&&(r=de.FromArray(e.scale))),t.position=i,t.rotationQuaternion=s,t.scaling=r}_loadSkinAsync(e,t,i,s){const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Ho(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},s(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const s=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=mF.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);r===i||s(r,i)||(we.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else we.Warn(`${e}: Failed to find common root`)}const s={};for(const r of t.joints){const n=mF.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,i,s)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const s of t){const t=[];let r=mF.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==r.index;)t.unshift(r),r=r.parent;i[s]=t}let s=null;for(let e=0;;++e){let r=i[t[0]];if(e>=r.length)return s;const n=r[e];for(let o=1;o=r.length||n!==r[e])return s;s=n}}_loadBone(e,t,i,s){let r=s[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?n=this._loadBone(e.parent,t,i,s):void 0!==t.skeleton&&we.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return r=new pr(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),s[e.index]=r,this._postSceneLoadActions.push((()=>{r.linkTransformNode(e._babylonTransformNode)})),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=mF.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const e=fe.Identity(),s=i._index;t&&-1!==s&&(fe.FromArrayToRef(t,16*s,e),e.invertToRef(e));const r=i.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?fe.FromArray(e.matrix):fe.Compose(e.scale?de.FromArray(e.scale):de.One(),e.rotation?pe.FromArray(e.rotation):pe.Identity(),e.translation?de.FromArray(e.translation):de.Zero())}loadCameraAsync(e,t,i=(()=>{})){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new xh(t.name||`camera${t.index}`,de.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=i.yfov,n.minZ=i.znear,n.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=Kr.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return gF.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(r).then((()=>n))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new kr(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const r=new Array;mF.Assign(t.channels),mF.Assign(t.samplers);for(const i of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),s.addTargetedAnimation(t,e)})));return Promise.all(r).then((()=>(s.normalize(0),s)))}_loadAnimationChannelAsync(e,t,i,s,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,s,r);if(n)return n;if(null==s.target.node)return Promise.resolve();const o=mF.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if("weights"===s.target.path&&!o._numMorphTargets||"weights"!==s.target.path&&!o._babylonTransformNode)return Promise.resolve();let a;switch(s.target.path){case"translation":a=pF.translation;break;case"rotation":a=pF.rotation;break;case"scale":a=pF.scale;break;case"weights":a=pF.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const l={object:o,info:a};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,l,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n){const o=this.parent.targetFps,a=1/o,l=mF.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,l).then((e=>{let t=0;const l=r.object,h=r.info;for(const r of h){const h=r.getStride(l),c=e.input,u=e.output,d=new Array(c.length);let _=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${s.index}_${t}`;r.buildAnimations(l,e,o,d,((e,i)=>{++t,n(e,i)}))}}}))}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=mF.Get(`${e}/input`,this._gltf.accessors,t.input),r=mF.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,s){const r=this._extensionsLoadBufferAsync(e,t,i,s);if(r)return r;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,s)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=mF.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const s=gF._GetNumComponents(e,t.type),r=s*ys.GetTypeByteLength(t.componentType),n=s*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(n));else{const o=mF.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==r){const e=new i(n);return ys.ForEach(a,t.byteOffset||0,o.byteStride||r,s,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return gF._GetTypedArray(e,t.componentType,a,t.byteOffset,n)}))}if(t.sparse){const n=t.sparse;t._data=t._data.then((o=>{const a=o,l=mF.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,n.indices.bufferView),h=mF.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,n.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=gF._GetTypedArray(`${e}/sparse/indices`,n.indices.componentType,o,n.indices.byteOffset,n.count),c=s*n.count;let u;if(5126!==t.componentType||t.normalized){const o=gF._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);u=new i(c),ys.ForEach(o,0,r,s,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=gF._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);let d=0;for(let e=0;egF._GetTypedArray(e,t.componentType,i,t.byteOffset,t.count)))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then((e=>new Ts(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){if(t._babylonVertexBuffer?.[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new ys(s,e,i,!1)));else{const r=mF.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(r).then((n=>{const o=gF._GetNumComponents(e,t.type);return new ys(s,n,i,!1,void 0,r.byteStride,void 0,t.byteOffset,o,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=Ce.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=Ce.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=e}))),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then((()=>{}))}_loadMaterialAsync(e,t,i,s,r=(()=>{})){const n=this._extensionsLoadMaterialAsync(e,t,i,s,r);if(n)return n;t._data=t._data||{};let o=t._data[s];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,s);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[s]=o,gF.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),r(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Um(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=Um.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?Ce.FromArray(t.emissiveFactor):new Ce(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${i.name} (Normal)`,i.bumpTexture=e}))),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${i.name} (Occlusion)`,i.ambientTexture=e}))),i.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(s).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=Um.PBRMATERIAL_OPAQUE,i.alpha=1;break;case"MASK":i.transparencyMode=Um.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=Um.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=(()=>{})){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=mF.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,(s=>{s.coordinatesIndex=t.texCoord||0,gF.AddPointerMetadata(s,e),this._parent.onTextureLoadedObservable.notifyObservers(s),i(s)}));return this.logClose(),n}_loadTextureAsync(e,t,i=(()=>{})){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=null==t.sampler?gF.DefaultSampler:mF.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=mF.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,r,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,s=(()=>{}),r,n){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new HP;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},c=new Vo(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,s=`data:${this._uniqueRootUrl}${t}`;c.updateURL(s,e)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,s(c),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:gF._GetTextureSamplingMode(e,t),wrapU:gF._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:gF._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=mF.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!gF._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(Zi(i)){const t=new Uint8Array(es(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((s,r)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),s(new Uint8Array(t)))}),!0,(t=>{r(new Gi(`${e}: Failed to load '${i}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return Vo.CLAMP_ADDRESSMODE;case 33648:return Vo.MIRROR_ADDRESSMODE;case 10497:return Vo.WRAP_ADDRESSMODE;default:return we.Warn(`${e}: Invalid value (${t})`),Vo.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,s=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(s){case 9728:return Vo.LINEAR_NEAREST;case 9729:return Vo.LINEAR_LINEAR;case 9984:return Vo.LINEAR_NEAREST_MIPNEAREST;case 9985:return Vo.LINEAR_LINEAR_MIPNEAREST;case 9986:return Vo.LINEAR_NEAREST_MIPLINEAR;case 9987:return Vo.LINEAR_LINEAR_MIPLINEAR;default:return we.Warn(`${e}/minFilter: Invalid value (${s})`),Vo.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&we.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return Vo.NEAREST_NEAREST;case 9729:return Vo.NEAREST_LINEAR;case 9984:return Vo.NEAREST_NEAREST_MIPNEAREST;case 9985:return Vo.NEAREST_LINEAR_MIPNEAREST;case 9986:return Vo.NEAREST_NEAREST_MIPLINEAR;case 9987:return Vo.NEAREST_LINEAR_MIPLINEAR;default:return we.Warn(`${e}/minFilter: Invalid value (${s})`),Vo.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,r){const n=i.buffer;s=i.byteOffset+(s||0);const o=gF._GetTypedArrayConstructor(`${e}/componentType`,t),a=ys.GetTypeByteLength(t);return s%a!=0?(we.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${a})`),new o(n.slice(s,s+r*a),0)):new o(n,s,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return hs.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return uo.PointListDrawMode;case 1:return uo.LineListDrawMode;case 2:return uo.LineLoopDrawMode;case 3:return uo.LineStripDrawMode;case 4:return uo.TriangleFillMode;case 5:return uo.TriangleStripDrawMode;case 6:return uo.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const s=t._data[i];for(const t of s.babylonMeshes){t.computeWorldMatrix(!0);const i=s.babylonMaterial;e.push(i.forceCompilationAsync(t)),e.push(i.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(i.forceCompilationAsync(t,{clipPlane:!0})),e.push(i.forceCompilationAsync(t,{clipPlane:!0,useInstances:!0})))}}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile materials")}))}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const t=i.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile shadow generators")}))}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const s of this._extensions)if(s.enabled){const r=`${s.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[r]){o[r]=!0;try{const e=i(s);if(e)return e}finally{delete o[r]}}}return null}_extensionsOnLoading(){this._forEachExtensions((e=>e.onLoading&&e.onLoading()))}_extensionsOnReady(){this._forEachExtensions((e=>e.onReady&&e.onReady()))}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n){return this._applyExtensions(r,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,s,r,n)))}_extensionsLoadMaterialAsync(e,t,i,s,r){return this._applyExtensions(t,"loadMaterial",(n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,s,r)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(s=>s.createMaterial&&s.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,s,r){return this._applyExtensions(i,"loadAnimationChannel",(n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,s,r)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(s=>s._loadUriAsync&&s._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",(r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,s)))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const r=t.extensions[i];return r?s(`${e}/extensions/${i}`,r):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const r=t.extras[i];return r?s(`${e}/extras/${i}`,r):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}gF._RegisteredExtensions={},gF.DefaultSampler={index:-1},UN._CreateGLTF2Loader=e=>new gF(e);const vF="EXT_lights_image_based";class xF{constructor(e){this.name=vF,this._loader=e,this.enabled=this._loader.isExtensionUsed(vF)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return gF.LoadExtensionAsync(e,t,this.name,((i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=mF.Get(`${i}/light`,this._lights,s.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,n).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(r).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let r=0;r{s[r][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new Mx(this._loader.babylonScene,null,t.specularImageSize);if(i.name=t.name||"environment",t._babylonTexture=i,null!=t.intensity&&(i.level=t.intensity),t.rotation){let e=pe.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=pe.Inverse(e)),fe.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=a_.FromArray(t.irradianceCoefficients);r.scaleInPlace(t.intensity),r.convertIrradianceToLambertianRadiance();const n=l_.FromHarmonics(r),o=(s.length-1)/xe.Log2(t.specularImageSize);return i.updateRGBDAsync(s,n,o)}))}return t._loaded.then((()=>t._babylonTexture))}}gF.RegisterExtension(vF,(e=>new xF(e)));const bF="EXT_mesh_gpu_instancing";class TF{constructor(e){this.name=bF,this._loader=e,this.enabled=this._loader.isExtensionUsed(bF)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((e,s)=>{this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return r;const n=new Array;let o=0;const a=t=>{if(null==s.attributes[t])return void n.push(Promise.resolve(null));const i=mF.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,s.attributes[t]);if(n.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===o)o=i.count;else if(o!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return a("TRANSLATION"),a("ROTATION"),a("SCALE"),r.then((e=>Promise.all(n).then((([i,s,r])=>{const n=new Float32Array(16*o);ge.Vector3[0].copyFromFloats(0,0,0),ge.Quaternion[0].copyFromFloats(0,0,0,1),ge.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew TF(e)));const yF="EXT_meshopt_compression";class SF{constructor(e){this.name=yF,this.enabled=e.isExtensionUsed(yF),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return gF.LoadExtensionAsync(e,t,this.name,((i,s)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=mF.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,s.byteOffset||0,s.byteLength).then((e=>ty.Default.decodeGltfBufferAsync(e,s.count,s.byteStride,s.mode,s.filter))),r._meshOptData}))}}gF.RegisterExtension(yF,(e=>new SF(e)));const CF="EXT_texture_webp";class EF{constructor(e){this.name=CF,this._loader=e,this.enabled=e.isExtensionUsed(CF)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?gF.DefaultSampler:mF.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mF.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}gF.RegisterExtension(CF,(e=>new EF(e)));const AF="EXT_texture_avif";class PF{constructor(e){this.name=AF,this._loader=e,this.enabled=e.isExtensionUsed(AF)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?gF.DefaultSampler:mF.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mF.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}gF.RegisterExtension(AF,(e=>new PF(e)));const RF="KHR_draco_mesh_compression";class IF{constructor(e){this.name=RF,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=ey.DecoderAvailable&&this._loader.isExtensionUsed(RF)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},a=(e,s)=>{const a=r.attributes[e];if(null!=a&&(i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s),n[s]=a,this.useNormalizedFlagFromAccessor)){const i=mF.TryGet(this._loader.gltf.accessors,t.attributes[e]);i&&(o[s]=i.normalized||!1)}};a("POSITION",ys.PositionKind),a("NORMAL",ys.NormalKind),a("TANGENT",ys.TangentKind),a("TEXCOORD_0",ys.UVKind),a("TEXCOORD_1",ys.UV2Kind),a("TEXCOORD_2",ys.UV3Kind),a("TEXCOORD_3",ys.UV4Kind),a("TEXCOORD_4",ys.UV5Kind),a("TEXCOORD_5",ys.UV6Kind),a("JOINTS_0",ys.MatricesIndicesKind),a("WEIGHTS_0",ys.MatricesWeightsKind),a("COLOR_0",ys.ColorKind);const l=mF.Get(s,this._loader.gltf.bufferViews,r.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||ey.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,t,n,o).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}gF.RegisterExtension(RF,(e=>new IF(e)));const MF="KHR_lights_punctual";class OF{constructor(e){this.name=MF,this._loader=e,this.enabled=this._loader.isExtensionUsed(MF)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,mF.Assign(this._lights)}}loadNodeAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const n=mF.Get(s,this._lights,r.light),o=n.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,n.type){case"directional":{const e=new lm(o,de.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new ov(o,de.Zero(),this._loader.babylonScene);break;case"spot":{const e=new um(o,de.Zero(),de.Backward(),0,1,this._loader.babylonScene);e.angle=2*(n.spot&&n.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(n.spot&&n.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${n.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,n._babylonLight=t,t.falloffType=yo.FALLOFF_GLTF,t.diffuse=n.color?Ce.FromArray(n.color):Ce.White(),t.intensity=null==n.intensity?1:n.intensity,t.range=null==n.range?Number.MAX_VALUE:n.range,t.parent=e,this._loader._babylonLights.push(t),gF.AddPointerMetadata(t,s),i(e)})))))}}gF.RegisterExtension(MF,(e=>new OF(e)));const DF="KHR_materials_pbrSpecularGlossiness";class wF{constructor(e){this.name=DF,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(DF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(s,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=Ce.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=Ce.White(),i.reflectivityColor=t.specularFactor?Ce.FromArray(t.specularFactor):Ce.White(),i.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${i.name} (Diffuse)`,i.albedoTexture=e}))),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,(e=>{e.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=e,i.reflectivityTexture.hasAlpha=!0}))),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(DF,(e=>new wF(e)));const NF="KHR_materials_unlit";class FF{constructor(e){this.name=NF,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(NF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=Ce.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=Ce.White(),r.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(NF,(e=>new FF(e)));const BF="KHR_materials_clearcoat";class LF{constructor(e){this.name=BF,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(BF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=e}))),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(BF,(e=>new LF(e)));const kF="KHR_materials_iridescence";class VF{constructor(e){this.name=kF,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(kF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(kF,(e=>new VF(e)));const UF="KHR_materials_anisotropy";class GF{constructor(e){this.name=UF,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(UF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e}))),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(UF,(e=>new GF(e)));const zF="KHR_materials_emissive_strength";class WF{constructor(e){this.name=zF,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(zF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(s,r,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(i.emissiveIntensity=t.emissiveStrength)}}gF.RegisterExtension(zF,(e=>new WF(e)));const HF="KHR_materials_sheen";class XF{constructor(e){this.name=HF,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(HF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=Ce.FromArray(t.sheenColorFactor):i.sheen.color=Ce.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${i.name} (Sheen Color)`,i.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=e})))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then((()=>{}))}}gF.RegisterExtension(HF,(e=>new XF(e)));const YF="KHR_materials_specular";class QF{constructor(e){this.name=YF,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(YF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const s=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=Ce.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=e}))),Promise.all(s).then((()=>{}))}}gF.RegisterExtension(YF,(e=>new QF(e)));const jF="KHR_materials_ior";class KF{constructor(e){this.name=jF,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(jF)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=KF._DEFAULT_IOR,Promise.resolve()}}KF._DEFAULT_IOR=1.5,gF.RegisterExtension(jF,(e=>new KF(e)));const $F="KHR_materials_variants";class qF{constructor(e){this.name=$F,this._loader=e,this.enabled=this._loader.isExtensionUsed($F)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return qF.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${$F} extension`);const s=e=>{const t=i.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)s(e);else s(t);i.lastSelected=t}selectVariant(e,t){qF.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${$F} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){qF.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${$F} extension`);return t.lastSelected}getLastSelectedVariant(e){return qF.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[$F]||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,r,n){return gF.LoadExtensionAsync(e,r,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,r,(t=>{if(n(t),t instanceof bo){const i=gF._GetDrawMode(e,r.mode),s=this._loader.rootBabylonMesh,n=s?s._internalMetadata=s._internalMetadata||{}:{},h=n.gltf=n.gltf||{},c=h[$F]=h[$F]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let r=null,n=i;do{if(n=n.parent,!n)return;r=qF._GetExtensionMetadata(n)}while(null===r);if(s&&r===qF._GetExtensionMetadata(s)){n._internalMetadata={};for(const e in s._internalMetadata)n._internalMetadata[e]=s._internalMetadata[e];n._internalMetadata.gltf=[];for(const e in s._internalMetadata.gltf)n._internalMetadata.gltf[e]=s._internalMetadata.gltf[e];n._internalMetadata.gltf[$F]={lastSelected:null,original:[],variants:{}};for(const e of r.original)n._internalMetadata.gltf[$F].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){n._internalMetadata.gltf[$F].variants[e]=[];for(const t of r.variants[e])n._internalMetadata.gltf[$F].variants[e].push({mesh:t.mesh,material:t.material})}r=n._internalMetadata.gltf[$F]}for(const e of r.original)e.mesh===t&&(e.mesh=i);for(const e of r.variants[o.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}gF.RegisterExtension($F,(e=>new qF(e)));class ZF{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Yd.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...ZF._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new X,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},i=this._options;this._options=t,t.renderSize===i.renderSize&&t.renderTargetTextureType===i.renderTargetTextureType&&t.generateMipmaps===i.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof Um&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),hs.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e)):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e)}))}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof Um&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==i?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===i&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){return null!==this._opaqueRenderTarget?.getInternalTexture()}_setupRenderTargets(){let e,t;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new pl("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=this._options.clearColor?.clone()??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0,this._opaqueRenderTarget.onBeforeBindObservable.add((i=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?i.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(i.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e})),this._transparentMeshesCache.forEach((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const JF="KHR_materials_transmission";class eB{constructor(e){this.name=JF,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(JF),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,s){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,void 0===s.transmissionFactor)return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();{r.subSurface.refractionIntensity=s.transmissionFactor;const e=r.getScene();r.subSurface.refractionIntensity&&!e._transmissionHelper?new ZF({},r.getScene()):r.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then((e=>{r.subSurface.refractionIntensityTexture=e,r.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}gF.RegisterExtension(JF,(e=>new eB(e)));const tB="KHR_materials_translucency";class iB{constructor(e){this.name=tB,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(tB),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);const r=i;return r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!0,void 0===s.translucencyFactor?(r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve()):(r.subSurface.translucencyIntensity=s.translucencyFactor,s.translucencyTexture?(s.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/translucencyTexture`,s.translucencyTexture).then((e=>{r.subSurface.translucencyIntensityTexture=e}))):Promise.resolve())}}gF.RegisterExtension(tB,(e=>new iB(e)));const sB="KHR_materials_volume";class rB{constructor(e){this.name=sB,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(sB),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=void 0!==s.attenuationDistance?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,void 0!==s.attenuationColor&&3==s.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then((e=>{i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}gF.RegisterExtension(sB,(e=>new rB(e)));const nB="KHR_materials_dispersion";class oB{constructor(e){this.name=nB,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(nB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof Um))throw new Error(`${e}: Material type not supported`);return i.subSurface.isRefractionEnabled&&s.dispersion?(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion,Promise.resolve()):Promise.resolve()}}gF.RegisterExtension(nB,(e=>new oB(e)));const aB="KHR_mesh_quantization";class lB{constructor(e){this.name=aB,this.enabled=e.isExtensionUsed(aB)}dispose(){}}gF.RegisterExtension(aB,(e=>new lB(e)));const hB="KHR_texture_basisu";class cB{constructor(e){this.name=hB,this._loader=e,this.enabled=e.isExtensionUsed(hB)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?gF.DefaultSampler:mF.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mF.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}gF.RegisterExtension(hB,(e=>new cB(e)));const uB="KHR_texture_transform";class dB{constructor(e){this.name=uB,this._loader=e,this.enabled=this._loader.isExtensionUsed(uB)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((s,r)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Vo))throw new Error(`${s}: Texture type not supported`);r.offset&&(e.uOffset=r.offset[0],e.vOffset=r.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,r.rotation&&(e.wAng=-r.rotation),r.scale&&(e.uScale=r.scale[0],e.vScale=r.scale[1]),null!=r.texCoord&&(e.coordinatesIndex=r.texCoord),i(e)}))))}}gF.RegisterExtension(uB,(e=>new dB(e)));const _B="KHR_xmp_json_ld";class pB{constructor(e){this.name=_B,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(_B)}dispose(){this._loader=null}onLoading(){if(null===this._loader.rootBabylonMesh)return;const e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){const i=+t.packet;e.packets&&i2)),new yB(Nt.ANIMATIONTYPE_FLOAT,`${e}.vScale`,vB,(()=>2))],offset:[new yB(Nt.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,mB,(()=>2)),new yB(Nt.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,vB,(()=>2))],rotation:[new yB(Nt.ANIMATIONTYPE_FLOAT,`${e}.wAng`,gB,(()=>1))]}}gF.RegisterExtension(_B,(e=>new pB(e)));class TB extends dF{buildAnimations(e,t,i,s,r){r(e._babylonCamera,this._buildAnimation(t,i,s))}}class yB extends dF{buildAnimations(e,t,i,s,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,i,s))}}class SB extends dF{buildAnimations(e,t,i,s,r){r(e._babylonLight,this._buildAnimation(t,i,s))}}const CB={__array__:{__target__:!0,...pF}},EB={__array__:{__target__:!0,orthographic:{xmag:[new TB(Nt.ANIMATIONTYPE_FLOAT,"orthoLeft",gB,(()=>1)),new TB(Nt.ANIMATIONTYPE_FLOAT,"orthoRight",vB,(()=>1))],ymag:[new TB(Nt.ANIMATIONTYPE_FLOAT,"orthoBottom",gB,(()=>1)),new TB(Nt.ANIMATIONTYPE_FLOAT,"orthoTop",vB,(()=>1))],zfar:[new TB(Nt.ANIMATIONTYPE_FLOAT,"maxZ",mB,(()=>1))],znear:[new TB(Nt.ANIMATIONTYPE_FLOAT,"minZ",mB,(()=>1))]},perspective:{yfov:[new TB(Nt.ANIMATIONTYPE_FLOAT,"fov",mB,(()=>1))],zfar:[new TB(Nt.ANIMATIONTYPE_FLOAT,"maxZ",mB,(()=>1))],znear:[new TB(Nt.ANIMATIONTYPE_FLOAT,"minZ",mB,(()=>1))]}}},AB={nodes:CB,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"albedoColor",fB,(()=>4)),new yB(Nt.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,s){return t[i+3]*s}),(()=>4))],metallicFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"metallic",mB,(()=>1))],roughnessFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"roughness",mB,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:bB("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:bB("metallicTexture")}}},emissiveFactor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"emissiveColor",fB,(()=>3))],normalTexture:{scale:[new yB(Nt.ANIMATIONTYPE_FLOAT,"bumpTexture.level",mB,(()=>1))],extensions:{KHR_texture_transform:bB("bumpTexture")}},occlusionTexture:{strength:[new yB(Nt.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",mB,(()=>1))],extensions:{KHR_texture_transform:bB("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:bB("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new yB(Nt.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",mB,(()=>1))],anisotropyRotation:[new yB(Nt.ANIMATIONTYPE_FLOAT,"anisotropy.angle",mB,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:bB("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",mB,(()=>1))],clearcoatRoughnessFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",mB,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:bB("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new yB(Nt.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",mB,(()=>1))],extensions:{KHR_texture_transform:bB("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:bB("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new yB(Nt.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",mB,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new yB(Nt.ANIMATIONTYPE_FLOAT,"emissiveIntensity",mB,(()=>1))]},KHR_materials_ior:{ior:[new yB(Nt.ANIMATIONTYPE_FLOAT,"indexOfRefraction",mB,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"iridescence.intensity",mB,(()=>1))],iridescenceIor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",mB,(()=>1))],iridescenceThicknessMinimum:[new yB(Nt.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",mB,(()=>1))],iridescenceThicknessMaximum:[new yB(Nt.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",mB,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:bB("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:bB("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"sheen.color",fB,(()=>3))],sheenRoughnessFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"sheen.roughness",mB,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:bB("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:bB("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"metallicF0Factor",mB,(()=>1))],specularColorFactor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",fB,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:bB("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:bB("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",mB,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:bB("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new yB(Nt.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",fB,(()=>3))],attenuationDistance:[new yB(Nt.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",mB,(()=>1))],thicknessFactor:[new yB(Nt.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",mB,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:bB("subSurface.thicknessTexture")}}}}}},cameras:EB,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new SB(Nt.ANIMATIONTYPE_COLOR3,"diffuse",fB,(()=>3))],intensity:[new SB(Nt.ANIMATIONTYPE_FLOAT,"intensity",mB,(()=>1))],range:[new SB(Nt.ANIMATIONTYPE_FLOAT,"range",mB,(()=>1))],spot:{innerConeAngle:[new SB(Nt.ANIMATIONTYPE_FLOAT,"innerAngle",xB,(()=>1))],outerConeAngle:[new SB(Nt.ANIMATIONTYPE_FLOAT,"angle",xB,(()=>1))]}}}}}};class PB{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,i=this._gltf,s=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(s.__array__)s=s.__array__;else if(s=s[n],!s)throw new Error(`Path ${e} is invalid`);if(void 0===i)throw new Error(`Path ${e} is invalid`);i=i[n],s.__target__&&(t=i)}return{object:t,info:s}}}const RB="KHR_animation_pointer";class IB extends PB{constructor(e){super(e,AB)}}class MB{constructor(e){this.name=RB,this._loader=e,this._pathToObjectConverter=new IB(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(RB)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,r){const n=s.target.extensions?.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;"pointer"!==s.target.path&&we.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),null!=s.target.node&&we.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,a=n.pointer;if(!a)throw new Error(`${o}: Pointer is missing`);try{const n=this._pathToObjectConverter.convert(a);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,n,r)}catch(e){return we.Warn(`${o}/pointer: Invalid pointer (${a}) skipped`),null}}}gF.RegisterExtension(RB,(e=>new MB(e)));const OB="MSFT_audio_emitter";class DB{constructor(e){this.name=OB,this._loader=e,this.enabled=this._loader.isExtensionUsed(OB)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,mF.Assign(this._clips),mF.Assign(this._emitters)}}loadSceneAsync(e,t){return gF.LoadExtensionAsync(e,t,this.name,((i,s)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const e of s.emitters){const t=mF.Get(`${i}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(r).then((()=>{}))}))}loadNodeAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((e,s)=>{const r=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of s.emitters){const s=mF.Get(`${e}/emitters`,this._emitters,i);r.push(this._loadEmitterAsync(`${e}/emitters/${s.index}`,s).then((()=>{for(const e of s._babylonSounds)e.attachToMesh(t),null==s.innerAngle&&null==s.outerAngle||(e.setLocalDirectionToMesh(de.Forward()),e.setDirectionalCone(2*hs.ToDegrees(null==s.innerAngle?Math.PI:s.innerAngle),2*hs.ToDegrees(null==s.outerAngle?Math.PI:s.outerAngle),0))})))}i(t)})).then((e=>Promise.all(r).then((()=>e))))}))}loadAnimationAsync(e,t){return gF.LoadExtensionAsync(e,t,this.name,((i,s)=>this._loader.loadAnimationAsync(e,t).then((r=>{const n=new Array;mF.Assign(s.events);for(const o of s.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,r));return Promise.all(n).then((()=>r))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=mF.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,i=t.name||`emitter${t.index}`,s={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let r=0;r{const n=t._babylonSounds[r]=new Ro(i,e,this._loader.babylonScene,null,s);n.refDistance=t.refDistance||1,n.maxDistance=t.maxDistance||256,n.rolloffFactor=t.rolloffFactor||1,n.distanceModel=t.distanceModel||"exponential"})))}const r=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new Oo(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*hs.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*hs.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:r}}return t._babylonData.loaded}_getEventAction(e,t,i,s,r){switch(i){case"play":return e=>{const i=(r||0)+(e-s);t.play(i)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,r){if(0==r.targetedAnimations.length)return Promise.resolve();const n=r.targetedAnimations[0],o=s.emitter,a=mF.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new Br(s.time,this._getEventAction(e,t,s.action,s.time,s.startOffset));n.animation.addEvent(i),r.onAnimationGroupEndObservable.add((()=>{t.stop()})),r.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}gF.RegisterExtension(OB,(e=>new DB(e)));const wB="MSFT_lod";class NB{constructor(e){this.name=wB,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new X,this.onMaterialLODsLoadedObservable=new X,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(wB)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}for(let e=0;e{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return gF.LoadExtensionAsync(e,t,this.name,((e,s)=>{let r;const n=this._getLODs(e,t,this._loader.gltf.nodes,s.ids);this._loader.logOpen(`${e}`);for(let e=0;e{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,s).then((t=>{if(0!==e){const t=n[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t}));this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?r=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(o))}return this._loader.logClose(),r}))}_loadMaterialAsync(e,t,i,s,r){return this._nodeIndexLOD?null:gF.LoadExtensionAsync(e,t,this.name,((e,n)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e{0===e&&r(t)})).then((t=>{if(0!==e){r(t);const i=a[e-1]._data;i[s]&&(this._disposeMaterials([i[s].babylonMaterial]),delete i[s])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?o=n:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(n))}return this._loader.logClose(),o}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new HP,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new HP,this._materialSignalLODs[s].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const t=(e,t)=>{const r=i,n=r+s-1;let o=e[t];return o?(o.start=Math.min(o.start,r),o.end=Math.max(o.end,n)):(o={start:r,end:n,loaded:new HP},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.start,s)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then((e=>{i.loaded.resolve(e)}),(e=>{i.loaded.reject(e)})))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let t=s.length-1;t>=0;t--)if(r.push(mF.Get(`${e}/ids/${s[t]}`,i,s[t])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.material);e.dispose();const s=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const i of e){for(const e of i.getActiveTextures())t[e.uniqueId]=e;i.dispose()}for(const e in t)for(const i of this._loader.babylonScene.materials)i.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}gF.RegisterExtension(wB,(e=>new NB(e)));const FB="MSFT_minecraftMesh";class BB{constructor(e){this.name=FB,this._loader=e,this.enabled=this._loader.isExtensionUsed(FB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtraAsync(e,t,this.name,((s,r)=>{if(r){if(!(i instanceof Um))throw new Error(`${s}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,r}return null}))}}gF.RegisterExtension(FB,(e=>new BB(e)));const LB="MSFT_sRGBFactors";class kB{constructor(e){this.name=LB,this._loader=e,this.enabled=this._loader.isExtensionUsed(LB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return gF.LoadExtraAsync(e,t,this.name,((s,r)=>{if(r){if(!(i instanceof Um))throw new Error(`${s}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i),n=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,n),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,n),r}return null}))}}gF.RegisterExtension(LB,(e=>new kB(e)));const VB={"lifecycle/onStart":CD.ClassName,"lifecycle/onTick":AD.ClassName,log:uM.ClassName,"flow/delay":TM.ClassName,"customEvent/send":mM.ClassName,"customEvent/receive":ED.ClassName,"flow/sequence":IM.ClassName,"world/get":LM.ClassName,"world/set":fM.ClassName,"flow/doN":vM.ClassName,"variable/get":NM.ClassName,"variable/set":dM.ClassName,"flow/whileLoop":AM.ClassName,"math/random":oO.ClassName,"math/e":lO.ClassName,"math/pi":hO.ClassName,"math/inf":cO.ClassName,"math/nan":uO.ClassName,"math/abs":_O.ClassName,"math/sign":pO.ClassName,"math/trunc":fO.ClassName,"math/floor":mO.ClassName,"math/ceil":gO.ClassName,"math/fract":vO.ClassName,"math/neg":xO.ClassName,"math/add":iO.ClassName,"math/sub":sO.ClassName,"math/mul":rO.ClassName,"math/div":nO.ClassName,"math/rem":TO.ClassName,"math/min":yO.ClassName,"math/max":SO.ClassName,"math/clamp":AO.ClassName,"math/saturate":RO.ClassName,"math/mix":IO.ClassName,"math/eq":MO.ClassName,"math/lt":DO.ClassName,"math/le":wO.ClassName,"math/gt":NO.ClassName,"math/ge":FO.ClassName,"math/isnan":BO.ClassName,"math/isinf":LO.ClassName,"math/rad":kO.ClassName,"math/deg":VO.ClassName,"math/sin":UO.ClassName,"math/cos":GO.ClassName,"math/tan":zO.ClassName,"math/asin":WO.ClassName,"math/acos":HO.ClassName,"math/atan":XO.ClassName,"math/atan2":YO.ClassName,"math/sinh":QO.ClassName,"math/cosh":jO.ClassName,"math/tanh":KO.ClassName,"math/asinh":$O.ClassName,"math/acosh":qO.ClassName,"math/atanh":ZO.ClassName,"math/exp":JO.ClassName,"math/log":eD.ClassName,"math/log2":tD.ClassName,"math/log10":iD.ClassName,"math/sqrt":sD.ClassName,"math/cbrt":rD.ClassName,"math/pow":nD.ClassName,"math/length":oD.ClassName,"math/normalize":aD.ClassName,"math/dot":aO.ClassName,"math/cross":lD.ClassName,"math/rotate2d":hD.ClassName,"math/rotate3d":cD.ClassName,"math/transpose":uD.ClassName,"math/determinant":dD.ClassName,"math/inverse":_D.ClassName,"math/matmul":pD.ClassName,"math/not":fD.ClassName,"math/and":mD.ClassName,"math/or":gD.ClassName,"math/xor":vD.ClassName,"math/asr":bD.ClassName,"math/lsl":xD.ClassName,"math/clz":TD.ClassName,"math/ctz":yD.ClassName,"math/popcnt":SD.ClassName},UB={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function GB(e,t,i){if(void 0!==e.type){const s=t.types&&t.types[e.type];if(!s)throw new Error(`${i}: Unknown type: ${e.type}`);const r=s.signature;if(!r)throw new Error(`${i}: Type ${e.type} has no signature`);const n=UB[r];return{value:e.value,className:n}}return e.value}function zB(e,t,i){const s=VB[t.type];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const r=e.toString(),n=function(e,t,i){const s={},r=e.configuration??[];for(const e of r)if("customEvent"===e.id){const r=t.customEvents&&t.customEvents[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown custom event: ${e.value}`);s.eventId=r.id,s.eventData=r.values.map((e=>e.id))}else if("variable"===e.id){const r=t.variables&&t.variables[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown variable: ${e.value}`);s.variableName=r.id}else if("path"===e.id){const t=e.value;s.path=t}else s[e.id]=GB(e,t,`/extensions/KHR_interactivity/nodes/${i}`);return s}(t,i,r);return{className:s,config:n,uniqueId:r,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class WB extends PB{constructor(e){super(e,HB)}}const HB={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},XB="KHR_interactivity";class YB{constructor(e){this._loader=e,this.name=XB,this.enabled=this._loader.isExtensionUsed(XB),this._pathConverter=new WB(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=this._loader.gltf.extensions?.KHR_interactivity,i=function(e){const t={uniqueId:ns(),_userVariables:{},_connectionValues:{}},i=[t],s=[];for(let t=0;te.name===a));h||(h={uniqueId:ns(),name:a,_connectionType:MI.Input,connectedPointIds:[]},l.signalInputs.push(h)),h.connectedPointIds.push(r.uniqueId),r.connectedPointIds.push(h.uniqueId)}const a=r.values??[];for(const r of a){const o=r.id,a={uniqueId:ns(),name:o,_connectionType:MI.Input,connectedPointIds:[]};if(n.dataInputs.push(a),void 0!==r.value){const s=GB(r,e,`/extensions/KHR_interactivity/nodes/${i}`);t._connectionValues[a.uniqueId]=s}else{if(void 0===r.node||void 0===r.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Invalid socket ${o} in node ${i}`);{const e=r.node,t=r.socket,n=s[e];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${e} that connects its output with node${i}'s input ${o}`);let l=n.dataOutputs.find((e=>e.name===t));l||(l={uniqueId:ns(),name:t,_connectionType:MI.Output,connectedPointIds:[]},n.dataOutputs.push(l)),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}}}}const r=e.variables??[];for(let i=0;inew YB(e)));const QB="ExtrasAsMetadata";class jB{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{};(i.gltf=i.gltf||{}).extras=t.extras}}constructor(e){this.name=QB,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}gF.RegisterExtension(QB,(e=>new jB(e)));class KB{constructor(){this.materials=[]}parseMTL(e,t,i,s){if(t instanceof ArrayBuffer)return;const r=t.split("\n"),n=/\s+/;let o,a=null;for(let t=0;t=0?l.substring(0,h):l;c=c.toLowerCase();const u=h>=0?l.substring(h+1).trim():"";if("newmtl"===c)a&&this.materials.push(a),e._blockEntityCollection=!!s,a=new yc(u,e),a._parentContainer=s,e._blockEntityCollection=!1;else if("kd"===c&&a)o=u.split(n,3).map(parseFloat),a.diffuseColor=Ce.FromArray(o);else if("ka"===c&&a)o=u.split(n,3).map(parseFloat),a.ambientColor=Ce.FromArray(o);else if("ks"===c&&a)o=u.split(n,3).map(parseFloat),a.specularColor=Ce.FromArray(o);else if("ke"===c&&a)o=u.split(n,3).map(parseFloat),a.emissiveColor=Ce.FromArray(o);else if("ns"===c&&a)a.specularPower=parseFloat(u);else if("d"===c&&a)a.alpha=parseFloat(u);else if("map_ka"===c&&a)a.ambientTexture=KB._GetTexture(i,u,e);else if("map_kd"===c&&a)a.diffuseTexture=KB._GetTexture(i,u,e);else if("map_ks"===c&&a)a.specularTexture=KB._GetTexture(i,u,e);else if("map_ns"===c);else if("map_bump"===c&&a){const t=u.split(n),s=t.indexOf("-bm");let r=null;s>=0&&(r=t[s+1],t.splice(s,2)),a.bumpTexture=KB._GetTexture(i,t.join(" "),e),a.bumpTexture&&null!==r&&(a.bumpTexture.level=parseFloat(r))}else"map_d"===c&&a&&(a.opacityTexture=KB._GetTexture(i,u,e))}a&&this.materials.push(a)}static _GetTexture(e,t,i){if(!t)return null;let s=e;if("file:"===e){let e=t.lastIndexOf("\\");-1===e&&(e=t.lastIndexOf("/")),s+=e>-1?t.substr(e+1):t}else s+=t;return new Vo(s,i,!1,KB.INVERT_TEXTURE_Y)}}KB.INVERT_TEXTURE_Y=!0;class $B{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new Ee(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return-1===i?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return 1!=i&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,s,r,n,o){let a;a=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e,i,t]):this._isInArray(this._tuplePosNorm,[e,i]),-1===a?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(r),this._wrappedNormalsForBabylon.push(n),void 0!==o&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(a)}_unwrapData(){for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(ys.PositionKind),i=e.getVerticesData(ys.NormalKind),s={};if(!t||!i)return;for(let e=0;ethis._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t+1],e[t]),this._handednessSign=1):(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=-1);const n=t.split("\n");for(let e=0;e=7){const e=parseFloat(i[4]),t=parseFloat(i[5]),s=parseFloat(i[6]);this._colors.push(new Ee(e>1?e/255:e,t>1?t/255:t,s>1?s/255:s,7===i.length||void 0===i[7]?1:parseFloat(i[7])))}else this._colors.push(this._grayColor)}else if(null!==(i=$B.NormalPattern.exec(t)))this._normals.push(new de(parseFloat(i[1]),parseFloat(i[2]),parseFloat(i[3])));else if(null!==(i=$B.UVPattern.exec(t)))this._uvs.push(new ue(parseFloat(i[1])*this._loadingOptions.UVScaling.x,parseFloat(i[2])*this._loadingOptions.UVScaling.y));else if(null!==(i=$B.FacePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),1);else if(null!==(i=$B.FacePattern4.exec(t)))this._setDataForCurrentFaceWithPattern4(i[1].trim().split(" "),1);else if(null!==(i=$B.FacePattern5.exec(t)))this._setDataForCurrentFaceWithPattern5(i[1].trim().split(" "),1);else if(null!==(i=$B.FacePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),1);else if(null!==(i=$B.FacePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),1);else if(null!==(i=$B.LinePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),0);else if(null!==(i=$B.LinePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),0);else if(null!==(i=$B.LinePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),0);else if($B.GroupDescriptor.test(t)||$B.ObjectDescriptor.test(t)){const e={name:t.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:$B.ObjectDescriptor.test(t)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if($B.UseMtlDescriptor.test(t)){if(this._materialNameFromObj=t.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const e={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(e),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else $B.MtlLibGroupDescriptor.test(t)?r(t.substring(7).trim()):$B.SmoothDescriptor.test(t)||we.Log("Unhandled expression at line : "+t)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let e=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new yc(_n.RandomId(),i),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=Ce.White()))}this._meshesFromObj.push({name:_n.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0})}for(let t=0;t=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){r.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[t].materialName),0===this._handledMesh.positions?.length){this._babylonMeshesArray.push(r);continue}const n=new cn;if(n.uvs=this._handledMesh.uvs,n.indices=this._handledMesh.indices,n.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const e=new Array;cn.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),n.normals=e}else n.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(n.colors=this._handledMesh.colors),n.applyToMesh(r),this._loadingOptions.invertY&&(r.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(r),this._babylonMeshesArray.push(r),this._handledMesh.directMaterial&&(r.material=this._handledMesh.directMaterial)}}}$B.ObjectDescriptor=/^o/,$B.GroupDescriptor=/^g/,$B.MtlLibGroupDescriptor=/^mtllib /,$B.UseMtlDescriptor=/^usemtl /,$B.SmoothDescriptor=/^s /,$B.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,$B.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,$B.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,$B.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,$B.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,$B.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,$B.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,$B.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,$B.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,$B.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,$B.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class qB{static get INVERT_TEXTURE_Y(){return KB.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){KB.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||qB._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:qB.COMPUTE_NORMALS,optimizeNormals:qB.OPTIMIZE_NORMALS,importVertexColors:qB.IMPORT_VERTEX_COLORS,invertY:qB.INVERT_Y,invertTextureY:qB.INVERT_TEXTURE_Y,UVScaling:qB.UV_SCALING,materialLoadingFailsSilently:qB.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:qB.OPTIMIZE_WITH_UV,skipMaterials:qB.SKIP_MATERIALS,useLegacyBehavior:qB.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,s){const r=t+e;hs.LoadFile(r,i,void 0,void 0,!1,((e,t)=>{s(r,t)}))}createPlugin(){return new qB(qB._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,s){return this._parseSolid(e,t,i,s).then((e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}loadAssetContainerAsync(e,t,i){const s=new Eo(e);return this._assetContainer=s,this.importMeshAsync(null,e,t,i).then((e=>(e.meshes.forEach((e=>s.meshes.push(e))),e.meshes.forEach((e=>{const t=e.material;t&&-1==s.materials.indexOf(t)&&(s.materials.push(t),t.getActiveTextures().forEach((e=>{-1==s.textures.indexOf(e)&&s.textures.push(e)})))})),this._assetContainer=null,s))).catch((e=>{throw this._assetContainer=null,e}))}_parseSolid(e,t,i,s){let r="";const n=new KB,o=[],a=[];new $B(o,a,this._loadingOptions).parse(e,i,t,this._assetContainer,(e=>{r=e}));const l=[];return""===r||this._loadingOptions.skipMaterials||l.push(new Promise(((e,i)=>{this._loadMTL(r,s,(l=>{try{n.parseMTL(t,l,s,this._assetContainer);for(let e=0;e-1;)i.push(s),t=s+1;if(-1===s&&0===i.length)n.materials[e].dispose();else for(let t=0;t{hs.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():i(s)}))}))),Promise.all(l).then((()=>a))}}qB.OPTIMIZE_WITH_UV=!0,qB.INVERT_Y=!1,qB.IMPORT_VERTEX_COLORS=!1,qB.COMPUTE_NORMALS=!1,qB.OPTIMIZE_NORMALS=!1,qB.UV_SCALING=new ue(1,1),qB.SKIP_MATERIALS=!1,qB.MATERIAL_LOADING_FAILS_SILENTLY=!0,qB.USE_LEGACY_BEHAVIOR=!1,Pa&&Pa.RegisterPlugin(new qB);class ZB{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name="stl",this.extensions={".stl":{isBinary:!0}}}importMesh(e,t,i,s,r){let n;if("string"!=typeof i){if(this._isBinary(i)){const e=new bo("stlmesh",t);return this._parseBinary(e,i),r&&r.push(e),!0}i=(new TextDecoder).decode(new Uint8Array(i))}for(;n=this.solidPattern.exec(i);){let i=n[1];const s=n[3];if(s&&i!=s)return hs.Error("Error in STL, solid name != endsolid name"),!1;if(e&&i)if(e instanceof Array){if(!e.indexOf(i))continue}else if(i!==e)continue;i=i||"stlmesh";const o=new bo(i,t);this._parseASCII(o,n[2]),r&&r.push(o)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const s=new Eo(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,s.meshes),e._blockEntityCollection=!1,s}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==i[e])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),s=i.getUint32(80,!0);let r=0;const n=new Float32Array(3*s*3),o=new Float32Array(3*s*3),a=new Uint32Array(3*s);let l=0;for(let e=0;e{if(e.tryDownload&&document){const i=new Blob([t],{type:"text/plain"}),s=URL.createObjectURL(i),r=e.fileName?e.fileName:"bitbybit-dev.step",n=document.createElement("a");n.href=s,n.target="_self",n.download=r,n.click(),n.remove()}return t}))}}class iL{constructor(e){this.occWorkerManager=e}makeCompound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.compound.makeCompound",e)}}class sL{constructor(e){this.occWorkerManager=e}line(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.line",e)}arcThroughThreePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughThreePoints",e)}arcThroughTwoPointsAndTangent(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughTwoPointsAndTangent",e)}arcFromCircleAndTwoPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoPoints",e)}arcFromCircleAndTwoAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoAngles",e)}arcFromCirclePointAndAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCirclePointAndAngle",e)}createCircleEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createCircleEdge",e)}createEllipseEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createEllipseEdge",e)}removeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.removeInternalEdges",e)}makeEdgeFromGeom2dCurveAndSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.makeEdgeFromGeom2dCurveAndSurface",e)}getEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdge",e)}getEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdges",e)}getEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesAlongWire",e)}getCircularEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgesAlongWire",e)}getLinearEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getLinearEdgesAlongWire",e)}getCornerPointsOfEdgesForShape(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCornerPointsOfEdgesForShape",e)}getEdgeLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeLength",e)}getEdgesLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesLengths",e)}getEdgeCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeCenterOfMass",e)}getEdgesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesCentersOfMass",e)}getCircularEdgeCenterPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeCenterPoint",e)}getCircularEdgeRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeRadius",e)}getCircularEdgePlaneDirection(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgePlaneDirection",e)}pointOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtParam",e)}edgesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.edgesToPoints",e)}reversedEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.reversedEdge",e)}tangentOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtParam",e)}pointOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtLength",e)}tangentOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtLength",e)}startPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.startPointOnEdge",e)}endPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.endPointOnEdge",e)}divideEdgeByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByParamsToPoints",e)}divideEdgeByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByEqualDistanceToPoints",e)}constraintTanLinesFromTwoPtsToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromTwoPtsToCircle",e)}constraintTanLinesFromPtToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromPtToCircle",e)}constraintTanLinesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesOnTwoCircles",e)}constraintTanCirclesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnTwoCircles",e)}constraintTanCirclesOnCircleAndPnt(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnCircleAndPnt",e)}}class rL{constructor(e){this.occWorkerManager=e}createFaceFromWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWire",e)}createFaceFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWires",e)}createFacesFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFacesFromWires",e)}createFaceFromMultipleCircleTanWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWires",e)}createFaceFromMultipleCircleTanWireCollections(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWireCollections",e)}faceFromSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurface",e)}faceFromSurfaceAndWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurfaceAndWire",e)}createPolygonFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createPolygonFace",e)}createCircleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createCircleFace",e)}createEllipseFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createEllipseFace",e)}createSquareFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createSquareFace",e)}createRectangleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createRectangleFace",e)}getFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFace",e)}getFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaces",e)}reversedFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.reversedFace",e)}subdivideToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPoints",e)}subdivideToPointsControlled(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsControlled",e)}subdivideToNormals(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToNormals",e)}subdivideToUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToUV",e)}pointOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointOnUV",e)}normalOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalOnUV",e)}pointsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointsOnUVs",e)}normalsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalsOnUVs",e)}subdivideToPointsOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsOnParam",e)}getUMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMinBound",e)}getUMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMaxBound",e)}getVMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMinBound",e)}getVMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMaxBound",e)}getFaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceArea",e)}getFacesAreas(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesAreas",e)}getFaceCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceCenterOfMass",e)}getFacesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesCentersOfMass",e)}filterFacePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.filterFacePoints",e)}}class nL{constructor(e){this.occWorkerManager=e}fromClosedShell(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.fromClosedShell",e)}createBox(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBox",e)}createCube(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCube",e)}createBoxFromCorner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBoxFromCorner",e)}createCylinder(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylinder",e)}createCylindersOnLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylindersOnLines",e)}createSphere(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createSphere",e)}createCone(e){return e.angle=e.angle*(Math.PI/180),this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCone",e)}getSolidSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidSurfaceArea",e)}getSolidVolume(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidVolume",e)}getSolidsVolumes(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsVolumes",e)}getSolidCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidCenterOfMass",e)}getSolidsCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsCentersOfMass",e)}getSolids(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolids",e)}filterSolidPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.filterSolidPoints",e)}}class oL{constructor(e){this.occWorkerManager=e}createPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygonWire",e)}createPolygons(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygons",e)}createLineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLineWire",e)}createLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLines",e)}splitOnPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.splitOnPoints",e)}wiresToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.wiresToPoints",e)}createPolylineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylineWire",e)}createZigZagBetweenTwoWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createZigZagBetweenTwoWires",e)}createWireFromTwoCirclesTan(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromTwoCirclesTan",e)}createPolylines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylines",e)}createBezier(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezier",e)}createBezierWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWires",e)}interpolatePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolatePoints",e)}interpolateWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolateWires",e)}createBSpline(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSpline",e)}createBSplines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSplines",e)}combineEdgesAndWiresIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.combineEdgesAndWiresIntoAWire",e)}createWireFromEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromEdge",e)}addEdgesAndWiresToWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.addEdgesAndWiresToWire",e)}divideWireByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByParamsToPoints",e)}divideWiresByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByParamsToPoints",e)}divideWireByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByEqualDistanceToPoints",e)}divideWiresByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByEqualDistanceToPoints",e)}pointOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtParam",e)}pointOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtLength",e)}tangentOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtParam",e)}tangentOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtLength",e)}derivativesOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtLength",e)}derivativesOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtParam",e)}startPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.startPointOnWire",e)}endPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.endPointOnWire",e)}createCircleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createCircleWire",e)}createSquareWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createSquareWire",e)}createStarWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createStarWire",e)}createChristmasTreeWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createChristmasTreeWire",e)}createNGonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createNGonWire",e)}createParallelogramWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createParallelogramWire",e)}createHeartWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createHeartWire",e)}createRectangleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createRectangleWire",e)}createLPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLPolygonWire",e)}createEllipseWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createEllipseWire",e)}getWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWire",e)}getWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWires",e)}getWireCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireCenterOfMass",e)}getWiresCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresCentersOfMass",e)}reversedWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWire",e)}reversedWireFromReversedEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWireFromReversedEdges",e)}getWireLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireLength",e)}getWiresLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresLengths",e)}placeWireOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWireOnFace",e)}placeWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWiresOnFace",e)}closeOpenWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.closeOpenWire",e)}project(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.project",e)}projectWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.projectWires",e)}}class aL{constructor(e){this.occWorkerManager=e}sewFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.sewFaces",e)}getShellSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.getShellSurfaceArea",e)}}class lL{constructor(e){this.occWorkerManager=e}purgeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.purgeInternalEdges",e)}unifySameDomain(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.unifySameDomain",e)}isClosed(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isClosed",e)}isConvex(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isConvex",e)}isChecked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isChecked",e)}isFree(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isFree",e)}isInfinite(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isInfinite",e)}isModified(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isModified",e)}isLocked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isLocked",e)}isNull(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNull",e)}isEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isEqual",e)}isNotEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNotEqual",e)}isPartner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isPartner",e)}isSame(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isSame",e)}getOrientation(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getOrientation",e)}getShapeType(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getShapeType",e)}}class hL{constructor(e){this.occWorkerManager=e}vertexFromPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexFromPoint",e)}verticesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesFromPoints",e)}verticesCompoundFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesCompoundFromPoints",e)}getVertices(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVertices",e)}getVerticesAsPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVerticesAsPoints",e)}verticesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesToPoints",e)}vertexToPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexToPoint",e)}}class cL{constructor(e){this.vertex=new hL(e),this.edge=new sL(e),this.wire=new oL(e),this.face=new rL(e),this.shell=new aL(e),this.solid=new nL(e),this.compound=new iL(e),this.shape=new lL(e)}}class uL{constructor(e){this.occWorkerManager=e}transform(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transform",e)}rotate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotate",e)}rotateAroundCenter(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenter",e)}align(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.align",e)}alignAndTranslate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslate",e)}translate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translate",e)}scale(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale",e)}scale3d(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3d",e)}mirror(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirror",e)}mirrorAlongNormal(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormal",e)}transformShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transformShapes",e)}rotateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateShapes",e)}rotateAroundCenterShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenterShapes",e)}alignShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignShapes",e)}alignAndTranslateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslateShapes",e)}translateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translateShapes",e)}scaleShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scaleShapes",e)}scale3dShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3dShapes",e)}mirrorShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorShapes",e)}mirrorAlongNormalShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormalShapes",e)}}class dL{constructor(e){this.occWorkerManager=e}loft(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loft",e)}loftAdvanced(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loftAdvanced",e)}closestPointsBetweenTwoShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsBetweenTwoShapes",e)}closestPointsOnShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapeFromPoints",e)}closestPointsOnShapesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapesFromPoints",e)}distancesToShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.distancesToShapeFromPoints",e)}extrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrude",e)}extrudeShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrudeShapes",e)}splitShapeWithShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.splitShapeWithShapes",e)}revolve(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.revolve",e)}rotatedExtrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.rotatedExtrude",e)}pipe(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipe",e)}pipePolylineWireNGon(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipePolylineWireNGon",e)}pipeWiresCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWiresCylindrical",e)}pipeWireCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWireCylindrical",e)}offset(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset",e)}offsetAdv(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offsetAdv",e)}makeThickSolidSimple(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidSimple",e)}makeThickSolidByJoin(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidByJoin",e)}slice(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.slice",e)}sliceInStepPattern(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.sliceInStepPattern",e)}offset3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset3DWire",e)}}class _L{constructor(e){this.occWorkerManager=e}union(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.union",e)}difference(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.difference",e)}intersection(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.intersection",e)}}class pL{constructor(e){this.occWorkerManager=e}geom2dEllipse(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dEllipse",e)}geom2dTrimmedCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dTrimmedCurve",e)}geom2dSegment(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dSegment",e)}get2dPointFrom2dCurveOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.get2dPointFrom2dCurveOnParam",e)}geomCircleCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomCircleCurve",e)}geomEllipseCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomEllipseCurve",e)}}class fL{constructor(e){this.occWorkerManager=e}cylindricalSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.cylindricalSurface",e)}surfaceFromFace(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.surfaceFromFace",e)}}class mL{constructor(e){this.curves=new pL(e),this.surfaces=new fL(e)}}class gL{constructor(e){this.occWorkerManager=e}filletEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdges",e)}filletEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesList",e)}filletEdgesListOneRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesListOneRadius",e)}filletEdgeVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgeVariableRadius",e)}filletEdgesSameVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesSameVariableRadius",e)}filletEdgesVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesVariableRadius",e)}fillet3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet3DWire",e)}chamferEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdges",e)}chamferEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesList",e)}chamferEdgeTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeTwoDistances",e)}chamferEdgesTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistances",e)}chamferEdgesTwoDistancesLists(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistancesLists",e)}chamferEdgeDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeDistAngle",e)}chamferEdgesDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistAngle",e)}chamferEdgesDistsAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistsAngles",e)}fillet2d(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet2d",e)}filletTwoEdgesInPlaneIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletTwoEdgesInPlaneIntoAWire",e)}}class vL{constructor(e){this.occWorkerManager=e}basicShapeRepair(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.basicShapeRepair",e)}fixSmallEdgeOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixSmallEdgeOnWire",e)}fixEdgeOrientationsAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixEdgeOrientationsAlongWire",e)}}var xL=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class bL{constructor(e){this.occWorkerManager=e,this.shapes=new cL(e),this.geom=new mL(e),this.transforms=new uL(e),this.operations=new dL(e),this.booleans=new _L(e),this.fillets=new gL(e),this.shapeFix=new vL(e),this.io=new tL(e)}shapeToMesh(e){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e)}))}shapesToMeshes(e){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e)}))}deleteShape(e){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShape",e)}))}deleteShapes(e){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShapes",e)}))}cleanAllCache(){return xL(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("cleanAllCache",{})}))}}var TL=function(e,t){return TL=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},TL(e,t)};function yL(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}TL(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function SL(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],s=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function CL(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var s,r,n=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return o}function EL(e,t,i){if(i||2===arguments.length)for(var s,r=0,n=t.length;r0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,s=i.hasError,r=i.isStopped,n=i.observers;return s||r?OL:(this.currentObservers=null,n.push(e),new ML((function(){t.currentObservers=null,IL(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,s=t.thrownError,r=t.isStopped;i?e.error(s):r&&e.complete()},t.prototype.asObservable=function(){var e=new tk;return e.source=this,e},t.create=function(e,t){return new lk(e,t)},t}(tk),lk=function(e){function t(t,i){var s=e.call(this)||this;return s.destination=t,s.source=i,s}return yL(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:OL},t}(ak);!function(e){e.loading="loading",e.loaded="loaded",e.initialised="initialised",e.computing="computing"}(sk||(sk={}));class hk{constructor(){this.occWorkerState$=new ak,this.promisesMade=[]}occWorkerAlreadyInitialised(){return!!this.occWorker}setOccWorker(e){this.occWorker=e,this.occWorker.onmessage=({data:e})=>{if("occ-initialised"===e)this.occWorkerState$.next({state:sk.initialised});else if("busy"===e)this.occWorkerState$.next({state:sk.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&void 0!==e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.occWorkerState$.next({state:sk.loaded}):this.occWorkerState$.next({state:sk.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,s={uid:i},r=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=r,this.promisesMade.push(s),this.occWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),r}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}!function(e){let t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(i=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(s=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(r=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(n=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(l=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(c=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(_=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(p=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(f=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(m=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainder=r)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,i,s,r,n){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==i&&(this.point1=i),void 0!==s&&(this.tolerance=s),void 0!==r&&(this.positionResult=r),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainders=r)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,i,s,r,n){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==i&&(this.planeOrigin=i),void 0!==s&&(this.planeDirection=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.solution=n)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==i&&(this.inside=i)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdgeIndexes=_),void 0!==p&&(this.edgeIndexHeight=p),void 0!==f&&(this.edgeIndexColour=f),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.DrawShapesDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdgeIndexes=_),void 0!==p&&(this.edgeIndexHeight=p),void 0!==f&&(this.edgeIndexColour=f),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.FaceSubdivisionDto=class{constructor(e,t,i,s,r,n,o,a,l){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepU=s),void 0!==r&&(this.removeStartEdgeU=r),void 0!==n&&(this.removeEndEdgeU=n),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==l&&(this.removeEndEdgeV=l)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepNthU=s),void 0!==r&&(this.shiftHalfStepUOffsetN=r),void 0!==n&&(this.removeStartEdgeNthU=n),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==l&&(this.removeEndEdgeUOffsetN=l),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==c&&(this.shiftHalfStepVOffsetN=c),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==_&&(this.removeEndEdgeNthV=_),void 0!==p&&(this.removeEndEdgeVOffsetN=p)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,i,s,r,n,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i),void 0!==s&&(this.nrPoints=s),void 0!==r&&(this.shiftHalfStep=r),void 0!==n&&(this.removeStartPoint=n),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,i){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==i&&(this.paramV=i)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,i){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.RectangleDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.LPolygonDto=class{constructor(e,t,i,s,n,o,a,l){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=r.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==i&&(this.widthSecond=i),void 0!==s&&(this.lengthSecond=s),void 0!==n&&(this.align=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==l&&(this.direction=l)}},e.BoxDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.center=s)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.corner=s)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,i,s,r,n){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==i&&(this.height=i),void 0!==s&&(this.angle=s),void 0!==r&&(this.center=r),void 0!==n&&(this.direction=n)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,i){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==i&&(this.end=i)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,i,s){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==i&&(this.end=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,i,s){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==i&&(this.alphaAngle2=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,i,s){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==s&&(this.sense=s)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,i){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==i&&(this.end=i)}},e.CylinderDto=class{constructor(e,t,i,s){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,i,s){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.indexes=s)}},e.FilletEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radius=i)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusLists=i),void 0!==s&&(this.paramsULists=s)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.Fillet3DWireDto=class{constructor(e,t,i,s,r){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.radiusList=s),void 0!==r&&(this.indexes=r)}},e.ChamferDto=class{constructor(e,t,i,s){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.distanceList=i),void 0!==s&&(this.indexes=s)}},e.ChamferEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.distanceList=i)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances1=s),void 0!==r&&(this.distances2=r)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances=s),void 0!==r&&(this.angles=r)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,i,s,r){this.keepLines=p.outside,this.circleRemainders=_.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.keepLines=i),void 0!==s&&(this.circleRemainders=s),void 0!==r&&(this.tolerance=r)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,i,s){this.combination=f.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,i,s){this.combination=f.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,i,s){this.nrZigZags=20,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==i&&(this.nrZigZags=i),void 0!==s&&(this.inverse=s)}},e.InterpolationDto=class{constructor(e,t,i){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==i&&(this.tolerance=i)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.ProjectWireDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.WiresToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.EdgesToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.ProjectWiresDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.DivideShapesDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,i,s){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.tEdgeParam=i),void 0!==s&&(this.distance2DParam=s)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,i,r,n,o,a,l,h,c,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=s.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==i&&(this.closed=i),void 0!==r&&(this.periodic=r),void 0!==n&&(this.straight=n),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==l&&(this.maxUDegree=l),void 0!==h&&(this.tolerance=h),void 0!==c&&(this.parType=c),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,i,s){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==i&&(this.distance=i),void 0!==s&&(this.tolerance=s)}},e.OffsetAdvancedDto=class{constructor(e,i,s,r,n,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.joinType=n),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,i,s){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.copy=s)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,i){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.nrCorners=i)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,i){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==i&&(this.keepEdges=i)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,i){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==i&&(this.precsmall=i)}},e.BasicShapeRepairDto=class{constructor(e,t,i,s){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.maxTolerance=i),void 0!==s&&(this.minTolerance=s)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,i){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==i&&(this.angle=i)}},e.ThickSolidByJoinDto=class{constructor(e,i,s,r,n,o,a,l){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.shapes=i),void 0!==s&&(this.offset=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.intersection=n),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==l&&(this.removeIntEdges=l)}},e.TransformDto=class{constructor(e,t,i,s,r){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==i&&(this.rotationAxis=i),void 0!==s&&(this.rotationAngle=s),void 0!==r&&(this.scaleFactor=r)}},e.TransformShapesDto=class{constructor(e,t,i,s,r){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==i&&(this.rotationAxes=i),void 0!==s&&(this.rotationAngles=s),void 0!==r&&(this.scaleFactors=r)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,i,s,r){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==i&&(this.fromDirection=i),void 0!==s&&(this.toOrigin=s),void 0!==r&&(this.toDirection=r)}},e.AlignShapesDto=class{constructor(e,t,i,s,r){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==i&&(this.fromDirections=i),void 0!==s&&(this.toOrigins=s),void 0!==r&&(this.toDirections=r)}},e.MirrorDto=class{constructor(e,t,i){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.direction=i)}},e.MirrorShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.directions=i)}},e.MirrorAlongNormalDto=class{constructor(e,t,i){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.normal=i)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.normals=i)}},e.AlignAndTranslateDto=class{constructor(e,t,i){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.center=i)}},e.UnifySameDomainDto=class{constructor(e,t,i,s){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==i&&(this.unifyFaces=i),void 0!==s&&(this.concatBSplines=s)}},e.FilterFacePointsDto=class{constructor(e,t,i,s,r,n,o,a,l){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.useBndBox=s),void 0!==r&&(this.gapTolerance=r),void 0!==n&&(this.keepIn=n),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==l&&(this.keepUnknown=l)}},e.FilterSolidPointsDto=class{constructor(e,t,i,s,r,n,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.keepIn=s),void 0!==r&&(this.keepOn=r),void 0!==n&&(this.keepOut=n),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,i){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==i&&(this.centers=i)}},e.RotateDto=class{constructor(e,t,i){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundCenterDto=class{constructor(e,t,i,s){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.center=i),void 0!==s&&(this.axis=s)}},e.RotateShapesDto=class{constructor(e,t,i){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==i&&(this.angles=i)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,i,s){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==i&&(this.centers=i),void 0!==s&&(this.axes=s)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,i){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==i&&(this.center=i)}},e.Scale3DShapesDto=class{constructor(e,t,i){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==i&&(this.centers=i)}},e.ShapeToMeshDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.ShapesToMeshesDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.SaveStepDto=class{constructor(e,t,i,s){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustYtoZ=i),void 0!==s&&(this.tryDownload=s)}},e.SaveStlDto=class{constructor(e,t,i,s,r,n){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.precision=i),void 0!==s&&(this.adjustYtoZ=s),void 0!==r&&(this.tryDownload=r),void 0!==n&&(this.binary=n)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,i){this.fileType=n.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==i&&(this.adjustZtoY=i)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,i){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustZtoY=i)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,i){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==i&&(this.direction=i)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,i){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==i&&(this.dir=i)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,i,s){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==i&&(this.nrOfPointsV=i),void 0!==s&&(this.flat=s)}},e.Geom2dEllipseDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s),void 0!==r&&(this.sense=r)}},e.Geom2dCircleDto=class{constructor(e,t,i,s){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.sense=s)}},e.ChristmasTreeDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==i&&(this.outerDist=i),void 0!==s&&(this.nrSkirts=s),void 0!==r&&(this.trunkHeight=r),void 0!==n&&(this.trunkWidth=n),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,i,s,r,n,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.numRays=i),void 0!==s&&(this.center=s),void 0!==r&&(this.direction=r),void 0!==n&&(this.offsetOuterEdges=n),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.aroundCenter=i),void 0!==s&&(this.width=s),void 0!==r&&(this.height=r),void 0!==n&&(this.angle=n)}},e.Heart2DDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.sizeApprox=s)}},e.NGonWireDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.nrCorners=i),void 0!==s&&(this.radius=s)}},e.EllipseDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,i,s,r){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==i&&(this.u2=i),void 0!==s&&(this.sense=s),void 0!==r&&(this.adjustPeriodic=r)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,i){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==i&&(this.direction=i)}},e.SliceInStepPatternDto=class{constructor(e,t,i){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==i&&(this.direction=i)}}}(rk||(rk={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(nk||(nk={})),"undefined"!=typeof document&&document.currentScript&&document.currentScript.src;class ck{constructor(e){this.context=e}create(e){const t=new de(e.target[0],e.target[1],e.target[2]),i=new Th(`arcRotateCamera${Math.random()}`,this.getRadians(e.alpha),this.getRadians(e.beta),e.radius,t,this.context.scene);void 0!==e.angularSensibilityX&&(i.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(i.angularSensibilityY=e.angularSensibilityY),void 0!==e.lowerBetaLimit&&(i.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(i.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.panningSensibility&&(i.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(i.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(i.maxZ=e.maxZ),i.minZ=0;const s=document.getElementById("renderCanvas");return i.attachControl(s,!0),i}getRadians(e){let t=vr.FromDegrees(e).radians();return e<0&&(t=-t),t}}class uk{constructor(e){this.context=e}create(e){const t=new de(e.position[0],e.position[1],e.position[2]),i=new xh(`freeCamera${Math.random()}`,t,this.context.scene),s=new de(e.target[0],e.target[1],e.target[2]);i.setTarget(s);const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i.minZ=0,i.maxZ=1e3,i}}class dk{constructor(e){this.context=e}create(e){const t=new de(e.position[0],e.position[1],e.position[2]),i=new vh(`freeCamera${Math.random()}`,t,this.context.scene),s=new de(e.target[0],e.target[1],e.target[2]);i.setTarget(s);const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i.minZ=0,i.maxZ=1e3,i}}class _k{constructor(e){this.context=e,this.free=new uk(this.context),this.arcRotate=new ck(this.context),this.target=new dk(this.context)}freezeProjectionMatrix(e){e.camera.freezeProjectionMatrix()}unfreezeProjectionMatrix(e){e.camera.unfreezeProjectionMatrix()}setPosition(e){const t=new de(e.position[0],e.position[1],e.position[2]);e.camera.position=t}getPosition(e){return[e.camera.position.x,e.camera.position.y,e.camera.position.z]}setTarget(e){const t=new de(e.target[0],e.target[1],e.target[2]);e.camera.setTarget(t)}getTarget(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setSpeed(e){e.camera.speed=e.speed}getSpeed(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setMinZ(e){e.camera.minZ=e.minZ}setMaxZ(e){e.camera.maxZ=e.maxZ}makeCameraOrthographic(e){e.camera.mode=Kr.ORTHOGRAPHIC_CAMERA,e.camera.orthoBottom=e.orthoBottom||-1,e.camera.orthoTop=e.orthoTop||1,e.camera.orthoLeft=e.orthoLeft||-1,e.camera.orthoRight=e.orthoRight||1}makeCameraPerspective(e){e.camera.mode=Kr.PERSPECTIVE_CAMERA}}class pk{constructor(e,t){this.context=e,this.color=t}create(e){const t=new zv(e.name,this.context.scene);return t.baseColor=Ce.FromHexString(e.baseColor),t.metallic=e.metallic,t.roughness=e.roughness,t.alpha=e.alpha,t.backFaceCulling=e.backFaceCulling,t.zOffset=e.zOffset,t.alphaMode=1,e.emissiveColor&&(t.emissiveColor=Ce.FromHexString(e.emissiveColor)),t}setBaseColor(e){e.material.baseColor=Ce.FromHexString(e.baseColor)}setMetallic(e){e.material.metallic=e.metallic}setRoughness(e){e.material.roughness=e.roughness}setAlpha(e){e.material.alpha=e.alpha}setBackFaceCulling(e){e.material.backFaceCulling=e.backFaceCulling}setBaseTexture(e){e.material.baseTexture=e.baseTexture}getBaseColor(e){const t=e.material,i=this.context.remap(t.baseColor.r,0,1,0,255),s=this.context.remap(t.baseColor.g,0,1,0,255),r=this.context.remap(t.baseColor.b,0,1,0,255);return this.color.rgbToHex({r:i,g:s,b:r})}getMetallic(e){return e.material.metallic}getRoughness(e){return e.material.roughness}getAlpha(e){return e.material.alpha}getBackFaceCulling(e){return e.material.backFaceCulling}getBaseTexture(e){return e.material.baseTexture}}class fk{constructor(e,t){this.context=e,this.color=t,this.pbrMetallicRoughness=new pk(e,t)}}var mk,gk=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class vk{constructor(e){this.context=e}createDefaultXRExperienceWithTeleportation(e){return gk(this,void 0,void 0,(function*(){const t=yield this.context.scene.createDefaultXRExperienceAsync();this.context.scene.metadata?this.context.scene.metadata.xr=t:this.context.scene.metadata={xr:t};const i=[];e.groundMeshes.forEach((e=>{e.getChildMeshes&&(null==e||e.getChildMeshes().forEach((e=>{e.isPickable=!0,i.push(e)}))),i.push(e),e.isPickable=!0}));const s=t.baseExperience.featuresManager,r=new zv("teleportation");r.baseColor=new Ce(0,0,1),r.metallic=0,r.roughness=1,s.enableFeature(ha.TELEPORTATION,"stable",{xrInput:t.input,floorMeshes:i,defaultTargetMeshOptions:{torusArrowMaterial:r,disableLighting:!1}});const n=new SN(this.context.scene);this.context.scene.metadata.guiManager=n,n.useRealisticScaling=!0;const o=new sN("near");n.addControl(o);const a=new Qw("button1"),l=new UD;l.text="Exit VR",l.color="white",l.fontSize="48px",a.onPointerClickObservable.add((()=>gk(this,void 0,void 0,(function*(){yield t.baseExperience.exitXRAsync()})))),o.addButton(a),a.content=l}))}}class xk{constructor(e){this.context=e}getEngine(){return this.context.engine}getRenderingCanvas(){return this.context.engine.getRenderingCanvas()}}class bk{static _CreateBufferView(e,t,i,s,r){const n={buffer:e,byteLength:i};return t&&(n.byteOffset=t),r&&(n.name=r),s&&(n.byteStride=s),n}static _CreateAccessor(e,t,i,s,r,n,o,a){const l={name:t,bufferView:e,componentType:s,count:r,type:i};return null!=o&&(l.min=o),null!=a&&(l.max=a),null!=n&&(l.byteOffset=n),l}static _CalculateMinMaxPositions(e,t,i){const s=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];let n,o,a;if(i)for(let l=t,h=t+i;lr[e]&&(r[e]=t),++n}}return{min:s,max:r}}static _NormalizeTangentFromRef(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);t>0&&(e.x/=t,e.y/=t,e.z/=t)}static _GetDataAccessorElementCount(e){switch(e){case"MAT2":case"VEC4":return 4;case"MAT3":return 9;case"MAT4":return 16;case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3}}}!function(e){e[e.INTANGENT=0]="INTANGENT",e[e.OUTTANGENT=1]="OUTTANGENT"}(mk||(mk={}));class Tk{static _IsTransformable(e){return e&&(e instanceof xn||e instanceof Kr||e instanceof yo)}static _CreateNodeAnimation(e,t,i,s,r){if(this._IsTransformable(e)){const n=[],o=[],a=t.getKeys(),l=Tk._CalculateMinMaxKeyFrames(a),h=Tk._DeduceInterpolation(a,i,s),c=h.interpolationType,u=h.shouldBakeAnimation;if(u?Tk._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,r,n,o,l,s):"LINEAR"===c||"STEP"===c?Tk._CreateLinearOrStepAnimation(e,t,i,n,o,s):"CUBICSPLINE"===c?Tk._CreateCubicSplineAnimation(e,t,i,n,o,s):Tk._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,r,n,o,l,s),n.length&&o.length)return{inputs:n,outputs:o,samplerInterpolation:c,inputsMin:u?l.min:hs.FloatRound(l.min/t.framePerSecond),inputsMax:u?l.max:hs.FloatRound(l.max/t.framePerSecond)}}return null}static _DeduceAnimationInfo(e){let t=null,i="VEC3",s=!1;const r=e.targetProperty.split(".");switch(r[0]){case"scaling":t="scale";break;case"position":t="translation";break;case"rotation":i="VEC4",t="rotation";break;case"rotationQuaternion":i="VEC4",s=!0,t="rotation";break;case"influence":i="SCALAR",t="weights";break;default:hs.Error(`Unsupported animatable property ${r[0]}`)}return t?{animationChannelTargetPath:t,dataAccessorType:i,useQuaternion:s}:(hs.Error("animation channel target path and data accessor type could be deduced"),null)}static _CreateNodeAnimationFromNodeAnimations(e,t,i,s,r,n,o,a,l,h){let c;if(Tk._IsTransformable(e)&&e.animations)for(const r of e.animations){if(h&&!h(r))continue;const u=Tk._DeduceAnimationInfo(r);u&&(c={name:r.name,samplers:[],channels:[]},Tk._AddAnimation(`${r.name}`,r.hasRunningRuntimeAnimations?t:c,e,r,u.dataAccessorType,u.animationChannelTargetPath,s,n,o,a,u.useQuaternion,l),c.samplers.length&&c.channels.length&&i.push(c))}}static _CreateMorphTargetAnimationFromMorphTargetAnimations(e,t,i,s,r,n,o,a,l,h){let c;if(e instanceof bo){const r=e.morphTargetManager;if(r)for(let u=0;u{for(let i=0;ie.morphTargetManager===i));s&&(h.has(s)||h.set(s,new Map),h.get(s)?.set(t,f),d.add(s),u.set(s,f))}}}}d.forEach((e=>{const t=e.morphTargetManager;let a=null;const d=[],p=u.get(e).getKeys(),f=p.length;for(let i=0;i0;)t=_.inputs.shift(),e%d==0&&i.push(t),e++;_.inputs=i}const s=o[i.uniqueId];let c=4*_.inputs.length;p=bk._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} keyframe data view`),l.push(p),_.inputs.forEach((function(e){a.setFloat32(e)})),f=bk._CreateAccessor(l.length-1,`${e} keyframes`,"SCALAR",5126,_.inputs.length,null,[_.inputsMin],[_.inputsMax]),h.push(f),m=h.length-1,v=_.outputs.length,c=4*bk._GetDataAccessorElementCount(r)*_.outputs.length,p=bk._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} data view`),l.push(p),_.outputs.forEach((function(e){e.forEach((function(e){a.setFloat32(e)}))})),f=bk._CreateAccessor(l.length-1,`${e} data`,r,5126,v,null,null,null),h.push(f),g=h.length-1,x={interpolation:_.samplerInterpolation,input:m,output:g},t.samplers.push(x),b={sampler:t.samplers.length-1,target:{node:s,path:n}},t.channels.push(b)}}static _CreateBakedAnimation(e,t,i,s,r,n,o,a,l,h,c){let u;const d=pe.Identity();let _,p=null,f=null,m=null,g=null,v=null,x=null;h.min=hs.FloatRound(s/n);const b=t.getKeys();for(let s=0,h=b.length;s{"StandardMaterial"===e.getClassName()?s.push(this._convertStandardMaterialAsync(e,t,i)):-1!==e.getClassName().indexOf("PBR")?s.push(this._convertPBRMaterialAsync(e,t,i)):hs.Warn(`Unsupported material type: ${e.name}`)})),Promise.all(s).then((()=>{}))}_stripTexturesFromMaterial(e){const t={};if(e){t.name=e.name,t.doubleSided=e.doubleSided,t.alphaMode=e.alphaMode,t.alphaCutoff=e.alphaCutoff,t.emissiveFactor=e.emissiveFactor;const i=e.pbrMetallicRoughness;i&&(t.pbrMetallicRoughness={},t.pbrMetallicRoughness.baseColorFactor=i.baseColorFactor,t.pbrMetallicRoughness.metallicFactor=i.metallicFactor,t.pbrMetallicRoughness.roughnessFactor=i.roughnessFactor)}return t}_hasTexturesPresent(e){if(e.emissiveTexture||e.normalTexture||e.occlusionTexture)return!0;const t=e.pbrMetallicRoughness;if(t&&(t.baseColorTexture||t.metallicRoughnessTexture))return!0;if(e.extensions)for(const t in e.extensions){const i=e.extensions[t];if(i)return i.hasTextures?.()}return!1}_getTextureInfo(e){if(e){const t=e.uid;if(t in this._textureMap)return this._textureMap[t]}return null}_convertToGLTFPBRMetallicRoughness(e){const t=new ue(0,1),i=new ue(0,.1),s=new ue(0,.1),r=new ue(1300,.1),n=e.diffuseColor.toLinearSpace(e.getScene().getEngine().useExactSrgbConversions).scale(.5),o=e.alpha,a=(l=xe.Clamp(e.specularPower,0,Sk._MaxSpecularPower),h=Math.pow(l/r.x,.333333),c=t.y,u=i.y,d=s.y,_=r.y,(1-h)*(1-h)*(1-h)*c+3*(1-h)*(1-h)*h*u+3*(1-h)*h*h*d+h*h*h*_);var l,h,c,u,d,_;return{baseColorFactor:[n.r,n.g,n.b,o],metallicFactor:0,roughnessFactor:a}}static _SolveMetallic(e,t,i){if(t{e&&(o.baseColorTexture=e)})));const i=e.bumpTexture;i&&n.push(this._exportTextureAsync(i,t).then((e=>{e&&(a.normalTexture=e,1!==i.level&&(a.normalTexture.scale=i.level))}))),e.emissiveTexture&&(a.emissiveFactor=[1,1,1],n.push(this._exportTextureAsync(e.emissiveTexture,t).then((e=>{e&&(a.emissiveTexture=e)})))),e.ambientTexture&&n.push(this._exportTextureAsync(e.ambientTexture,t).then((e=>{if(e){const t={index:e.index};a.occlusionTexture=t}})))}return(e.alpha<1||e.opacityTexture)&&(e.alphaMode===Yd.ALPHA_COMBINE?a.alphaMode="BLEND":hs.Warn(e.name+": glTF 2.0 does not support alpha mode: "+e.alphaMode.toString())),e.emissiveColor&&!Sk._FuzzyEquals(e.emissiveColor,Ce.Black(),Sk._Epsilon)&&(a.emissiveFactor=e.emissiveColor.asArray()),a.pbrMetallicRoughness=o,Sk._SetAlphaMode(a,e),r.push(a),s[e.uniqueId]=r.length-1,this._finishMaterial(n,a,e,t)}_finishMaterial(e,t,i,s){return Promise.all(e).then((()=>{const e=this._exporter._extensionsPostExportMaterialAdditionalTextures("exportMaterial",t,i);let r=null;for(const t of e)r||(r=[]),r.push(this._exportTextureAsync(t,s));return r||(r=[Promise.resolve(null)]),Promise.all(r).then((()=>{const e=this._exporter._extensionsPostExportMaterialAsync("exportMaterial",t,i);return e?e.then((()=>t)):t}))}))}async _getImageDataAsync(e,t,i,s){const r=Yd.TEXTURETYPE_UNSIGNED_INT,n=this._exporter._babylonScene,o=n.getEngine(),a=o.createRawTexture(e,t,i,Yd.TEXTUREFORMAT_RGBA,!1,!0,Vo.NEAREST_SAMPLINGMODE,null,r);await g_.ApplyPostProcess("pass",a,n,r,Yd.TEXTURE_NEAREST_SAMPLINGMODE,Yd.TEXTUREFORMAT_RGBA);const l=await o._readTexturePixels(a,t,i);return await _l.DumpDataAsync(t,i,l,s,void 0,!0,!0)}_createWhiteTexture(e,t,i){const s=new Uint8Array(e*t*4);for(let e=0;er.width?(o=t&&t instanceof Vo?g_.CreateResizedCopy(t,s.width,s.height,!0):this._createWhiteTexture(s.width,s.height,i),n=e):(n=e,o=t),{texture1:n,texture2:o}}_convertPixelArrayToFloat32(e){if(e instanceof Uint8Array){const t=e.length,i=new Float32Array(e.length);for(let s=0;sSk._Epsilon?T.baseColor.r:1,m[i+1]/=T.baseColor.g>Sk._Epsilon?T.baseColor.g:1,m[i+2]/=T.baseColor.b>Sk._Epsilon?T.baseColor.b:1;const s=Ce.FromInts(m[i],m[i+1],m[i+2]).toGammaSpace(n.getEngine().useExactSrgbConversions);m[i]=255*s.r,m[i+1]=255*s.g,m[i+2]=255*s.b,Sk._FuzzyEquals(s,Ce.White(),Sk._Epsilon)||(S=!0),f[i+1]/=T.roughness>Sk._Epsilon?T.roughness:1,f[i+2]/=T.metallic>Sk._Epsilon?T.metallic:1;const r=Ce.FromInts(255,f[i+1],f[i+2]);Sk._FuzzyEquals(r,Ce.White(),Sk._Epsilon)||(y=!0)}return y&&r.push(this._getImageDataAsync(f,c,u,s).then((e=>{T.metallicRoughnessTextureData=e}))),S&&r.push(this._getImageDataAsync(m,c,u,s).then((e=>{T.baseColorTextureData=e}))),Promise.all(r).then((()=>T))}return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!")}_convertSpecularGlossinessToMetallicRoughness(e){const t=this._getPerceivedBrightness(e.diffuseColor),i=this._getPerceivedBrightness(e.specularColor),s=1-this._getMaxComponent(e.specularColor),r=Sk._SolveMetallic(t,i,s),n=e.diffuseColor.scale(s/(1-Sk._DielectricSpecular.r)/Math.max(1-r,Sk._Epsilon)),o=e.specularColor.subtract(Sk._DielectricSpecular.scale(1-r)).scale(1/Math.max(r,Sk._Epsilon));let a=Ce.Lerp(n,o,r*r);return a=a.clampToRef(0,1,a),{baseColor:a,metallic:r,roughness:1-e.glossiness}}_getPerceivedBrightness(e){return e?Math.sqrt(.299*e.r*e.r+.587*e.g*e.g+.114*e.b*e.b):0}_getMaxComponent(e){return e?Math.max(e.r,Math.max(e.g,e.b)):0}_convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,i,s){const r=[],n={baseColor:e._albedoColor,metallic:e._metallic,roughness:e._roughness};if(s){e._albedoTexture&&r.push(this._exportTextureAsync(e._albedoTexture,t).then((e=>{e&&(i.baseColorTexture=e)})));const s=e._metallicTexture;s&&r.push(this._exportTextureAsync(s,t).then((e=>{e&&(i.metallicRoughnessTexture=e)})))}return Promise.all(r).then((()=>n))}_getTextureSampler(e){const t={};if(!(e&&e instanceof Vo))return t;const i=this._getGLTFTextureWrapMode(e.wrapU);10497!==i&&(t.wrapS=i);const s=this._getGLTFTextureWrapMode(e.wrapV);switch(10497!==s&&(t.wrapT=s),e.samplingMode){case Vo.LINEAR_LINEAR:t.magFilter=9729,t.minFilter=9729;break;case Vo.LINEAR_NEAREST:t.magFilter=9729,t.minFilter=9728;break;case Vo.NEAREST_LINEAR:t.magFilter=9728,t.minFilter=9729;break;case Vo.NEAREST_LINEAR_MIPLINEAR:t.magFilter=9728,t.minFilter=9987;break;case Vo.NEAREST_NEAREST:t.magFilter=9728,t.minFilter=9728;break;case Vo.NEAREST_LINEAR_MIPNEAREST:t.magFilter=9728,t.minFilter=9985;break;case Vo.LINEAR_NEAREST_MIPNEAREST:t.magFilter=9729,t.minFilter=9984;break;case Vo.LINEAR_NEAREST_MIPLINEAR:t.magFilter=9729,t.minFilter=9986;break;case Vo.NEAREST_NEAREST_MIPLINEAR:t.magFilter=9728,t.minFilter=9986;break;case Vo.LINEAR_LINEAR_MIPLINEAR:t.magFilter=9729,t.minFilter=9987;break;case Vo.LINEAR_LINEAR_MIPNEAREST:t.magFilter=9729,t.minFilter=9985;break;case Vo.NEAREST_NEAREST_MIPNEAREST:t.magFilter=9728,t.minFilter=9984}return t}_getGLTFTextureWrapMode(e){switch(e){case Vo.WRAP_ADDRESSMODE:return 10497;case Vo.CLAMP_ADDRESSMODE:return 33071;case Vo.MIRROR_ADDRESSMODE:return 33648;default:return hs.Error(`Unsupported Texture Wrap Mode ${e}!`),10497}}_convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,i,s){return Promise.resolve().then((()=>{const r={diffuseColor:e._albedoColor,specularColor:e._reflectivityColor,glossiness:e._microSurface},n=e._albedoTexture,o=e._reflectivityTexture,a=e._useMicroSurfaceFromReflectivityMapAlpha;if(o&&!a)return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");if((n||o)&&s){const e=this._exportTextureSampler(n||o);return this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(n,o,r,t).then((s=>{const r=this._exporter._textures;if(s.baseColorTextureData){const o=this._exportImage(`baseColor${r.length}`,t,s.baseColorTextureData);i.baseColorTexture=this._exportTextureInfo(o,e,n?.coordinatesIndex)}if(s.metallicRoughnessTextureData){const n=this._exportImage(`metallicRoughness${r.length}`,t,s.metallicRoughnessTextureData);i.metallicRoughnessTexture=this._exportTextureInfo(n,e,o?.coordinatesIndex)}return s}))}return this._convertSpecularGlossinessToMetallicRoughness(r)}))}_convertPBRMaterialAsync(e,t,i){const s={},r={name:e.name};if(e.isMetallicWorkflow()){const n=e._albedoColor,o=e.alpha;return n&&(s.baseColorFactor=[n.r,n.g,n.b,o]),this._convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,s,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,r,s,t,i)))}return this._convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,s,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,r,s,t,i)))}_setMetallicRoughnessPbrMaterial(e,t,i,s,r,n){const o=this._exporter._materialMap,a=this._exporter._materials,l=[];if(e){if(Sk._SetAlphaMode(i,t),Sk._FuzzyEquals(e.baseColor,Ce.White(),Sk._Epsilon)&&t.alpha>=Sk._Epsilon||(s.baseColorFactor=[e.baseColor.r,e.baseColor.g,e.baseColor.b,t.alpha]),null!=e.metallic&&1!==e.metallic&&(s.metallicFactor=e.metallic),null!=e.roughness&&1!==e.roughness&&(s.roughnessFactor=e.roughness),null==t.backFaceCulling||t.backFaceCulling||(t._twoSidedLighting||hs.Warn(t.name+": Back-face culling disabled and two-sided lighting disabled is not supported in glTF."),i.doubleSided=!0),n){const e=t._bumpTexture;if(e){const t=this._exportTextureAsync(e,r).then((t=>{t&&(i.normalTexture=t,1!==e.level&&(i.normalTexture.scale=e.level))}));l.push(t)}const s=t._ambientTexture;if(s){const e=this._exportTextureAsync(s,r).then((e=>{if(e){const s={index:e.index,texCoord:e.texCoord,extensions:e.extensions};i.occlusionTexture=s;const r=t._ambientTextureStrength;r&&(s.strength=r)}}));l.push(e)}const n=t._emissiveTexture;if(n){const e=this._exportTextureAsync(n,r).then((e=>{e&&(i.emissiveTexture=e)}));l.push(e)}}const h=t._emissiveColor;Sk._FuzzyEquals(h,Ce.Black(),Sk._Epsilon)||(i.emissiveFactor=h.asArray()),i.pbrMetallicRoughness=s,a.push(i),o[t.uniqueId]=a.length-1}return this._finishMaterial(l,i,t,r)}_getPixelsFromTexture(e){return e.textureType,Yd.TEXTURETYPE_UNSIGNED_INT,e.readPixels()}_exportTextureAsync(e,t){const i=this._exporter._extensionsPreExportTextureAsync("exporter",e,t);return i?i.then((i=>i?this._exportTextureInfoAsync(i,t):this._exportTextureInfoAsync(e,t))):this._exportTextureInfoAsync(e,t)}async _exportTextureInfoAsync(e,t){const i=e.uid;if(!(i in this._textureMap)){const s=await this._getPixelsFromTexture(e);if(!s)return null;const r=this._exportTextureSampler(e),n=e.mimeType;if(n)switch(n){case"image/jpeg":case"image/png":case"image/webp":t=n;break;default:hs.Warn(`Unsupported media type: ${n}`)}const o=this._internalTextureToImage,a=e.getInternalTexture().uniqueId;o[a]||(o[a]={});let l=o[a][t];if(void 0===l){const i=e.getSize();l=(async()=>{const r=await this._getImageDataAsync(s,i.width,i.height,t);return this._exportImage(e.name,t,r)})(),o[a][t]=l}const h=this._exportTextureInfo(await l,r,e.coordinatesIndex);this._textureMap[i]=h,this._exporter._extensionsPostExportTextures("exporter",this._textureMap[i],e)}return this._textureMap[i]}_exportImage(e,t,i){const s=this._exporter._imageData,r=e.replace(/\.\/|\/|\.\\|\\/g,"_"),n=function(e){switch(e){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/webp":return".webp";case"image/avif":return".avif"}}(t);let o=r+n;o in s&&(o=`${r}_${hs.RandomId()}${n}`),s[o]={data:i,mimeType:t};const a=this._exporter._images;return a.push({name:e,uri:o}),a.length-1}_exportTextureInfo(e,t,i){const s=this._exporter._textures;let r=s.findIndex((i=>i.sampler==t&&i.source===e));-1===r&&(r=s.length,s.push({source:e,sampler:t}));const n={index:r};return i&&(n.texCoord=i),n}_exportTextureSampler(e){const t=this._getTextureSampler(e),i=this._exporter._samplers,s=i.findIndex((e=>e.minFilter===t.minFilter&&e.magFilter===t.magFilter&&e.wrapS===t.wrapS&&e.wrapT===t.wrapT));return-1!==s?s:(i.push(t),i.length-1)}}Sk._DielectricSpecular=new Ce(.04,.04,.04),Sk._MaxSpecularPower=1024,Sk._Epsilon=1e-6;const Ck=fe.Compose(new de(-1,1,1),pe.Identity(),de.Zero()),Ek=new pe(0,1,0,0);function Ak(e,t){if(!(e instanceof xn))return!1;if(t){if(!e.getWorldMatrix().isIdentity())return!1}else if(!e.getWorldMatrix().multiplyToRef(Ck,ge.Matrix[0]).isIdentity())return!1;return!(e instanceof bo&&e.geometry||e instanceof To&&e.sourceMesh.geometry)}function Pk(e){const t=de.FromArrayToRef(e.translation||[0,0,0],0,ge.Vector3[0]),i=pe.FromArrayToRef(e.rotation||[0,0,0,1],0,ge.Quaternion[0]),s=de.FromArrayToRef(e.scale||[1,1,1],0,ge.Vector3[1]);fe.ComposeToRef(s,i,t,ge.Matrix[0]).multiplyToRef(Ck,ge.Matrix[0]).decompose(s,i,t),t.equalsToFloats(0,0,0)?delete e.translation:e.translation=t.asArray(),pe.IsIdentity(i)?delete e.rotation:e.rotation=i.asArray(),s.equalsToFloats(1,1,1)?delete e.scale:e.scale=s.asArray()}class Rk{_applyExtension(e,t,i,s){if(i>=t.length)return Promise.resolve(e);const r=s(t[i],e);return r?r.then((e=>this._applyExtension(e,t,i+1,s))):this._applyExtension(e,t,i+1,s)}_applyExtensions(e,t){const i=[];for(const e of Rk._ExtensionNames)i.push(this._extensions[e]);return this._applyExtension(e,i,0,t)}_extensionsPreExportTextureAsync(e,t,i){return this._applyExtensions(t,((t,s)=>t.preExportTextureAsync&&t.preExportTextureAsync(e,s,i)))}_extensionsPostExportMeshPrimitiveAsync(e,t,i,s){return this._applyExtensions(t,((t,r)=>t.postExportMeshPrimitiveAsync&&t.postExportMeshPrimitiveAsync(e,r,i,s)))}_extensionsPostExportNodeAsync(e,t,i,s,r){return this._applyExtensions(t,((t,n)=>t.postExportNodeAsync&&t.postExportNodeAsync(e,n,i,s,r)))}_extensionsPostExportMaterialAsync(e,t,i){return this._applyExtensions(t,((t,s)=>t.postExportMaterialAsync&&t.postExportMaterialAsync(e,s,i)))}_extensionsPostExportMaterialAdditionalTextures(e,t,i){const s=[];for(const r of Rk._ExtensionNames){const n=this._extensions[r];n.postExportMaterialAdditionalTextures&&s.push(...n.postExportMaterialAdditionalTextures(e,t,i))}return s}_extensionsPostExportTextures(e,t,i){for(const s of Rk._ExtensionNames){const r=this._extensions[s];r.postExportTexture&&r.postExportTexture(e,t,i)}}_forEachExtensions(e){for(const t of Rk._ExtensionNames){const i=this._extensions[t];i.enabled&&e(i)}}_extensionsOnExporting(){this._forEachExtensions((e=>{e.wasUsed&&(null==this._glTF.extensionsUsed&&(this._glTF.extensionsUsed=[]),-1===this._glTF.extensionsUsed.indexOf(e.name)&&this._glTF.extensionsUsed.push(e.name),e.required&&(null==this._glTF.extensionsRequired&&(this._glTF.extensionsRequired=[]),-1===this._glTF.extensionsRequired.indexOf(e.name)&&this._glTF.extensionsRequired.push(e.name)),null==this._glTF.extensions&&(this._glTF.extensions={}),e.onExporting&&e.onExporting())}))}_loadExtensions(){for(const e of Rk._ExtensionNames){const t=Rk._ExtensionFactories[e](this);this._extensions[e]=t}}constructor(e,t){this._extensions={},this._glTF={asset:{generator:`Babylon.js v${gn.Version}`,version:"2.0"}},(e=e||se.LastCreatedScene)&&(this._babylonScene=e,this._bufferViews=[],this._accessors=[],this._meshes=[],this._scenes=[],this._cameras=[],this._nodes=[],this._images=[],this._materials=[],this._materialMap=[],this._textures=[],this._samplers=[],this._skins=[],this._animations=[],this._imageData={},this._orderedImageData=[],this._options=t||{},this._animationSampleRate=this._options.animationSampleRate||1/60,this._glTFMaterialExporter=new Sk(this),this._loadExtensions())}dispose(){for(const e in this._extensions)this._extensions[e].dispose()}get options(){return this._options}static RegisterExtension(e,t){Rk.UnregisterExtension(e)&&hs.Warn(`Extension with the name ${e} already exists`),Rk._ExtensionFactories[e]=t,Rk._ExtensionNames.push(e)}static UnregisterExtension(e){if(!Rk._ExtensionFactories[e])return!1;delete Rk._ExtensionFactories[e];const t=Rk._ExtensionNames.indexOf(e);return-1!==t&&Rk._ExtensionNames.splice(t,1),!0}_reorderIndicesBasedOnPrimitiveMode(e,t,i,s,r){switch(t){case uo.TriangleFillMode:s||(s=0);for(let t=e.indexStart,i=e.indexStart+e.indexCount;t=n;--t)r.setUInt32(i[t],s),s+=4;break;case uo.TriangleStripDrawMode:e.indexCount>=3&&(r.setUInt32(i[e.indexStart+2],s+4),r.setUInt32(i[e.indexStart+1],s+8))}}_reorderVertexAttributeDataBasedOnPrimitiveMode(e,t,i,s,r,n){switch(t){case uo.TriangleFillMode:this._reorderTriangleFillMode(e,i,s,r,n);break;case uo.TriangleStripDrawMode:this._reorderTriangleStripDrawMode(e,i,s,r,n);break;case uo.TriangleFanDrawMode:this._reorderTriangleFanMode(e,i,s,r,n)}}_reorderTriangleFillMode(e,t,i,s,r){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/ys.GetTypeByteLength(n.type);if(e.verticesCount%3!=0)hs.Error("The submesh vertices for the triangle fill mode is not divisible by 3!");else{const a=[];let l=0;switch(t){case ys.PositionKind:case ys.NormalKind:for(let t=e.verticesStart;t=e.verticesStart;--t)l=t*o,a.push(_e.FromArray(i,l));break;case ys.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,4===n.getSize()?a.push(_e.FromArray(i,l)):a.push(de.FromArray(i,l));break;case ys.UVKind:case ys.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(ue.FromArray(i,l));break;default:hs.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,s+12,t,r)}else hs.Warn(`reorderTriangleStripDrawMode: Vertex buffer kind ${t} not present!`)}_reorderTriangleFanMode(e,t,i,s,r){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/ys.GetTypeByteLength(n.type),a=[];let l=0;switch(t){case ys.PositionKind:case ys.NormalKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(de.FromArray(i,l));break;case ys.TangentKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(_e.FromArray(i,l));break;case ys.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(_e.FromArray(i,l)),4===n.getSize()?a.push(_e.FromArray(i,l)):a.push(de.FromArray(i,l));break;case ys.UVKind:case ys.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(ue.FromArray(i,l));break;default:hs.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,s,t,r)}else hs.Warn(`reorderTriangleFanMode: Vertex buffer kind ${t} not present!`)}_writeVertexAttributeData(e,t,i,s){for(const r of e){i===ys.NormalKind?r.normalize():i===ys.TangentKind&&r instanceof _e&&bk._NormalizeTangentFromRef(r);for(const e of r.asArray())s.setFloat32(e,t),t+=4}}_writeAttributeData(e,t,i,s,r,n){let o,a,l=[];switch(e){case ys.PositionKind:for(let e=0,t=i.length/s;e{e.uri&&(n=this._imageData[e.uri],this._orderedImageData.push(n),r=e.uri.split(".")[0]+" image",o=bk._CreateBufferView(0,a,n.data.byteLength,void 0,r),a+=n.data.byteLength,this._bufferViews.push(o),e.bufferView=this._bufferViews.length-1,e.name=r,e.mimeType=n.mimeType,e.uri=void 0,this._glTF.images||(this._glTF.images=[]),this._glTF.images.push(e))})),s.byteLength=a):this._glTF.images=this._images),e||(s.uri=t+".bin"),i?JSON.stringify(this._glTF,null,2):JSON.stringify(this._glTF)}_generateGLTFAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const s=this._generateJSON(!1,e,!0),r=new Blob([i],{type:"application/octet-stream"}),n=e+".gltf",o=e+".bin",a=new yk;if(a.glTFFiles[n]=s,a.glTFFiles[o]=r,this._imageData)for(const e in this._imageData)a.glTFFiles[e]=new Blob([this._imageData[e].data],{type:this._imageData[e].mimeType});return t&&this.dispose(),a}))}_generateBinaryAsync(){const e=new Ik(4);return this._createSceneAsync(e).then((()=>(this._localEngine&&this._localEngine.dispose(),e.getArrayBuffer())))}_getPadding(e){const t=e%4;return 0===t?t:4-t}_generateGLBAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const s=this._generateJSON(!0),r=e+".glb";let n,o=s.length,a=0;"undefined"!=typeof TextEncoder&&(n=(new TextEncoder).encode(s),o=n.length);for(let e=0;e0){if((null!==o.overrideMaterialSideOrientation?o.overrideMaterialSideOrientation:d.sideOrientation)===(this._babylonScene.useRightHandedSystem?uo.ClockWiseSideOrientation:uo.CounterClockWiseSideOrientation)){let e=null!=l?this._bufferViews[l].byteOffset:null;null==e&&(e=0);let t=null;if(null!=l&&(t=o.getIndices()),t)this._reorderIndicesBasedOnPrimitiveMode(r,h,t,e,i);else for(const e of a){const t=o.getVerticesData(e.kind,void 0,void 0,!0);if(t){const s=this._bufferViews[c[e.kind]].byteOffset||0;this._reorderVertexAttributeDataBasedOnPrimitiveMode(r,h,e.kind,t,s,i)}}}null!=_&&(f.material=_)}if(u){e.extras||(e.extras={}),e.extras.targetNames=[];for(let t=0;t{}))}_createSceneAsync(e){const t={nodes:[]};let i,s,r;const n=[...this._babylonScene.transformNodes,...this._babylonScene.meshes,...this._babylonScene.lights,...this._babylonScene.cameras],o=new Set;if(this._babylonScene.metadata&&(this._options.metadataSelector?t.extras=this._options.metadataSelector(this._babylonScene.metadata):this._babylonScene.metadata.gltf&&(t.extras=this._babylonScene.metadata.gltf.extras)),(this._options.removeNoopRootNodes??1)&&!this._options.includeCoordinateSystemConversionNodes)for(const e of this._babylonScene.rootNodes)Ak(e,this._babylonScene.useRightHandedSystem)&&(o.add(e),n.splice(n.indexOf(e),1));const a=new Map;this._babylonScene.cameras.forEach((e=>{if(this._options.shouldExportNode&&!this._options.shouldExportNode(e))return;const t={type:e.mode===Kr.PERSPECTIVE_CAMERA?"perspective":"orthographic"};if(e.name&&(t.name=e.name),"perspective"===t.type)t.perspective={aspectRatio:e.getEngine().getAspectRatio(e),yfov:e.fovMode===Kr.FOVMODE_VERTICAL_FIXED?e.fov:e.fov*e.getEngine().getAspectRatio(e),znear:e.minZ,zfar:e.maxZ};else if("orthographic"===t.type){const i=e.orthoLeft&&e.orthoRight?.5*(e.orthoRight-e.orthoLeft):.5*e.getEngine().getRenderWidth(),s=e.orthoBottom&&e.orthoTop?.5*(e.orthoTop-e.orthoBottom):.5*e.getEngine().getRenderHeight();t.orthographic={xmag:i,ymag:s,znear:e.minZ,zfar:e.maxZ}}a.set(e,this._cameras.length),this._cameras.push(t)}));const[l,h]=this._getExportNodes(n);return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(h,"image/png",!0).then((()=>this._createNodeMapAndAnimationsAsync(l,e).then((l=>this._createSkinsAsync(l,e).then((h=>{if(this._nodeMap=l,this._totalByteLength=e.getByteOffset(),null==this._totalByteLength)throw new Error("undefined byte length!");for(const e of n)if(i=this._nodeMap[e.uniqueId],void 0!==i&&(s=this._nodes[i],e.metadata&&(this._options.metadataSelector?s.extras=this._options.metadataSelector(e.metadata):e.metadata.gltf&&(s.extras=e.metadata.gltf.extras)),e instanceof Kr&&(s.camera=a.get(e)),this._options.shouldExportNode&&!this._options.shouldExportNode(e)?hs.Log("Omitting "+e.name+" from scene."):(e.parent||this._babylonScene.useRightHandedSystem||Pk(s),e.parent&&!o.has(e.parent)||t.nodes.push(i)),e instanceof bo&&e.skeleton&&(s.skin=h[e.skeleton.uniqueId]),r=e.getDescendants(!0),!s.children&&r&&r.length)){const e=[];for(const t of r)null!=this._nodeMap[t.uniqueId]&&e.push(this._nodeMap[t.uniqueId]);e.length&&(s.children=e)}t.nodes.length&&this._scenes.push(t)}))))))}_getExportNodes(e){const t=[],i=new Set;for(const s of e)if(!this._options.shouldExportNode||this._options.shouldExportNode(s)){t.push(s);const e=s;if(e.subMeshes&&e.subMeshes.length>0){const t=e.material||e.getScene().defaultMaterial;if(t instanceof _o)for(const e of t.subMaterials)e&&i.add(e);else i.add(t)}}else s.name;return[t,i]}_createNodeMapAndAnimationsAsync(e,t){let i=Promise.resolve();const s={};let r;const n={name:"runtime animations",channels:[],samplers:[]},o=[];for(const a of e)i=i.then((()=>this._createNodeAsync(a,t).then((e=>{const i=this._extensionsPostExportNodeAsync("createNodeAsync",e,a,s,t);return null==i?(hs.Warn(`Not exporting node ${a.name}`),Promise.resolve()):i.then((e=>{e&&(this._nodes.push(e),r=this._nodes.length-1,s[a.uniqueId]=r,this._babylonScene.animationGroups.length||(Tk._CreateMorphTargetAnimationFromMorphTargetAnimations(a,n,o,s,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),a.animations.length&&Tk._CreateNodeAnimationFromNodeAnimations(a,n,o,s,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation)))}))}))));return i.then((()=>(n.channels.length&&n.samplers.length&&this._animations.push(n),o.forEach((e=>{e.channels.length&&e.samplers.length&&this._animations.push(e)})),this._babylonScene.animationGroups.length&&Tk._CreateNodeAndMorphAnimationFromAnimationGroups(this._babylonScene,this._animations,s,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),s)))}_createNodeAsync(e,t){return Promise.resolve().then((()=>{const i={},s={primitives:[]};if(e.name&&(i.name=e.name),e instanceof xn){if(this._setNodeTransformation(i,e),e instanceof bo){const t=e.morphTargetManager;if(t&&t.numTargets>0){s.weights=[];for(let e=0;e(s.primitives.length&&(this._meshes.push(s),i.mesh=this._meshes.length-1),i)))}return e instanceof Kr?(this._setCameraTransformation(i,e),i):i}))}_createSkinsAsync(e,t){const i=Promise.resolve(),s={};for(const i of this._babylonScene.skeletons){if(i.bones.length<=0)continue;const r={joints:[]},n=[],o={};let a=-1;for(let e=0;ea&&(a=s))}for(let t=0;t<=a;++t){const i=o[t];n.push(i.getInvertedAbsoluteTransform());const s=i.getTransformNode();s&&null!==e[s.uniqueId]&&void 0!==e[s.uniqueId]?r.joints.push(e[s.uniqueId]):hs.Warn("Exporting a bone without a linked transform node is currently unsupported")}if(r.joints.length>0){const e=64,o=n.length*e,a=t.getByteOffset(),l=bk._CreateBufferView(0,a,o,void 0,"InverseBindMatrices - "+i.name);this._bufferViews.push(l);const h=this._bufferViews.length-1,c=bk._CreateAccessor(h,"InverseBindMatrices - "+i.name,"MAT4",5126,n.length,null,null,null),u=this._accessors.push(c)-1;r.inverseBindMatrices=u,this._skins.push(r),s[i.uniqueId]=this._skins.length-1,n.forEach((e=>{e.m.forEach((e=>{t.setFloat32(e)}))}))}}return i.then((()=>s))}}Rk._ExtensionNames=new Array,Rk._ExtensionFactories={};class Ik{constructor(e){this._arrayBuffer=new ArrayBuffer(e),this._dataView=new DataView(this._arrayBuffer),this._byteOffset=0}_resizeBuffer(e){const t=new ArrayBuffer(e),i=Math.min(this._arrayBuffer.byteLength,e),s=new Uint8Array(this._arrayBuffer,0,i);return new Uint8Array(t).set(s,0),this._arrayBuffer=t,this._dataView=new DataView(this._arrayBuffer),t}getArrayBuffer(){return this._resizeBuffer(this.getByteOffset())}getByteOffset(){if(null==this._byteOffset)throw new Error("Byte offset is undefined!");return this._byteOffset}setUInt8(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint8(this._byteOffset,e),this._byteOffset+=1)}setUInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint16(this._byteOffset,e,!0),this._byteOffset+=2)}getUInt32(e){if(ethis._byteOffset?hs.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0))}setVector3Float32FromRef(e,t){t+8>this._byteOffset?hs.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0))}getVector4Float32FromRef(e,t){t+12>this._byteOffset?hs.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0),e.w=this._dataView.getFloat32(t+12,!0))}setVector4Float32FromRef(e,t){t+12>this._byteOffset?hs.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0),this._dataView.setFloat32(t+12,e.w,!0))}setFloat32(e,t){isNaN(e)&&hs.Error("Invalid data being written!"),null!=t&&(tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setFloat32(this._byteOffset,e,!0),this._byteOffset+=4}setUInt32(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint32(this._byteOffset,e,!0),this._byteOffset+=4)}setInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt16(this._byteOffset,e,!0),this._byteOffset+=2)}setByte(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt8(this._byteOffset,e),this._byteOffset++)}}class Mk{static GLTFAsync(e,t,i){return e.whenReadyAsync().then((()=>{const s=t.replace(/\.[^/.]+$/,"");return new Rk(e,i)._generateGLTFAsync(s)}))}static _PreExportAsync(e,t){return Promise.resolve().then((()=>t&&t.exportWithoutWaitingForScene?Promise.resolve():e.whenReadyAsync()))}static _PostExportAsync(e,t,i){return Promise.resolve().then((()=>(i&&i.exportWithoutWaitingForScene,t)))}static GLBAsync(e,t,i){return this._PreExportAsync(e,i).then((()=>{const s=t.replace(/\.[^/.]+$/,"");return new Rk(e,i)._generateGLBAsync(s).then((t=>this._PostExportAsync(e,t,i)))}))}}const Ok="KHR_texture_transform";class Dk{constructor(){this.name=Ok,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportTexture(e,t,i){if(i&&(0===i.uAng&&0===i.wAng&&0===i.vAng||0===i.uRotationCenter&&0===i.vRotationCenter)){const e={};let s=!1;if(0===i.uOffset&&0===i.vOffset||(e.offset=[i.uOffset,i.vOffset],s=!0),1===i.uScale&&1===i.vScale||(e.scale=[i.uScale,i.vScale],s=!0),0!==i.wAng&&(e.rotation=-i.wAng,s=!0),0!==i.coordinatesIndex&&(e.texCoord=i.coordinatesIndex,s=!0),!s)return;this._wasUsed=!0,t.extensions||(t.extensions={}),t.extensions[Ok]=e}}preExportTextureAsync(e,t){return new Promise(((i,s)=>{t.getScene()?0!==t.uAng||0!==t.vAng?(hs.Warn(`${e}: Texture ${t.name} with rotation in the u or v axis is not supported in glTF.`),i(null)):0===t.wAng||0===t.uRotationCenter&&0===t.vRotationCenter?i(t):(hs.Warn(`${e}: Texture ${t.name} with rotation not centered at the origin cannot be exported with ${Ok}`),i(null)):s(`${e}: "scene" is not defined for Babylon texture ${t.name}!`)}))}}Rk.RegisterExtension(Ok,(()=>new Dk));const wk="KHR_lights_punctual";class Nk{constructor(e){this.name=wk,this.enabled=!0,this.required=!1,this._exporter=e}dispose(){this._lights=null}get wasUsed(){return!!this._lights}onExporting(){this._exporter._glTF.extensions[wk]=this._lights}postExportNodeAsync(e,t,i,s){return new Promise((r=>{if(t&&i instanceof am){let n;const o=i.getTypeID()==yo.LIGHTTYPEID_POINTLIGHT?"point":i.getTypeID()==yo.LIGHTTYPEID_DIRECTIONALLIGHT?"directional":i.getTypeID()==yo.LIGHTTYPEID_SPOTLIGHT?"spot":null;if(null==o)we.Warn(`${e}: Light ${i.name} is not supported in ${wk}`);else{if(i.position.equalsToFloats(0,0,0)||(t.translation=i.position.asArray()),"point"!==o){const e=i.direction,s=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),n=-Math.atan2(e.y,r),o=pe.RotationYawPitchRoll(s+Math.PI,n,0);pe.IsIdentity(o)||(t.rotation=o.asArray())}if(i.falloffType!==yo.FALLOFF_GLTF&&we.Warn(`${e}: Light falloff for ${i.name} does not match the ${wk} specification!`),n={type:o},i.diffuse.equals(Ce.White())||(n.color=i.diffuse.asArray()),1!==i.intensity&&(n.intensity=i.intensity),i.range!==Number.MAX_VALUE&&(n.range=i.range),"spot"===o){const e=i;e.angle!==Math.PI/2&&(null==n.spot&&(n.spot={}),n.spot.outerConeAngle=e.angle/2),0!==e.innerAngle&&(null==n.spot&&(n.spot={}),n.spot.innerConeAngle=e.innerAngle/2)}this._lights||(this._lights={lights:[]}),this._lights.lights.push(n);const a={light:this._lights.lights.length-1},l=i.parent;if(l&&1==l.getChildren().length){const e=this._exporter._nodes[s[l.uniqueId]];if(e){const i=de.FromArrayToRef(e.translation||[0,0,0],0,ge.Vector3[0]),s=pe.FromArrayToRef(e.rotation||[0,0,0,1],0,ge.Quaternion[0]),n=de.FromArrayToRef(e.scale||[1,1,1],0,ge.Vector3[1]),o=fe.ComposeToRef(n,s,i,ge.Matrix[0]),l=de.FromArrayToRef(t.translation||[0,0,0],0,ge.Vector3[2]),h=pe.FromArrayToRef(t.rotation||[0,0,0,1],0,ge.Quaternion[1]),c=fe.ComposeToRef(de.OneReadOnly,h,l,ge.Matrix[1]);return o.multiplyToRef(c,c),c.decompose(n,s,i),i.equalsToFloats(0,0,0)?delete e.translation:e.translation=i.asArray(),pe.IsIdentity(s)?delete e.rotation:e.rotation=s.asArray(),n.equalsToFloats(1,1,1)?delete e.scale:e.scale=n.asArray(),e.extensions||(e.extensions={}),e.extensions[wk]=a,void r(null)}}t.extensions||(t.extensions={}),t.extensions[wk]=a}}r(t)}))}}Rk.RegisterExtension(wk,(e=>new Nk(e)));const Fk="KHR_materials_clearcoat";class Bk{constructor(e){this.name=Fk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Vm&&i.clearCoat.isEnabled?(i.clearCoat.texture&&s.push(i.clearCoat.texture),!i.clearCoat.useRoughnessFromMainTexture&&i.clearCoat.textureRoughness&&s.push(i.clearCoat.textureRoughness),i.clearCoat.bumpTexture&&s.push(i.clearCoat.bumpTexture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Vm){if(!i.clearCoat.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture);let r;r=i.clearCoat.useRoughnessFromMainTexture?this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture):this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.textureRoughness),i.clearCoat.isTintEnabled&&hs.Warn(`Clear Color tint is not supported for glTF export. Ignoring for: ${i.name}`),i.clearCoat.remapF0OnInterfaceChange&&hs.Warn(`Clear Color F0 remapping is not supported for glTF export. Ignoring for: ${i.name}`);const n=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.bumpTexture),o={clearcoatFactor:i.clearCoat.intensity,clearcoatTexture:s??void 0,clearcoatRoughnessFactor:i.clearCoat.roughness,clearcoatRoughnessTexture:r??void 0,clearcoatNormalTexture:n??void 0,hasTextures:()=>null!==o.clearcoatTexture||null!==o.clearcoatRoughnessTexture||null!==o.clearcoatRoughnessTexture};t.extensions[Fk]=o}e(t)}))}}Rk.RegisterExtension(Fk,(e=>new Bk(e)));const Lk="KHR_materials_iridescence";class kk{constructor(e){this.name=Lk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Vm&&i.iridescence.isEnabled?(i.iridescence.texture&&s.push(i.iridescence.texture),i.iridescence.thicknessTexture&&i.iridescence.thicknessTexture!==i.iridescence.texture&&s.push(i.iridescence.thicknessTexture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Vm){if(!i.iridescence.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.texture),r=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.thicknessTexture),n={iridescenceFactor:i.iridescence.intensity,iridescenceIor:i.iridescence.indexOfRefraction,iridescenceThicknessMinimum:i.iridescence.minimumThickness,iridescenceThicknessMaximum:i.iridescence.maximumThickness,iridescenceTexture:s??void 0,iridescenceThicknessTexture:r??void 0,hasTextures:()=>null!==n.iridescenceTexture||null!==n.iridescenceThicknessTexture};t.extensions[Lk]=n}e(t)}))}}Rk.RegisterExtension(Lk,(e=>new kk(e)));const Vk="KHR_materials_anisotropy";class Uk{constructor(e){this.name=Vk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Vm&&i.anisotropy.isEnabled&&!i.anisotropy.legacy?(i.anisotropy.texture&&s.push(i.anisotropy.texture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Vm){if(!i.anisotropy.isEnabled||i.anisotropy.legacy)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.anisotropy.texture),r={anisotropyStrength:i.anisotropy.intensity,anisotropyRotation:i.anisotropy.angle,anisotropyTexture:s??void 0,hasTextures:()=>null!==r.anisotropyTexture};t.extensions[Vk]=r}e(t)}))}}Rk.RegisterExtension(Vk,(e=>new Uk(e)));const Gk="KHR_materials_sheen";class zk{constructor(e){this.name=Gk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){return i instanceof Um&&i.sheen.isEnabled&&i.sheen.texture?[i.sheen.texture]:[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um){if(!i.sheen.isEnabled)return void e(t);this._wasUsed=!0,null==t.extensions&&(t.extensions={});const s={sheenColorFactor:i.sheen.color.asArray(),sheenRoughnessFactor:i.sheen.roughness??0,hasTextures:()=>null!==s.sheenColorTexture||null!==s.sheenRoughnessTexture};i.sheen.texture&&(s.sheenColorTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),i.sheen.textureRoughness&&!i.sheen.useRoughnessFromMainTexture?s.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.textureRoughness)??void 0:i.sheen.texture&&i.sheen.useRoughnessFromMainTexture&&(s.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),t.extensions[Gk]=s}e(t)}))}}Rk.RegisterExtension(Gk,(e=>new zk(e)));const Wk="KHR_materials_unlit";class Hk{constructor(){this.name=Wk,this.enabled=!0,this.required=!1,this._wasUsed=!1}get wasUsed(){return this._wasUsed}dispose(){}postExportMaterialAsync(e,t,i){return new Promise((e=>{let s=!1;i instanceof Um?s=i.unlit:i instanceof yc&&(s=i.disableLighting),s&&(this._wasUsed=!0,null==t.extensions&&(t.extensions={}),t.extensions[Wk]={}),e(t)}))}}Rk.RegisterExtension(Wk,(()=>new Hk));const Xk="KHR_materials_ior";class Yk{constructor(){this.name=Xk,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){return!e.unlit&&null!=e.indexOfRefraction&&1.5!=e.indexOfRefraction}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={ior:i.indexOfRefraction};t.extensions=t.extensions||{},t.extensions[Xk]=e}e(t)}))}}Rk.RegisterExtension(Xk,(e=>new Yk));const Qk="KHR_materials_specular";class jk{constructor(e){this.name=Qk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Um&&this._isExtensionEnabled(i)?(i.metallicReflectanceTexture&&s.push(i.metallicReflectanceTexture),i.reflectanceTexture&&s.push(i.reflectanceTexture),s):s}_isExtensionEnabled(e){return!e.unlit&&(null!=e.metallicF0Factor&&1!=e.metallicF0Factor||null!=e.metallicReflectanceColor&&!e.metallicReflectanceColor.equalsFloats(1,1,1)||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.metallicReflectanceTexture||null!=e.reflectanceTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0,t.extensions=t.extensions||{};const e=this._exporter._glTFMaterialExporter._getTextureInfo(i.metallicReflectanceTexture)??void 0,s=this._exporter._glTFMaterialExporter._getTextureInfo(i.reflectanceTexture)??void 0,r={specularFactor:1==i.metallicF0Factor?void 0:i.metallicF0Factor,specularTexture:e,specularColorFactor:i.metallicReflectanceColor.equalsFloats(1,1,1)?void 0:i.metallicReflectanceColor.asArray(),specularColorTexture:s,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions[Qk]=r}e(t)}))}}Rk.RegisterExtension(Qk,(e=>new jk(e)));const Kk="KHR_materials_volume";class $k{constructor(e){this.name=Kk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Um&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isTranslucencyEnabled)&&(null!=t.maximumThickness&&0!=t.maximumThickness||null!=t.tintColorAtDistance&&t.tintColorAtDistance!=Number.POSITIVE_INFINITY||null!=t.tintColor&&t.tintColor!=Ce.White()||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.subSurface.thicknessTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={thicknessFactor:0==e.maximumThickness?void 0:e.maximumThickness,thicknessTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.thicknessTexture)??void 0,attenuationDistance:e.tintColorAtDistance==Number.POSITIVE_INFINITY?void 0:e.tintColorAtDistance,attenuationColor:e.tintColor.equalsFloats(1,1,1)?void 0:e.tintColor.asArray(),hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[Kk]=s}e(t)}))}}Rk.RegisterExtension(Kk,(e=>new $k(e)));const qk="KHR_materials_dispersion";class Zk{constructor(){this.name=qk,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isDispersionEnabled)}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={dispersion:i.subSurface.dispersion};t.extensions=t.extensions||{},t.extensions[qk]=e}e(t)}))}}Rk.RegisterExtension(qk,(()=>new Zk));const Jk="KHR_materials_transmission";class eV{constructor(e){this.name=Jk,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Um&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return t.isRefractionEnabled&&null!=t.refractionIntensity&&0!=t.refractionIntensity||this._hasTexturesExtension(e)}_hasTexturesExtension(e){return null!=e.subSurface.refractionIntensityTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Um&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={transmissionFactor:0===e.refractionIntensity?void 0:e.refractionIntensity,transmissionTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.refractionIntensityTexture)??void 0,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[Jk]=s}e(t)}))}}Rk.RegisterExtension(Jk,(e=>new eV(e)));const tV="EXT_mesh_gpu_instancing";class iV{constructor(e){this.name=tV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportNodeAsync(e,t,i,s,r){return new Promise((e=>{if(t&&i instanceof bo&&i.hasThinInstances&&r){this._wasUsed=!0;const e=de.Zero(),s=pe.Identity(),n=de.One(),o=i.thinInstanceGetWorldMatrices(),a=ge.Vector3[2],l=ge.Quaternion[1],h=ge.Vector3[3];let c=!1,u=!1,d=!1;const _=new Float32Array(3*i.thinInstanceCount),p=new Float32Array(4*i.thinInstanceCount),f=new Float32Array(3*i.thinInstanceCount);let m=0;for(const t of o)t.decompose(h,l,a),_.set(a.asArray(),3*m),p.set(l.normalize().asArray(),4*m),f.set(h.asArray(),3*m),c=c||!a.equalsWithEpsilon(e),u=u||!l.equalsWithEpsilon(s),d=d||!h.equalsWithEpsilon(n),m++;const g={attributes:{}};if(c&&(g.attributes.TRANSLATION=this._buildAccessor(_,"VEC3",i.thinInstanceCount,r,5126)),u){const e=5126;g.attributes.ROTATION=this._buildAccessor(p,"VEC4",i.thinInstanceCount,r,e)}d&&(g.attributes.SCALE=this._buildAccessor(f,"VEC3",i.thinInstanceCount,r,5126)),t.extensions=t.extensions||{},t.extensions[tV]=g}e(t)}))}_buildAccessor(e,t,i,s,r){const n=s.getByteOffset();switch(r){case 5126:for(let t=0;t!=e.length;t++)s.setFloat32(e[t]);break;case 5120:for(let t=0;t!=e.length;t++)s.setByte(127*e[t]);break;case 5122:for(let t=0;t!=e.length;t++)s.setInt16(32767*e[t])}const o={buffer:0,byteOffset:n,byteLength:e.length*ys.GetTypeByteLength(r)},a=this._exporter._bufferViews.length;this._exporter._bufferViews.push(o);const l=this._exporter._accessors.length,h={bufferView:a,componentType:r,count:i,type:t,normalized:5120==r||5122==r};return this._exporter._accessors.push(h),l}}Rk.RegisterExtension(tV,(e=>new iV(e)));const sV="KHR_materials_emissive_strength";class rV{constructor(){this.name=sV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(!(i instanceof Um))return e(t);const s=i.emissiveColor.asArray(),r=Math.max(...s);if(r>1){this._wasUsed=!0,t.extensions||(t.extensions={});const e={emissiveStrength:r},s=i.emissiveColor.scale(1/e.emissiveStrength);t.emissiveFactor=s.asArray(),t.extensions[sV]=e}return e(t)}))}}Rk.RegisterExtension(sV,(e=>new rV));class nV{static CreateSTL(e,t=!0,i="stlmesh",s=!1,r=!0,n=!1,o=!1,a=!1){const l=function(e,t,i){const s=[3*e[i],3*e[i+1],3*e[i+2]],r=[new de(t[s[0]],t[s[0]+2],t[s[0]+1]),new de(t[s[1]],t[s[1]+2],t[s[1]+1]),new de(t[s[2]],t[s[2]+2],t[s[2]+1])],n=r[0].subtract(r[1]),o=r[2].subtract(r[1]);return{v:r,n:de.Cross(o,n).normalize()}},h=function(e,t,i,s){return t=c(e,t,i.x,s),t=c(e,t,i.y,s),c(e,t,i.z,s)},c=function(e,t,i,s){return e.setFloat32(t,i,s),t+4},u=function(e){if(o){let t=e;e instanceof To&&(t=e.sourceMesh);const i=t.getVerticesData(ys.PositionKind,!0,!0);if(!i)return[];const s=de.Zero();let r;for(r=0;r"bitbybit-hdrSkyBox"!==e.name&&!e.name.includes("bitbybit-ground")}),Mk.GLBAsync(this.context.scene,e.fileName,t).then((e=>{e.downloadFiles()}))}exportMeshToStl(e){return FV(this,void 0,void 0,(function*(){const t=e.mesh.getChildMeshes();let i=[];t&&t.length>0&&(i=t.filter((e=>!(e instanceof Qu))));let s=[e.mesh,...i];return s=s.filter((e=>e.isVisible)),nV.CreateSTL(s,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}exportMeshesToStl(e){return FV(this,void 0,void 0,(function*(){let t;return e.meshes.forEach((e=>{const i=e.getChildMeshes();let s=[];i&&i.length>0&&(s=i.filter((e=>!(e instanceof Qu)))),t.push(e),s.length>0&&t.push(...s)})),nV.CreateSTL(t,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}loadAsset(e,t,i,s){return FV(this,void 0,void 0,(function*(){const e=yield Pa.ImportMeshAsync("",t,i,this.context.scene),r=this.context.scene.metadata.shadowGenerators,n=new bo("ImportedMeshContainer"+Math.random(),this.context.scene);return r.length>0&&e.meshes.forEach((e=>{if(e.isPickable=!1,s&&(e.isVisible=!1),e.getChildMeshes().forEach((e=>{e.isPickable=!1,s&&(e.isVisible=!1)})),this.context.scene.metadata.shadowGenerators.length>0){try{e.receiveShadows=!0}catch(e){}r.forEach((t=>{t.addShadowCaster(e)})),e.getChildMeshes().forEach((e=>{try{e.receiveShadows=!0}catch(e){}r.forEach((t=>{t.addShadowCaster(e)}))}))}})),e.meshes.forEach((e=>{e.parent=n})),n}))}}!function(e){e.GetAssetDto=class{constructor(e){void 0!==e&&(this.fileName=e)}},e.FileDto=class{constructor(e){void 0!==e&&(this.file=e)}},e.FilesDto=class{constructor(e){void 0!==e&&(this.files=e)}},e.AssetFileDto=class{constructor(e,t){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.hidden=t)}},e.AssetFileByUrlDto=class{constructor(e,t,i){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.rootUrl=t),void 0!==i&&(this.hidden=i)}}}(oV||(oV={})),function(e){e.ArcRotateCameraDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.radius=20,this.target=[0,0,0],this.alpha=45,this.beta=70,this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,this.maxZ=1e3,void 0!==e&&(this.radius=e),void 0!==t&&(this.alpha=t),void 0!==i&&(this.beta=i),void 0!==s&&(this.lowerBetaLimit=s),void 0!==r&&(this.upperBetaLimit=r),void 0!==n&&(this.angularSensibilityX=n),void 0!==o&&(this.angularSensibilityY=o),void 0!==a&&(this.panningSensibility=a),void 0!==l&&(this.wheelPrecision=l),void 0!==h&&(this.maxZ=h)}},e.FreeCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.TargetCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.PositionDto=class{constructor(e,t){this.position=[20,20,20],void 0!==e&&(this.camera=e),void 0!==t&&(this.position=t)}},e.SpeedDto=class{constructor(e,t){this.speed=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.speed=t)}},e.TargetDto=class{constructor(e,t){this.target=[0,0,0],void 0!==e&&(this.camera=e),void 0!==t&&(this.target=t)}},e.MinZDto=class{constructor(e,t){this.minZ=0,void 0!==e&&(this.camera=e),void 0!==t&&(this.minZ=t)}},e.MaxZDto=class{constructor(e,t){this.maxZ=1e3,void 0!==e&&(this.camera=e),void 0!==t&&(this.maxZ=t)}},e.OrthographicDto=class{constructor(e,t,i,s,r){this.orthoLeft=-1,this.orthoRight=1,this.orthoBottom=-1,this.orthoTop=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.orthoLeft=t),void 0!==i&&(this.orthoRight=i),void 0!==s&&(this.orthoTop=s),void 0!==r&&(this.orthoBottom=r)}},e.CameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}}}(aV||(aV={})),function(e){e.ExportSceneGlbDto=class{constructor(e,t){this.fileName="bitbybit-scene",this.discardSkyboxAndGrid=!1,void 0!==e&&(this.fileName=e),void 0!==t&&(this.discardSkyboxAndGrid=t)}},e.ExportSceneDto=class{constructor(e){this.fileName="bitbybit-scene",void 0!==e&&(this.fileName=e)}},e.ExportMeshToStlDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.ExportMeshesToStlDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}}}(lV||(lV={})),function(e){e.PBRMetallicRoughnessDto=class{constructor(e,t,i,s,r,n,o,a){this.name="Custom Material",this.baseColor="#0000ff",this.emissiveColor="#000000",this.metallic=.6,this.roughness=.5,this.alpha=1,this.backFaceCulling=!1,this.zOffset=0,void 0!==e&&(this.name=e),void 0!==t&&(this.baseColor=t),void 0!==i&&(this.emissiveColor=i),void 0!==s&&(this.metallic=s),void 0!==r&&(this.roughness=r),void 0!==n&&(this.alpha=n),void 0!==o&&(this.backFaceCulling=o),void 0!==a&&(this.zOffset=a)}},e.BaseColorDto=class{constructor(e,t){this.baseColor="#0000ff",void 0!==e&&(this.material=e),void 0!==t&&(this.baseColor=t)}},e.MaterialPropDto=class{constructor(e){void 0!==e&&(this.material=e)}},e.MetallicDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.metallic=t)}},e.RoughnessDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.roughness=t)}},e.AlphaDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.alpha=t)}},e.BackFaceCullingDto=class{constructor(e,t){this.backFaceCulling=!0,void 0!==e&&(this.material=e),void 0!==t&&(this.backFaceCulling=t)}},e.BaseTextureDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.baseTexture=t)}}}(hV||(hV={})),function(e){let t;!function(e){e.frontside="frontside",e.backside="backside",e.doubleside="doubleside"}(t=e.sideOrientationEnum||(e.sideOrientationEnum={})),e.UpdateDrawnBabylonMesh=class{constructor(e,t,i,s,r){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.scaling=s),void 0!==r&&(this.colours=r)}},e.SetParentDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.parentMesh=t)}},e.UpdateDrawnBabylonMeshPositionDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t)}},e.UpdateDrawnBabylonMeshRotationDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotation=t)}},e.UpdateDrawnBabylonMeshScaleDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.scale=t)}},e.IntersectsMeshDto=class{constructor(e,t,i,s){this.precise=!1,this.includeDescendants=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.babylonMesh2=t),void 0!==i&&(this.precise=i),void 0!==s&&(this.includeDescendants=s)}},e.IntersectsPointDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.point=t)}},e.BabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ShowHideMeshDto=class{constructor(e,t){this.includeChildren=!0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.includeChildren=t)}},e.CloneBabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ChildMeshesBabylonMeshDto=class{constructor(e,t){this.directDescendantsOnly=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.directDescendantsOnly=t)}},e.TranslateBabylonMeshDto=class{constructor(e,t){this.distance=0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.distance=t)}},e.NameBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.name=t),void 0!==i&&(this.includeChildren=i)}},e.ByNameBabylonMeshDto=class{constructor(e){void 0!==e&&(this.name=e)}},e.MaterialBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.material=t),void 0!==i&&(this.includeChildren=i)}},e.IdBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.id=t)}},e.ByIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.id=e)}},e.UniqueIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.uniqueId=e)}},e.PickableBabylonMeshDto=class{constructor(e,t,i){this.pickable=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.pickable=t),void 0!==i&&(this.includeChildren=i)}},e.CheckCollisionsBabylonMeshDto=class{constructor(e,t,i){this.checkCollisions=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.checkCollisions=t),void 0!==i&&(this.includeChildren=i)}},e.RotateBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotate=t)}},e.SetMeshVisibilityDto=class{constructor(e,t,i){this.visibility=0,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.visibility=t),void 0!==i&&(this.includeChildren=i)}},e.MeshInstanceAndTransformDto=class{constructor(e,t,i,s){void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.scaling=s)}},e.MeshInstanceDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,s){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}}}(cV||(cV={})),function(e){e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.PickInfo=class{constructor(e){void 0!==e&&(this.pickInfo=e)}}}(uV||(uV={})),function(e){e.BaseRayDto=class{constructor(e,t,i){void 0!==e&&(this.origin=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.length=i)}},e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.FromToDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.to=t)}}}(dV||(dV={})),function(e){e.CreateBoxDto=class{constructor(e,t,i,s){this.width=1,this.depth=1,this.height=1,this.sideOrientation=cV.sideOrientationEnum.frontside,void 0!==e&&(this.width=e),void 0!==t&&(this.depth=t),void 0!==i&&(this.height=i),void 0!==s&&(this.sideOrientation=s)}},e.CreateCubeDto=class{constructor(e,t){this.size=1,this.sideOrientation=cV.sideOrientationEnum.frontside,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t)}},e.CreateSquarePlaneDto=class{constructor(e,t){this.size=1,this.sideOrientation=cV.sideOrientationEnum.frontside,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t)}},e.CreateRectanglePlaneDto=class{constructor(e,t,i){this.width=1,this.height=1,this.sideOrientation=cV.sideOrientationEnum.frontside,void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.sideOrientation=i)}}}(_V||(_V={})),function(e){let t;!function(e){e.nearest="nearest",e.bilinear="bilinear",e.trilinear="trilinear"}(t=e.samplingModeEnum||(e.samplingModeEnum={})),e.TextureSimpleDto=class{constructor(t,i,s,r,n,o,a,l,h,c){this.name="Custom Texture",this.invertY=!1,this.invertZ=!1,this.wAng=0,this.uScale=1,this.vScale=1,this.uOffset=0,this.vOffset=0,this.samplingMode=e.samplingModeEnum.nearest,void 0!==t&&(this.name=t),void 0!==i&&(this.url=i),void 0!==s&&(this.invertY=s),void 0!==r&&(this.invertZ=r),void 0!==n&&(this.wAng=n),void 0!==o&&(this.uScale=o),void 0!==a&&(this.vScale=a),void 0!==l&&(this.uOffset=l),void 0!==h&&(this.vOffset=h),void 0!==c&&(this.samplingMode=c)}}}(pV||(pV={})),function(e){e.DefaultWebXRWithTeleportationDto=class{constructor(e){void 0!==e&&(this.groundMeshes=e)}}}(fV||(fV={})),function(e){e.HexDto=class{constructor(e){this.color="#0000ff",void 0!==e&&(this.color=e)}},e.HexDtoMapped=class{constructor(e,t,i){this.color="#0000ff",this.from=0,this.to=255,void 0!==e&&(this.color=e),void 0!==t&&(this.from=t),void 0!==i&&(this.to=i)}},e.RGBDto=class{constructor(e,t,i){this.r=255,this.g=255,this.b=255,void 0!==e&&(this.r=e),void 0!==t&&(this.g=t),void 0!==i&&(this.b=i)}},e.RGBObjectDto=class{constructor(e){void 0!==e&&(this.rgb=e)}}}(mV||(mV={})),function(e){let t;e.DrawAny=class{constructor(e,t,i){void 0!==e&&(this.entity=e),void 0!==t&&(this.options=t),void 0!==i&&(this.babylonMesh=i)}},e.SceneDrawGridMeshDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.width=400,this.height=400,this.subdivisions=10,this.majorUnitFrequency=10,this.minorUnitVisibility=.45,this.gridRatio=.5,this.opacity=.5,this.backFaceCulling=!1,this.mainColor="#ffffff",this.secondaryColor="#ffffff",void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.subdivisions=i),void 0!==s&&(this.majorUnitFrequency=s),void 0!==r&&(this.minorUnitVisibility=r),void 0!==n&&(this.gridRatio=n),void 0!==o&&(this.opacity=o),void 0!==a&&(this.backFaceCulling=a),void 0!==l&&(this.mainColor=l),void 0!==h&&(this.secondaryColor=h)}},e.DrawBasicGeometryOptions=class{constructor(e,t,i,s,r){this.colours="#ff0000",this.size=.1,this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.colours=e),void 0!==t&&(this.size=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r)}},e.DrawNodeOptions=class{constructor(e,t,i,s){this.colorX="#0000ff",this.colorY="#00ff00",this.colorZ="#ff0000",this.size=2,void 0!==e&&(this.colorX=e),void 0!==t&&(this.colorY=t),void 0!==i&&(this.colorZ=i),void 0!==s&&(this.size=s)}},e.DrawOcctShapeOptions=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.vertexColour="#ffaaff",this.edgeWidth=2,this.vertexSize=.03,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.faceOpacity=e),void 0!==t&&(this.edgeOpacity=t),void 0!==i&&(this.edgeColour=i),void 0!==s&&(this.faceMaterial=s),void 0!==r&&(this.faceColour=r),void 0!==h&&(this.vertexColour=h),void 0!==c&&(this.vertexSize=c),void 0!==n&&(this.edgeWidth=n),void 0!==o&&(this.drawEdges=o),void 0!==a&&(this.drawFaces=a),void 0!==l&&(this.drawVertices=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdgeIndexes=d),void 0!==_&&(this.edgeIndexHeight=_),void 0!==p&&(this.edgeIndexColour=p),void 0!==f&&(this.drawFaceIndexes=f),void 0!==m&&(this.faceIndexHeight=m),void 0!==g&&(this.faceIndexColour=g)}},e.DrawOcctShapeSimpleOptions=class{constructor(e,t,i,s,r,n){this.precision=.01,this.drawFaces=!0,this.faceColour="#ff0000",this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.drawFaces=t),void 0!==i&&(this.faceColour=i),void 0!==s&&(this.drawEdges=s),void 0!==r&&(this.edgeColour=r),void 0!==n&&(this.edgeWidth=n)}},e.DrawOcctShapeMaterialOptions=class{constructor(e,t,i,s,r){this.precision=.01,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.faceMaterial=t),void 0!==i&&(this.drawEdges=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.edgeWidth=r)}},function(e){e[e.point=0]="point",e[e.points=1]="points",e[e.line=2]="line",e[e.lines=3]="lines",e[e.node=4]="node",e[e.nodes=5]="nodes",e[e.polyline=6]="polyline",e[e.polylines=7]="polylines",e[e.verbCurve=8]="verbCurve",e[e.verbCurves=9]="verbCurves",e[e.verbSurface=10]="verbSurface",e[e.verbSurfaces=11]="verbSurfaces",e[e.jscadMesh=12]="jscadMesh",e[e.jscadMeshes=13]="jscadMeshes",e[e.occt=14]="occt",e[e.tag=15]="tag",e[e.tags=16]="tags"}(t=e.drawingTypes||(e.drawingTypes={}))}(gV||(gV={})),function(e){let t,i;!function(e){e.edge="edge",e.round="round",e.chamfer="chamfer"}(t=e.solidCornerTypeEnum||(e.solidCornerTypeEnum={})),function(e){e.left="left",e.center="center",e.right="right"}(i=e.jscadTextAlignEnum||(e.jscadTextAlignEnum={})),e.DrawSolidMeshDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.mesh=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawSolidMeshesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.meshes=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawPathDto=class{constructor(e,t,i,s,r,n){this.colour="#444444",this.opacity=1,this.width=10,this.updatable=!1,void 0!==e&&(this.path=e),void 0!==t&&(this.colour=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.width=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pathMesh=n)}},e.TransformSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.transformation=t)}},e.TransformSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.DownloadSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.DownloadGeometryDto=class{constructor(e,t){void 0!==e&&(this.geometry=e),void 0!==t&&(this.fileName=t)}},e.DownloadSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}},e.ColorizeDto=class{constructor(e,t){this.color="#0000ff",void 0!==e&&(this.geometry=e),void 0!==t&&(this.color=t)}},e.BooleanObjectsDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.BooleanTwoObjectsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.BooleanObjectsFromDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.meshes=t)}},e.ExpansionDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.OffsetDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.ExtrudeLinearDto=class{constructor(e,t,i,s){this.height=1,this.twistAngle=90,this.twistSteps=15,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.twistAngle=i),void 0!==s&&(this.twistSteps=s)}},e.HullDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.ExtrudeRectangularDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRectangularPointsDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.points=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRotateDto=class{constructor(e,t,i,s){this.angle=90,this.startAngle=0,this.segments=24,void 0!==e&&(this.polygon=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.startAngle=i),void 0!==s&&(this.segments=s)}},e.PathDto=class{constructor(e){void 0!==e&&(this.path=e)}},e.PathFromPointsDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.PathsFromPointsDto=class{constructor(e){void 0!==e&&(this.pointsLists=e)}},e.PathFromPolylineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.closed=t)}},e.PathAppendCurveDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.path=t)}},e.PathAppendPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.path=t)}},e.PathAppendPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.path=t)}},e.PathAppendArcDto=class{constructor(e,t,i,s,r,n,o,a){this.endPoint=[1,1],this.xAxisRotation=90,this.clockwise=!0,this.large=!1,this.segments=24,this.radiusX=1,this.radiusY=1,void 0!==e&&(this.path=e),void 0!==t&&(this.endPoint=t),void 0!==i&&(this.xAxisRotation=i),void 0!==s&&(this.clockwise=s),void 0!==r&&(this.large=r),void 0!==n&&(this.segments=n),void 0!==o&&(this.radiusX=o),void 0!==a&&(this.radiusY=a)}},e.CircleDto=class{constructor(e,t,i){this.center=[0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipseDto=class{constructor(e,t,i){this.center=[0,0],this.radius=[1,2],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SquareDto=class{constructor(e,t){this.center=[0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.RectangleDto=class{constructor(e,t,i){this.center=[0,0],this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i)}},e.RoundedRectangleDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.roundRadius=.2,this.segments=24,this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.segments=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r)}},e.StarDto=class{constructor(e,t,i,s,r,n){this.center=[0,0],this.vertices=10,this.density=1,this.outerRadius=2,this.innerRadius=1,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.vertices=t),void 0!==i&&(this.density=i),void 0!==s&&(this.outerRadius=s),void 0!==r&&(this.innerRadius=r),void 0!==n&&(this.startAngle=n)}},e.CubeDto=class{constructor(e,t){this.center=[0,0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CubeCentersDto=class{constructor(e,t){this.size=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.size=t)}},e.CuboidDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.width=1,this.length=1,this.height=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.CuboidCentersDto=class{constructor(e,t,i,s){this.width=1,this.length=1,this.height=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.RoundedCuboidDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.roundRadius=1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.RoundedCuboidCentersDto=class{constructor(e,t,i,s,r,n){this.roundRadius=.1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.CylidnerEllipticDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerCentersEllipticDto=class{constructor(e,t,i,s,r){this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.EllipsoidDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipsoidCentersDto=class{constructor(e,t,i){this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.GeodesicSphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.frequency=12,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.GeodesicSphereCentersDto=class{constructor(e,t,i){this.radius=1,this.frequency=12,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.CylidnerCentersDto=class{constructor(e,t,i,s){this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerCentersDto=class{constructor(e,t,i,s,r){this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.SphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SphereCentersDto=class{constructor(e,t,i){this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.TorusDto=class{constructor(e,t,i,s,r,n,o,a){this.center=[0,0,0],this.innerRadius=1,this.outerRadius=2,this.innerSegments=24,this.outerSegments=24,this.innerRotation=0,this.outerRotation=360,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.outerRadius=i),void 0!==s&&(this.innerSegments=s),void 0!==r&&(this.outerSegments=r),void 0!==n&&(this.innerRotation=n),void 0!==o&&(this.outerRotation=o),void 0!==a&&(this.startAngle=a)}},e.TextDto=class{constructor(e,t,s,r,n,o,a,l,h){this.text="Hello World",this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.segments=t),void 0!==s&&(this.xOffset=s),void 0!==r&&(this.yOffset=r),void 0!==n&&(this.height=n),void 0!==o&&(this.lineSpacing=o),void 0!==a&&(this.letterSpacing=a),void 0!==l&&(this.align=l),void 0!==h&&(this.extrudeOffset=h)}},e.CylinderTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c,u){this.text="Hello World",this.extrusionHeight=.5,this.extrusionSize=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.extrusionHeight=t),void 0!==s&&(this.extrusionSize=s),void 0!==r&&(this.segments=r),void 0!==n&&(this.xOffset=n),void 0!==o&&(this.yOffset=o),void 0!==a&&(this.height=a),void 0!==l&&(this.lineSpacing=l),void 0!==h&&(this.letterSpacing=h),void 0!==c&&(this.align=c),void 0!==u&&(this.extrudeOffset=u)}},e.SphereTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c){this.text="Hello World",this.radius=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.radius=t),void 0!==s&&(this.segments=s),void 0!==r&&(this.xOffset=r),void 0!==n&&(this.yOffset=n),void 0!==o&&(this.height=o),void 0!==a&&(this.lineSpacing=a),void 0!==l&&(this.letterSpacing=l),void 0!==h&&(this.align=h),void 0!==c&&(this.extrudeOffset=c)}},e.FromPolygonPoints=class{constructor(e){void 0!==e&&(this.polygonPoints=e)}}}(vV||(vV={})),function(e){e.StringifyDto=class{constructor(e){void 0!==e&&(this.json=e)}},e.ParseDto=class{constructor(e){void 0!==e&&(this.text=e)}},e.QueryDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.SetValueDto=class{constructor(e,t,i){void 0!==e&&(this.json=e),void 0!==t&&(this.value=t),void 0!==i&&(this.path=i)}},e.SetValuesOnPathsDto=class{constructor(e,t,i){void 0!==e&&(this.json=e),void 0!==t&&(this.values=t),void 0!==i&&(this.paths=i)}},e.PathsDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.JsonDto=class{constructor(e){void 0!==e&&(this.json=e)}}}(xV||(xV={})),function(e){e.LinePointsDto=class{constructor(e,t){void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LineStartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoints=e),void 0!==t&&(this.endPoints=t)}},e.DrawLineDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.line=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.lineMesh=n)}},e.DrawLinesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.linesMesh=n)}},e.PointsLinesDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.LineDto=class{constructor(e){void 0!==e&&(this.line=e)}},e.LinesDto=class{constructor(e){void 0!==e&&(this.lines=e)}},e.PointOnLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.param=t)}},e.TransformLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.transformation=t)}},e.TransformsLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}},e.TransformLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}}}(bV||(bV={})),function(e){let t;!function(e){e.first="first",e.last="last"}(t=e.firstLastEnum||(e.firstLastEnum={})),e.ListItemDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.SubListDto=class{constructor(e,t,i,s){this.indexStart=0,this.indexEnd=1,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.indexStart=t),void 0!==i&&(this.indexEnd=i),void 0!==s&&(this.clone=s)}},e.ListDto=class{constructor(e,t){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t)}},e.GroupListDto=class{constructor(e,t,i){this.nrElements=2,this.keepRemainder=!1,void 0!==e&&(this.list=e),void 0!==t&&(this.nrElements=t),void 0!==i&&(this.keepRemainder=i)}},e.MultiplyItemDto=class{constructor(e,t){void 0!==e&&(this.item=e),void 0!==t&&(this.times=t)}},e.AddItemAtIndexDto=class{constructor(e,t,i,s){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.index=i),void 0!==s&&(this.clone=s)}},e.AddItemAtIndexesDto=class{constructor(e,t,i,s){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.indexes=i),void 0!==s&&(this.clone=s)}},e.AddItemsAtIndexesDto=class{constructor(e,t,i,s){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.items=t),void 0!==i&&(this.indexes=i),void 0!==s&&(this.clone=s)}},e.RemoveItemAtIndexDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.RemoveNthItemDto=class{constructor(e,t,i,s){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==s&&(this.clone=s)}},e.GetByPatternDto=class{constructor(e,t){this.pattern=[!0,!0,!1],void 0!==e&&(this.list=e),void 0!==t&&(this.pattern=t)}},e.GetNthItemDto=class{constructor(e,t,i,s){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==s&&(this.clone=s)}},e.GetLongestListLength=class{constructor(e){void 0!==e&&(this.lists=e)}},e.MergeElementsOfLists=class{constructor(e,t){this.level=0,void 0!==e&&(this.lists=e),void 0!==t&&(this.level=t)}},e.AddItemFirstLastDto=class{constructor(e,i,s,r){this.position=t.last,this.clone=!0,void 0!==e&&(this.list=e),void 0!==i&&(this.item=i),void 0!==s&&(this.position=s),void 0!==r&&(this.clone=r)}}}(TV||(TV={})),function(e){let t;!function(e){e.less="<",e.lessOrEqual="<=",e.greater=">",e.greaterOrEqual=">=",e.tripleEqual="===",e.tripleNotEqual="!==",e.equal="==",e.notEqual="!="}(t=e.BooleanOperatorsEnum||(e.BooleanOperatorsEnum={})),e.ComparisonDto=class{constructor(e,t,i){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operator=i)}},e.BooleanDto=class{constructor(e){this.boolean=!1,void 0!==e&&(this.boolean=e)}},e.BooleanListDto=class{constructor(e){void 0!==e&&(this.booleans=e)}},e.ValueGateDto=class{constructor(e,t){this.boolean=!1,void 0!==e&&(this.value=e),void 0!==t&&(this.boolean=t)}},e.TwoValueGateDto=class{constructor(e,t){void 0!==e&&(this.value1=e),void 0!==t&&(this.value2=t)}},e.RandomBooleansDto=class{constructor(e){this.length=10,void 0!==e&&(this.length=e)}},e.TwoThresholdRandomGradientDto=class{},e.ThresholdBooleanListDto=class{},e.ThresholdGapsBooleanListDto=class{}}(yV||(yV={})),function(e){let t,i;!function(e){e.add="add",e.subtract="subtract",e.multiply="multiply",e.divide="divide",e.power="power",e.modulus="modulus"}(t=e.mathTwoNrOperatorEnum||(e.mathTwoNrOperatorEnum={})),function(e){e.absolute="absolute",e.negate="negate",e.ln="ln",e.log10="log10",e.tenPow="tenPow",e.round="round",e.floor="floor",e.ceil="ceil",e.sqrt="sqrt",e.sin="sin",e.cos="cos",e.tan="tan",e.asin="asin",e.acos="acos",e.atan="atan",e.log="log",e.exp="exp",e.radToDeg="radToDeg",e.degToRad="degToRad"}(i=e.mathOneNrOperatorEnum||(e.mathOneNrOperatorEnum={})),e.NumberDto=class{constructor(e){this.number=0,void 0!==e&&(this.number=e)}},e.ModulusDto=class{constructor(e,t){this.number=1,this.modulus=2,void 0!==e&&(this.number=e),void 0!==t&&(this.modulus=t)}},e.RoundToDecimalsDto=class{constructor(e,t){this.number=1.123456,this.decimalPlaces=2,void 0!==e&&(this.number=e),void 0!==t&&(this.decimalPlaces=t)}},e.ActionOnTwoNumbersDto=class{constructor(e,t,i){this.first=1,this.second=1,void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operation=i)}},e.ActionOnOneNumberDto=class{constructor(e,t){this.number=1,void 0!==e&&(this.number=e),void 0!==t&&(this.operation=t)}},e.RemapNumberDto=class{constructor(e,t,i,s,r){this.number=.5,this.fromLow=0,this.fromHigh=1,this.toLow=1,this.toHigh=2,void 0!==e&&(this.number=e),void 0!==t&&(this.fromLow=t),void 0!==i&&(this.fromHigh=i),void 0!==s&&(this.toLow=s),void 0!==r&&(this.toHigh=r)}},e.RandomNumberDto=class{constructor(e,t){this.low=0,this.high=1,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t)}},e.RandomNumbersDto=class{constructor(e,t,i){this.low=0,this.high=1,this.count=10,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t),void 0!==i&&(this.count=i)}}}(SV||(SV={})),function(e){e.NodeDto=class{constructor(e){void 0!==e&&(this.node=e)}},e.NodeTranslationDto=class{constructor(e,t,i){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.distance=i)}},e.NodeParentDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.parentNode=t)}},e.NodeDirectionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t)}},e.NodePositionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.position=t)}},e.RotateNodeDto=class{constructor(e,t,i){this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,s){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}},e.CreateNodeFromRotationDto=class{constructor(e,t,i){this.origin=[0,0,0],this.rotation=[0,0,0],void 0!==e&&(this.parent=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.rotation=i)}},e.DrawNodeDto=class{constructor(e,t,i,s,r){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.node=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==s&&(this.colorZ=s),void 0!==r&&(this.size=r)}},e.DrawNodesDto=class{constructor(e,t,i,s,r){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.nodes=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==s&&(this.colorZ=s),void 0!==r&&(this.size=r)}}}(CV||(CV={})),function(e){e.PointDto=class{constructor(e){void 0!==e&&(this.point=e)}},e.PointXYZDto=class{constructor(e,t,i){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.PointXYDto=class{constructor(e,t){this.x=0,this.y=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.DrawPointDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.size=3,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.point=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==s&&(this.colours=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pointMesh=n)}},e.DrawPointsDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.size=.1,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==s&&(this.colours=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pointsMesh=n)}},e.TransformPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.transformation=t)}},e.TransformPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.TransformsForPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.ClosestPointFromPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.point=t)}},e.StartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoint=t)}},e.StartEndPointsListDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoints=t)}},e.MultiplyPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.amountOfPoints=t)}},e.SpiralDto=class{constructor(e,t,i,s,r){this.phi=.9,this.numberPoints=200,this.widening=3,this.radius=6,this.factor=1,void 0!==e&&(this.radius=e),void 0!==t&&(this.numberPoints=t),void 0!==i&&(this.widening=i),void 0!==s&&(this.factor=s),void 0!==r&&(this.phi=r)}},e.HexGridCentersDto=class{constructor(e,t,i,s,r){this.nrHexagonsY=21,this.nrHexagonsX=21,this.orientOnCenter=!1,this.pointsOnGround=!1,void 0!==e&&(this.nrHexagonsX=e),void 0!==t&&(this.nrHexagonsY=t),void 0!==i&&(this.radiusHexagon=i),void 0!==s&&(this.orientOnCenter=s),void 0!==r&&(this.pointsOnGround=r)}}}(EV||(EV={})),function(e){e.PolylinePropertiesDto=class{constructor(e,t){this.isClosed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.isClosed=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.polyline=e)}},e.PolylinesDto=class{constructor(e){void 0!==e&&(this.polylines=e)}},e.TransformPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.transformation=t)}},e.DrawPolylineDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.polylineMesh=n)}},e.DrawPolylinesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.polylinesMesh=n)}}}(AV||(AV={})),function(e){let t,i;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={})),function(e){e.none="none",e.exponential="exponential",e.exponentialSquared="exponentialSquared",e.linear="linear"}(i=e.fogModeEnum||(e.fogModeEnum={}))}(PV||(PV={})),function(e){e.SceneBackgroundColourDto=class{constructor(e){this.colour="#ffffff",void 0!==e&&(this.colour=e)}},e.SceneDto=class{constructor(e){void 0!==e&&(this.scene=e)}},e.EnablePhysicsDto=class{constructor(e){this.vector=[0,-9.81,0],void 0!==e&&(this.vector=e)}},e.PointLightDto=class{constructor(e,t,i,s,r,n,o,a){this.position=[0,0,0],this.intensity=2e3,this.diffuse="#ffffff",this.specular="#ffffff",this.radius=.1,this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,void 0!==e&&(this.position=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==s&&(this.specular=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.shadowGeneratorMapSize=n),void 0!==o&&(this.enableShadows=o),void 0!==a&&(this.shadowDarkness=a)}},e.ActiveCameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}},e.UseRightHandedSystemDto=class{constructor(e){this.use=!0,void 0!==e&&(this.use=e)}},e.DirectionalLightDto=class{constructor(e,t,i,s,r,n,o){this.direction=[-100,-100,-100],this.intensity=.5,this.diffuse="#ffffff",this.specular="#ffffff",this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,void 0!==e&&(this.direction=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==s&&(this.specular=s),void 0!==r&&(this.shadowGeneratorMapSize=r),void 0!==n&&(this.enableShadows=n),void 0!==o&&(this.shadowDarkness=o)}},e.CameraConfigurationDto=class{constructor(e,t,i,s,r,n,o,a,l){this.position=[10,10,10],this.lookAt=[0,0,0],this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.maxZ=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,void 0!==e&&(this.position=e),void 0!==t&&(this.lookAt=t),void 0!==i&&(this.lowerBetaLimit=i),void 0!==s&&(this.upperBetaLimit=s),void 0!==r&&(this.angularSensibilityX=r),void 0!==n&&(this.angularSensibilityY=n),void 0!==o&&(this.maxZ=o),void 0!==a&&(this.panningSensibility=a),void 0!==l&&(this.wheelPrecision=l)}},e.SkyboxDto=class{constructor(e,t,i,s){this.skybox=PV.skyboxEnum.clearSky,this.size=1e3,this.blur=.1,this.environmentIntensity=.7,void 0!==e&&(this.skybox=e),void 0!==t&&(this.size=t),void 0!==i&&(this.blur=i),void 0!==s&&(this.environmentIntensity=s)}},e.PointerDto=class{},e.FogDto=class{constructor(e,t,i,s,r){this.color="#ffffff",this.density=.1,void 0!==e&&(this.mode=e),void 0!==t&&(this.color=t),void 0!==i&&(this.density=i),void 0!==s&&(this.start=s),void 0!==r&&(this.end=r)}}}(RV||(RV={})),function(e){e.DrawTagDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tag=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagVariable=i)}},e.DrawTagsDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tags=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagsVariable=i)}},e.TagDto=class{constructor(e,t,i,s,r,n,o){this.position=[0,0,0],this.colour="#444444",this.size=12,this.adaptDepth=!1,void 0!==e&&(this.text=e),void 0!==t&&(this.position=t),void 0!==i&&(this.colour=i),void 0!==s&&(this.size=s),void 0!==r&&(this.adaptDepth=r),void 0!==n&&(this.needsUpdate=n),void 0!==o&&(this.id=o)}}}(IV||(IV={})),function(e){e.TextDto=class{constructor(e){this.text="Hello World",void 0!==e&&(this.text=e)}},e.TextSplitDto=class{constructor(e,t){this.text="a,b,c",this.separator=",",void 0!==e&&(this.text=e),void 0!==t&&(this.separator=t)}},e.TextReplaceDto=class{constructor(e,t,i){this.text="a-c",this.search="-",this.replaceWith="b",void 0!==e&&(this.text=e),void 0!==t&&(this.search=t),void 0!==i&&(this.replaceWith=i)}},e.TextJoinDto=class{constructor(e,t){this.separator=",",void 0!==e&&(this.list=e),void 0!==t&&(this.separator=t)}},e.ToStringDto=class{constructor(e){void 0!==e&&(this.item=e)}},e.ToStringEachDto=class{constructor(e){void 0!==e&&(this.list=e)}}}(MV||(MV={})),function(e){e.PostFromIframe=class{constructor(e,t){void 0!==e&&(this.data=e),void 0!==t&&(this.targetOrigin=t)}}}(OV||(OV={})),function(e){e.RotationCenterAxisDto=class{constructor(e,t,i){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.center=i)}},e.TransformBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.RotationCenterDto=class{constructor(e,t){this.angle=90,this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.center=t)}},e.RotationCenterYawPitchRollDto=class{constructor(e,t,i,s){this.yaw=0,this.pitch=0,this.roll=0,this.center=[0,0,0],void 0!==e&&(this.yaw=e),void 0!==t&&(this.pitch=t),void 0!==i&&(this.roll=i),void 0!==s&&(this.center=s)}},e.ScaleXYZDto=class{constructor(e){this.scaleXyz=[1,1,1],void 0!==e&&(this.scaleXyz=e)}},e.ScaleCenterXYZDto=class{constructor(e,t){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.center=e),void 0!==t&&(this.scaleXyz=t)}},e.UniformScaleDto=class{constructor(e){this.scale=1,void 0!==e&&(this.scale=e)}},e.UniformScaleFromCenterDto=class{constructor(e,t){this.scale=1,this.center=[0,0,0],void 0!==e&&(this.scale=e),void 0!==t&&(this.center=t)}},e.TranslationXYZDto=class{constructor(e){this.translation=[0,0,0],void 0!==e&&(this.translation=e)}},e.TranslationsXYZDto=class{constructor(e){void 0!==e&&(this.translations=e)}}}(DV||(DV={})),function(e){e.TwoVectorsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.VectorBoolDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.VectorDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.RangeMaxDto=class{constructor(e){void 0!==e&&(this.max=e)}},e.VectorXYZDto=class{constructor(e,t,i){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.VectorXYDto=class{constructor(e,t){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.SpanDto=class{constructor(e,t,i){this.step=.1,this.min=0,this.max=1,void 0!==e&&(this.step=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i)}},e.RayPointDto=class{constructor(e,t,i){void 0!==e&&(this.point=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.vector=i)}},e.VectorsDto=class{constructor(e){void 0!==e&&(this.vectors=e)}},e.FractionTwoVectorsDto=class{constructor(e,t,i){this.fraction=.5,void 0!==e&&(this.fraction=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}},e.VectorScalarDto=class{constructor(e,t){void 0!==e&&(this.scalar=e),void 0!==t&&(this.vector=t)}},e.TwoVectorsReferenceDto=class{constructor(e,t,i){void 0!==e&&(this.reference=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}}}(wV||(wV={})),function(e){e.CurveDto=class{constructor(e){void 0!==e&&(this.curve=e)}},e.CurvesDto=class{constructor(e){void 0!==e&&(this.curves=e)}},e.ClosestPointDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.point=t)}},e.ClosestPointsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.points=t)}},e.BezierCurveDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t)}},e.DrawCurveDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curve=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.curveMesh=n)}},e.CurveParameterDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t)}},e.CurvesParameterDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.parameter=t)}},e.CurveTransformDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.transformation=t)}},e.CurvesTransformDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.transformation=t)}},e.CurveToleranceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.tolerance=t)}},e.CurveLengthToleranceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t),void 0!==i&&(this.tolerance=i)}},e.CurveDerivativesDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.numDerivatives=i)}},e.CurveSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.subdivision=t)}},e.CurvesSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.subdivision=t)}},e.CurvesDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.length=t)}},e.CurveDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t)}},e.DrawCurvesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curves=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.curvesMesh=n)}},e.CurveNurbsDataDto=class{constructor(e,t,i,s){void 0!==e&&(this.degree=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.knots=i),void 0!==s&&(this.points=s)}},e.CurvePathDataDto=class{constructor(e,t){void 0!==e&&(this.degree=e),void 0!==t&&(this.points=t)}},e.EllipseDto=class{constructor(e){void 0!==e&&(this.ellipse=e)}},e.CircleDto=class{constructor(e){void 0!==e&&(this.circle=e)}},e.ArcDto=class{constructor(e){void 0!==e&&(this.arc=e)}},e.EllipseParametersDto=class{constructor(e,t,i){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.center=i)}},e.CircleParametersDto=class{constructor(e,t,i,s){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.center=s)}},e.ArcParametersDto=class{constructor(e,t,i,s,r,n){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==s&&(this.yAxis=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.center=n)}},e.EllipseArcParametersDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==s&&(this.yAxis=s),void 0!==r&&(this.center=r)}},e.SurfaceDto=class{constructor(e){void 0!==e&&(this.surface=e)}},e.SurfaceTransformDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.transformation=t)}},e.SurfaceParameterDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.useV=i)}},e.IsocurvesParametersDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameters=t),void 0!==i&&(this.useV=i)}},e.IsocurveSubdivisionDto=class{constructor(e,t,i,s,r){this.useV=!1,this.includeLast=!0,this.includeFirst=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.useV=t),void 0!==i&&(this.includeLast=i),void 0!==s&&(this.includeFirst=s),void 0!==r&&(this.isocurveSegments=r)}},e.DerivativesDto=class{constructor(e,t,i,s){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i),void 0!==s&&(this.numDerivatives=s)}},e.SurfaceLocationDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i)}},e.CornersDto=class{constructor(e,t,i,s){void 0!==e&&(this.point1=e),void 0!==t&&(this.point2=t),void 0!==i&&(this.point3=i),void 0!==s&&(this.point4=s)}},e.SurfaceParamDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.point=t)}},e.KnotsControlPointsWeightsDto=class{constructor(e,t,i,s,r,n){void 0!==e&&(this.degreeU=e),void 0!==t&&(this.degreeV=t),void 0!==i&&(this.knotsU=i),void 0!==s&&(this.knotsV=s),void 0!==r&&(this.points=r),void 0!==n&&(this.weights=n)}},e.LoftCurvesDto=class{constructor(e,t){void 0!==e&&(this.degreeV=e),void 0!==t&&(this.curves=t)}},e.DrawSurfaceDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surface=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfaceMesh=n)}},e.DrawSurfacesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfacesMesh=n)}},e.DrawSurfacesColoursDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.colours=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfacesMesh=n)}},e.ConeAndCylinderParametersDto=class{constructor(e,t,i,s,r){this.axis=[0,1,0],this.xAxis=[1,0,0],this.base=[0,0,0],this.height=2,this.radius=1,void 0!==e&&(this.axis=e),void 0!==t&&(this.xAxis=t),void 0!==i&&(this.base=i),void 0!==s&&(this.height=s),void 0!==r&&(this.radius=r)}},e.ConeDto=class{constructor(e){void 0!==e&&(this.cone=e)}},e.CylinderDto=class{constructor(e){void 0!==e&&(this.cylinder=e)}},e.ExtrusionParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.direction=t)}},e.ExtrusionDto=class{constructor(e){void 0!==e&&(this.extrusion=e)}},e.SphericalParametersDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.SphereDto=class{constructor(e){void 0!==e&&(this.sphere=e)}},e.RevolutionParametersDto=class{constructor(e,t,i,s){void 0!==e&&(this.profile=e),void 0!==t&&(this.center=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}},e.RevolutionDto=class{constructor(e){void 0!==e&&(this.revolution=e)}},e.SweepParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.rail=t)}},e.SweepDto=class{constructor(e){void 0!==e&&(this.sweep=e)}},e.CurveCurveDto=class{constructor(e,t,i){void 0!==e&&(this.firstCurve=e),void 0!==t&&(this.secondCurve=t),void 0!==i&&(this.tolerance=i)}},e.CurveSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t),void 0!==i&&(this.tolerance=i)}},e.SurfaceSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.firstSurface=e),void 0!==t&&(this.secondSurface=t),void 0!==i&&(this.tolerance=i)}},e.CurveCurveIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}},e.CurveSurfaceIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}}}(NV||(NV={}));class LV{constructor(e){this.context=e}dispose(e){e.babylonMesh&&(e.babylonMesh.getScene().removeMesh(e.babylonMesh,!0),e.babylonMesh.dispose())}updateDrawn(e){const t=e.babylonMesh.metadata.type;e.babylonMesh.position=new de(e.position[0],e.position[1],e.position[2]),e.babylonMesh.rotation=new de(e.rotation[0],e.rotation[1],e.rotation[2]),e.babylonMesh.scaling=new de(e.scaling[0],e.scaling[1],e.scaling[2]);const i=Array.isArray(e.colours);let s;if(e.babylonMesh.getChildMeshes&&(s=e.babylonMesh.getChildMeshes()),s&&s.length>0)i&&e.colours.length===s.length?s.forEach(((t,i)=>{const s=Ce.FromHexString(e.colours[i]);this.assignColorToMesh(t,s)})):i?s.forEach((t=>{const i=Ce.FromHexString(e.colours[0]);this.assignColorToMesh(t,i)})):s.forEach((t=>{const i=Ce.FromHexString(e.colours);this.assignColorToMesh(t,i)}));else{const t=i?Ce.FromHexString(e.colours[0]):Ce.FromHexString(e.colours);this.assignColorToMesh(e.babylonMesh,t)}if(null!==e.babylonMesh.edgesRenderer){const t=i?Ce.FromHexString(e.colours[0]):Ce.FromHexString(e.colours);e.babylonMesh.edgesColor=Ee.FromColor3(t)}if([gV.drawingTypes.point,gV.drawingTypes.points,gV.drawingTypes.line,gV.drawingTypes.lines,gV.drawingTypes.polyline,gV.drawingTypes.polylines].includes(t)){const t=e.babylonMesh.getVerticesData(ys.ColorKind).length/4,s=[];if(i&&t===e.colours.length)for(let i=0;i{t.visibility=e.visibility}))}hide(e){e.babylonMesh.isVisible=!1,e.includeChildren&&e.babylonMesh.getChildMeshes&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!1}))}show(e){e.babylonMesh.isVisible=!0,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!0}))}setParent(e){e.babylonMesh.parent=e.parentMesh}getParent(e){return e.babylonMesh.parent}setCheckCollisions(e){e.babylonMesh.checkCollisions=e.checkCollisions,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.checkCollisions=e.checkCollisions}))}getCheckCollisions(e){return e.babylonMesh.checkCollisions}setPickable(e){e.babylonMesh.isPickable=e.pickable,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.isPickable=e.pickable}))}getPickable(e){return e.babylonMesh.isPickable}getMeshesWhereNameContains(e){return this.context.scene.meshes.filter((t=>t.name.includes(e.name)))}getChildMeshes(e){return e.babylonMesh.getChildMeshes(e.directDescendantsOnly)}getMeshesOfId(e){return this.context.scene.getMeshesById(e.id)}getMeshOfId(e){return this.context.scene.getMeshById(e.id)}getMeshOfUniqueId(e){return this.context.scene.getMeshByUniqueId(e.uniqueId)}clone(e){var t,i;const s=e.babylonMesh.clone(),r=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;return r.length>0&&(s.getChildMeshes().forEach((e=>{e.receiveShadows=!0,r.forEach((t=>t.addShadowCaster(e)))})),s.receiveShadows=!0,r.forEach((e=>e.addShadowCaster(s)))),s}setId(e){e.babylonMesh.id=e.id}getId(e){return e.babylonMesh.id}getUniqueId(e){return e.babylonMesh.uniqueId}setName(e){e.babylonMesh.name=e.name,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.name=e.name}))}getVerticesAsPolygonPoints(e){const t=e.babylonMesh.getVerticesData(ys.PositionKind),i=e.babylonMesh.getIndices(),s=[];for(let e=0;e{t.material=e.material}))}getMaterial(e){return e.babylonMesh.material}getPosition(e){const t=e.babylonMesh;return[t.position.x,t.position.y,t.position.z]}getAbsolutePosition(e){const t=e.babylonMesh;return[t.absolutePosition.x,t.absolutePosition.y,t.absolutePosition.z]}getRotation(e){const t=e.babylonMesh;return[t.rotation.x,t.rotation.y,t.rotation.z]}getScale(e){const t=e.babylonMesh;return[t.scaling.x,t.scaling.y,t.scaling.z]}moveForward(e){const t=e.babylonMesh;t.translate(t.forward,e.distance,lr.WORLD)}moveBackward(e){const t=e.babylonMesh;t.translate(t.forward.negate(),e.distance,lr.WORLD)}moveUp(e){const t=e.babylonMesh;t.translate(t.up,e.distance,lr.WORLD)}moveDown(e){const t=e.babylonMesh;t.translate(t.up.negate(),e.distance,lr.WORLD)}moveRight(e){const t=e.babylonMesh;t.translate(t.right,e.distance,lr.WORLD)}moveLeft(e){const t=e.babylonMesh;t.translate(t.right.negate(),e.distance,lr.WORLD)}yaw(e){const t=e.babylonMesh,i=vr.FromDegrees(e.rotate).radians();t.rotate(_r.Y,i,lr.LOCAL)}pitch(e){const t=e.babylonMesh,i=vr.FromDegrees(e.rotate).radians();t.rotate(_r.X,i,lr.LOCAL)}roll(e){const t=e.babylonMesh,i=vr.FromDegrees(e.rotate).radians();t.rotate(_r.Z,i,lr.LOCAL)}rotateAroundAxisWithPosition(e){e.mesh.rotateAround(new de(e.position[0],e.position[1],e.position[2]),new de(e.axis[0],e.axis[1],e.axis[2]),vr.FromDegrees(e.angle).radians())}setPosition(e){e.babylonMesh.position=new de(e.position[0],e.position[1],e.position[2])}setRotation(e){const t=vr.FromDegrees(e.rotation[0]).radians(),i=vr.FromDegrees(e.rotation[1]).radians(),s=vr.FromDegrees(e.rotation[2]).radians();e.babylonMesh.rotation=new de(t,i,s)}setScale(e){e.babylonMesh.scaling=new de(e.scale[0],e.scale[1],e.scale[2])}intersectsMesh(e){return e.babylonMesh.intersectsMesh(e.babylonMesh2,e.precise,e.includeDescendants)}intersectsPoint(e){const t=new de(e.point[0],e.point[1],e.point[2]);return e.babylonMesh.intersectsPoint(t)}createMeshInstanceAndTransformNoReturn(e){this.createMeshInstanceAndTransform(e)}createMeshInstanceAndTransform(e){var t,i;const s=new bo("instanceContainer"+Math.random(),this.context.scene),r=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0)e.mesh.getChildMeshes(!1).forEach((t=>{const i=t.getTotalVertices();if(t.createInstance&&i>0){t.disableEdgesRendering();const i=t.createInstance(`InstanceMesh${Math.random()}`);i.position=new de(e.position[0],e.position[1],e.position[2]),i.rotation=new de(e.rotation[0],e.rotation[1],e.rotation[2]),i.scaling=new de(e.scaling[0],e.scaling[1],e.scaling[2]),r.length>0&&r.forEach((e=>{e.addShadowCaster(i)})),i.parent=s}})),e.mesh.isVisible=!1;else if(e.mesh){e.mesh.isVisible=!1;const t=e.mesh.createInstance(`InstanceMesh${Math.random()}`);t.position=new de(e.position[0],e.position[1],e.position[2]),t.rotation=new de(vr.FromDegrees(e.rotation[0]).radians(),vr.FromDegrees(e.rotation[1]).radians(),vr.FromDegrees(e.rotation[2]).radians()),t.scaling=new de(e.scaling[0],e.scaling[1],e.scaling[2]),t.parent=s,r.length>0&&r.forEach((e=>{e.addShadowCaster(t)}))}return s}createMeshInstance(e){let t;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0){e.mesh.setParent(null);const i=new bo("meshCloneContainer"+Math.random());e.mesh.getChildMeshes(!1).forEach((e=>{e.createInstance&&e.getTotalVertices()>0&&e.getTotalIndices()>0&&(e.createInstance(`InstanceMesh${Math.random()}`).parent=i)})),t=i;const s=this.context.scene.metadata.shadowGenerators;s.length>0&&(t.getChildMeshes().forEach((e=>{s.forEach((t=>t.addShadowCaster(e)))})),s.forEach((e=>e.addShadowCaster(t))))}else if(e.mesh&&(e.mesh.setParent(null),e.mesh.getTotalVertices()>0)){const i=new bo("meshCloneContainer"+Math.random());e.mesh.createInstance(`InstanceMesh${Math.random()}`).parent=i,t=i}return t}getSideOrientation(e){switch(e){case cV.sideOrientationEnum.frontside:return bo.FRONTSIDE;case cV.sideOrientationEnum.backside:return bo.BACKSIDE;case cV.sideOrientationEnum.doubleside:return bo.DOUBLESIDE;default:return bo.FRONTSIDE}}assignColorToMesh(e,t){const i=e.material;i instanceof zv?i.baseColor=t:i instanceof yc&&(i.diffuseColor=t)}}class kV{constructor(e,t){this.context=e,this.mesh=t}createBox(e){const t=Gd.CreateBox("BabylonMesh"+Math.random(),{width:e.width,height:e.height,depth:e.depth,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createCube(e){const t=Gd.CreateBox("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createSquarePlane(e){const t=Gd.CreatePlane("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createRectanglePlane(e){const t=Gd.CreatePlane("BabylonMesh"+Math.random(),{width:e.width,height:e.height,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}enableShadows(e){this.context.scene.metadata.shadowGenerators&&(e.receiveShadows=!0,this.context.scene.metadata.shadowGenerators.forEach((t=>{t.addShadowCaster(e)})))}}class VV{constructor(e,t){this.context=e,this.geometryHelper=t}drawNode(e){this.geometryHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=e.node}drawNodes(e){e.nodes.forEach((t=>{this.geometryHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=t}))}createNodeFromRotation(e){const t=new xn(`node${Math.random()}`,this.context.scene);return e.parent&&(t.parent=e.parent),t.position=new de(e.origin[0],e.origin[1],e.origin[2]),t.rotation=new de(vr.FromDegrees(e.rotation[0]).radians(),vr.FromDegrees(e.rotation[1]).radians(),vr.FromDegrees(e.rotation[2]).radians()),t}createWorldNode(){const e=new xn(`root${Math.random()}`,this.context.scene);return e.parent=this.context.scene.getTransformNodeByID("root"),e}getAbsoluteForwardVector(e){const t=e.node.forward;return[t.x,t.y,t.z]}getAbsoluteRightVector(e){const t=e.node.right;return[t.x,t.y,t.z]}getAbsoluteUpVector(e){const t=e.node.up;return[t.x,t.y,t.z]}getAbsolutePosition(e){const t=e.node.getAbsolutePosition();return[t.x,t.y,t.z]}getAbsoluteRotationTransformation(e){const t=new fe;return e.node.absoluteRotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getRotationTransformation(e){const t=new fe;return e.node.rotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getChildren(e){return e.node.getChildren()}getParent(e){return e.node.parent}getPositionExpressedInLocalSpace(e){const t=e.node.getPositionExpressedInLocalSpace();return[t.x,t.y,t.z]}getRootNode(){return this.context.scene.getTransformNodeByID("root")}getRotation(e){const t=e.node.rotation;return[vr.FromRadians(t.x).degrees(),vr.FromRadians(t.y).degrees(),vr.FromRadians(t.z).degrees()]}rotateAroundAxisWithPosition(e){e.node.rotateAround(new de(e.position[0],e.position[1],e.position[2]),new de(e.axis[0],e.axis[1],e.axis[2]),vr.FromDegrees(e.angle).radians())}rotate(e){e.node.rotate(new de(e.axis[0],e.axis[1],e.axis[2]),vr.FromDegrees(e.angle).radians())}setAbsolutePosition(e){e.node.setAbsolutePosition(new de(e.position[0],e.position[1],e.position[2]))}setDirection(e){e.node.setDirection(new de(e.direction[0],e.direction[1],e.direction[2]))}setParent(e){e.node.setParent(e.parentNode)}translate(e){e.node.translate(new de(e.direction[0],e.direction[1],e.direction[2]),e.distance)}}class UV{constructor(e){this.context=e}pickWithRay(e){return this.context.scene.pickWithRay(e.ray)}pickWithPickingRay(){const e=this.context.scene,t=e.createPickingRay(e.pointerX,e.pointerY,fe.Identity(),this.context.scene.activeCamera,!1);return e.pickWithRay(t)}getDistance(e){return e.pickInfo.distance}getPickedMesh(e){return e.pickInfo.pickedMesh}getPickedPoint(e){const t=e.pickInfo.pickedPoint;return[t.x,t.y,t.z]}hit(e){return e.pickInfo.hit}getSubMeshId(e){return e.pickInfo.subMeshId}getSubMeshFaceId(e){return e.pickInfo.subMeshFaceId}getBU(e){return e.pickInfo.bu}getBV(e){return e.pickInfo.bv}getPickedSprite(e){return e.pickInfo.pickedSprite}}class GV{constructor(e){this.context=e}createPickingRay(){const e=this.context.scene;return e.createPickingRay(e.pointerX,e.pointerY,fe.Identity(),this.context.scene.activeCamera,!1)}createRay(e){const t=new de(e.origin[0],e.origin[1],e.origin[2]),i=new de(e.direction[0],e.direction[1],e.direction[2]);let s;return 0!==e.length&&(s=e.length),new Zo(t,i,s)}createRayFromTo(e){const t=new de(e.from[0],e.from[1],e.from[2]),i=new de(e.to[0],e.to[1],e.to[2]);return Zo.CreateNewFromTo(t,i)}getOrigin(e){const t=e.ray.origin;return[t.x,t.y,t.z]}getDirection(e){const t=e.ray.direction;return[t.x,t.y,t.z]}getLength(e){return e.ray.length}}class zV{constructor(e){this.context=e}getScene(){return this.context.scene}setAndAttachScene(e){return e.scene.metadata={shadowGenerators:[]},new xn("root",this.context.scene),this.context.scene=e.scene}backgroundColour(e){this.context.scene.clearColor=Ee.FromColor3(Ce.FromHexString(e.colour))}activateCamera(e){this.context.scene.activeCamera.detachControl(),this.context.scene.activeCamera=e.camera}useRightHandedSystem(e){this.context.scene.useRightHandedSystem=e.use,this.context.scene.activeCamera.getViewMatrix(!0),this.context.scene.activeCamera.getProjectionMatrix(!0)}drawPointLightNoReturn(e){this.drawPointLight(e)}getShadowGenerators(){return this.context.scene.metadata&&this.context.scene.metadata.shadowGenerators?this.context.scene.metadata.shadowGenerators:[]}drawPointLight(e){const t=new de(e.position[0],e.position[1],e.position[2]),i=new ov(`pointLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new Kg(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=!0,t.contactHardeningLightSizeUVRatio=.2,t.bias=1e-4,t.normalBias=.002,i.shadowMaxZ=1e3,i.shadowMinZ=.01,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}if(i.diffuse=Ce.FromHexString(e.diffuse),i.specular=Ce.FromHexString(e.specular),i.intensityMode=yo.INTENSITYMODE_LUMINOUSPOWER,i.intensity=e.intensity,e.radius>0){const t=Gd.CreateSphere(`PointLightSphere${Math.random()}`,{diameter:2*e.radius},this.context.scene),s=new yc(`LightMaterial${Math.random()}`,this.context.scene);s.diffuseColor=i.diffuse,s.specularColor=i.diffuse,s.emissiveColor=i.diffuse,t.material=s,t.parent=i}return i}drawDirectionalLightNoReturn(e){this.drawDirectionalLight(e)}drawDirectionalLight(e){const t=new de(e.direction[0],e.direction[1],e.direction[2]),i=new lm(`directionalLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new Kg(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=!0,t.contactHardeningLightSizeUVRatio=.2,t.bias=1e-4,t.normalBias=.002,i.shadowMaxZ=1e3,i.shadowMinZ=0,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}return i.diffuse=Ce.FromHexString(e.diffuse),i.specular=Ce.FromHexString(e.specular),i.intensity=e.intensity,i.shadowMaxZ=1e3,i}getActiveCamera(){return this.context.scene.activeCamera}adjustActiveArcRotateCamera(e){const t=this.context.scene.getCameraByName("Camera");t.position=new de(e.position[0],e.position[1],e.position[2]),t.target=new de(e.lookAt[0],e.lookAt[1],e.lookAt[2]);const i=de.Distance(t.position,t.target);t.radius=i,void 0!==e.lowerBetaLimit&&(t.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(t.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.angularSensibilityX&&(t.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(t.angularSensibilityY=e.angularSensibilityY),void 0!==e.panningSensibility&&(t.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(t.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(t.maxZ=e.maxZ)}clearAllDrawn(){const e=this.context.scene;if(e&&(e.environmentTexture&&e.environmentTexture.dispose(),e.environmentTexture=null,e.fogMode=dr.FOGMODE_NONE,e.meshes.forEach((e=>e.dispose())),e.meshes=[],e.materials.forEach((e=>e.dispose())),e.textures.forEach((e=>e.dispose())),e.materials=[],e.textures=[],e.useRightHandedSystem=!1,e.geometries.forEach((e=>{e.meshes&&e.meshes.forEach((e=>e.dispose())),e.dispose&&e.dispose()})),e.geometries=[],e.lights.forEach((e=>{"HemiLight"!==e.name&&e.dispose()})),e.lights=e.lights.filter((e=>"HemiLight"===e.name)),e.transformNodes&&e.transformNodes.forEach((e=>{e&&"root"!==e.name&&e.dispose()})),e.metadata&&(e.metadata.shadowGenerators.length>0&&(e.metadata.shadowGenerators.forEach((e=>e.dispose())),e.metadata.shadowGenerators=[]),e.metadata.xr&&e.metadata.xr.dispose(),e.metadata.guiManager&&e.metadata.guiManager.dispose()),e.transformNodes=[e.getTransformNodeByName("root")],e.activeCamera&&"Camera"!==e.activeCamera.name)){e.cameras.forEach((e=>e.dispose()));const t=new Th("Camera",0,10,10,new de(0,0,0),e);t.lowerRadiusLimit=0,e.setActiveCameraByName(t.name),t.setPosition(new de(0,10,20));const i=document.getElementById("renderCanvas");t.attachControl(i,!0),t.minZ=0}}enableSkybox(e){let t;e.skybox===PV.skyboxEnum.default?t=new mm("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.9/textures/skybox/default_skybox/skybox",this.context.scene):e.skybox===PV.skyboxEnum.clearSky?t=mm.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.9/textures/skybox/clear_sky/environment.env",this.context.scene,!1,!1):e.skybox===PV.skyboxEnum.city&&(t=mm.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.9/textures/skybox/city/environmentSpecular.env",this.context.scene,!1,!1)),this.context.scene.createDefaultSkybox(t,!0,e.size,e.blur,!0).name="bitbybit-hdrSkyBox",this.context.scene.environmentIntensity=e.environmentIntensity}onPointerDown(e){this.context.scene.onPointerDown=e.statement_update}onPointerUp(e){this.context.scene.onPointerUp=e.statement_update}onPointerMove(e){this.context.scene.onPointerMove=e.statement_update}fog(e){switch(e.mode){case PV.fogModeEnum.none:this.context.scene.fogMode=0;break;case PV.fogModeEnum.exponential:this.context.scene.fogMode=1;break;case PV.fogModeEnum.exponentialSquared:this.context.scene.fogMode=2;break;case PV.fogModeEnum.linear:this.context.scene.fogMode=3}this.context.scene.fogDensity=e.density,this.context.scene.fogStart=e.start,this.context.scene.fogEnd=e.end,this.context.scene.fogColor=Ce.FromHexString(e.color)}enablePhysics(e){this.context.scene.enablePhysics(new de(e.vector[0],e.vector[1],e.vector[2]),this.context.havokPlugin)}getRadians(e){let t=vr.FromDegrees(e).radians();return e<0&&(t=-t),t}}class WV{constructor(e){this.context=e}createSimple(e){const t=new Vo(e.url,this.context.scene,void 0,e.invertY,this.getSamplingMode(e.samplingMode));return t.uScale=e.uScale,t.vScale=e.vScale,t.wAng=e.wAng,t.invertZ=e.invertZ,t.uOffset=e.uOffset,t.vOffset=e.vOffset,t}getSamplingMode(e){switch(e){case pV.samplingModeEnum.nearest:return Vo.NEAREST_SAMPLINGMODE;case pV.samplingModeEnum.bilinear:return Vo.BILINEAR_SAMPLINGMODE;case pV.samplingModeEnum.trilinear:return Vo.TRILINEAR_SAMPLINGMODE;default:return Vo.NEAREST_SAMPLINGMODE}}}class HV{rotationCenterAxis(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationAxis(new de(e.axis[0],e.axis[1],e.axis[2]),vr.FromDegrees(e.angle).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterX(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationX(vr.FromDegrees(e.angle).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterY(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationY(vr.FromDegrees(e.angle).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterZ(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationZ(vr.FromDegrees(e.angle).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterYawPitchRoll(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.RotationYawPitchRoll(vr.FromDegrees(e.yaw).radians(),vr.FromDegrees(e.pitch).radians(),vr.FromDegrees(e.roll).radians()).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}scaleCenterXYZ(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}scaleXYZ(e){return[[...fe.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).toArray()]]}uniformScale(e){return[[...fe.Scaling(e.scale,e.scale,e.scale).toArray()]]}uniformScaleFromCenter(e){return[[...fe.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...fe.Scaling(e.scale,e.scale,e.scale).toArray()],[...fe.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}translationXYZ(e){return[[...fe.Translation(e.translation[0],e.translation[1],e.translation[2]).toArray()]]}translationsXYZ(e){return e.translations.map((e=>[[...fe.Translation(e[0],e[1],e[2]).toArray()]]))}}class XV{constructor(e,t,i){this.mesh=new LV(e),this.camera=new _k(e),this.node=new VV(e,t),this.scene=new zV(e),this.webxr=new vk(e),this.transforms=new HV,this.io=new BV(e),this.ray=new GV(e),this.pick=new UV(e),this.material=new fk(e,i),this.texture=new WV(e),this.meshBuilder=new kV(e,this.mesh),this.engine=new xk(e)}}var YV=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class QV{constructor(e){this.jscadWorkerManager=e}intersect(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.intersect",e)}))}subtract(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtract",e)}))}union(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.union",e)}))}intersectTwo(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.intersectTwo",e)}))}subtractTwo(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtractTwo",e)}))}unionTwo(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.unionTwo",e)}))}subtractFrom(e){return YV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtractFrom",e)}))}}var jV=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class KV{constructor(e){this.jscadWorkerManager=e}expand(e){return jV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("expansions.expand",e)}))}offset(e){return jV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("expansions.offset",e)}))}}var $V=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class qV{constructor(e){this.jscadWorkerManager=e}extrudeLinear(e){return $V(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeLinear",e)}))}extrudeRectangular(e){return $V(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRectangular",e)}))}extrudeRectangularPoints(e){return $V(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRectangularPoints",e)}))}extrudeRotate(e){return $V(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRotate",e)}))}}var ZV=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class JV{constructor(e){this.jscadWorkerManager=e}hullChain(e){return ZV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("hulls.hullChain",e)}))}hull(e){return ZV(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("hulls.hullChain",e)}))}}var eU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class tU{constructor(e){this.jscadWorkerManager=e}createFromPoints(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createFromPoints",e)}))}createPathsFromPoints(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createPathsFromPoints",e)}))}createFromPolyline(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createFromPolyline",e)}))}createEmpty(){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createEmpty",{})}))}close(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.close",e)}))}appendPoints(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendPoints",e)}))}appendPolyline(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendPolyline",e)}))}appendArc(e){return eU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendArc",e)}))}}var iU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class sU{constructor(e){this.jscadWorkerManager=e}createFromPoints(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPoints",e)}))}createFromPolyline(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPolyline",e)}))}createFromCurve(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromCurve",e)}))}createFromPath(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPath",e)}))}circle(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.circle",e)}))}ellipse(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.ellipse",e)}))}rectangle(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.rectangle",e)}))}roundedRectangle(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.roundedRectangle",e)}))}square(e){return iU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.square",e)}))}star(e){return iU(this,void 0,void 0,(function*(){return yield this.jscadWorkerManager.genericCallToWorkerPromise("polygon.star",e)}))}}var rU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class nU{constructor(e){this.jscadWorkerManager=e}cube(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cube",e)}))}cubesOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cubesOnCenterPoints",e)}))}cuboid(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cuboid",e)}))}cuboidsOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cuboidsOnCenterPoints",e)}))}cylinderElliptic(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinderElliptic",e)}))}cylinderEllipticOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinderEllipticOnCenterPoints",e)}))}cylinder(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinder",e)}))}cylindersOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylindersOnCenterPoints",e)}))}ellipsoid(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.ellipsoid",e)}))}ellipsoidsOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.ellipsoidsOnCenterPoints",e)}))}geodesicSphere(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.geodesicSphere",e)}))}geodesicSpheresOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.geodesicSpheresOnCenterPoints",e)}))}roundedCuboid(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCuboid",e)}))}roundedCuboidsOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCuboidsOnCenterPoints",e)}))}roundedCylinder(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCylinder",e)}))}roundedCylindersOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCylindersOnCenterPoints",e)}))}sphere(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.sphere",e)}))}spheresOnCenterPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.spheresOnCenterPoints",e)}))}torus(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.torus",e)}))}fromPolygonPoints(e){return rU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.fromPolygonPoints",e)}))}}var oU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class aU{constructor(e){this.jscadWorkerManager=e}cylindricalText(e){return oU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.cylindricalText",e)}))}sphericalText(e){return oU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.sphericalText",e)}))}createVectorText(e){return oU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.createVectorText",e)}))}}class lU{constructor(e){this.jscadWorkerManager=e}colorize(e){return t=this,i=void 0,r=function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("colors.colorize",e)},new((s=void 0)||(s=Promise))((function(e,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,a)}l((r=r.apply(t,i||[])).next())}));var t,i,s,r}}var hU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class cU{constructor(e,t,i){this.jscadWorkerManager=e,this.context=t,this.geometryHelper=i,this.booleans=new QV(e),this.expansions=new KV(e),this.extrusions=new qV(e),this.hulls=new JV(e),this.path=new tU(e),this.polygon=new sU(e),this.shapes=new nU(e),this.text=new aU(e),this.colors=new lU(e)}drawSolidOrPolygonMesh(e){return hU(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);let i,s;i=e.jscadMesh&&e.updatable?e.jscadMesh:new bo(`jscadMesh${Math.random()}`,this.context.scene),s=e.mesh.color&&e.mesh.color.length>0?Ce.FromArray(e.mesh.color).toHexString():Array.isArray(e.colours)?e.colours[0]:e.colours;const r=this.makeMesh(Object.assign(Object.assign({},e),{colour:s}),i,t);return e.jscadMesh=r,r}))}makeMesh(e,t,i){this.createMesh(i.positions,i.indices,i.normals,t,i.transforms,e.updatable),t.material=new zv(`jscadMaterial${Math.random()}`,this.context.scene),t.flipFaces(!1);const s=t.material;return s.baseColor=Ce.FromHexString(e.colour),s.metallic=1,s.roughness=.6,s.alpha=e.opacity,s.alphaMode=1,s.backFaceCulling=!0,s.zOffset=0,t.isPickable=!1,e.hidden&&(t.isVisible=!1),t}drawSolidOrPolygonMeshes(e){return hU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e).then((t=>{let i;e.jscadMesh&&e.updatable?(i=e.jscadMesh,i.getChildMeshes().forEach((e=>{e.dispose(),i.removeChild(e)}))):i=new bo("local_origin"+Math.random(),this.context.scene),i.isVisible=!1;const s=Array.isArray(e.colours)&&e.colours.length===t.length,r=Array.isArray(e.colours);return t.map(((t,n)=>{const o=new bo(`jscadMesh${Math.random()}`,this.context.scene);let a;a=t.color?Ce.FromArray(t.color).toHexString():s?e.colours[n]:r?e.colours[0]:e.colours,this.makeMesh(Object.assign(Object.assign({},e),{colour:a}),o,t).parent=i})),e.jscadMesh=i,i}))}))}drawPath(e){return hU(this,void 0,void 0,(function*(){return new Promise((t=>{if(e.path.points&&e.path.isClosed){const t=e.path.points[0];e.path.points.push([t[0],0,t[1]])}let i=e.colour;e.path.color&&(i=Ce.FromArray(e.path.color).toHexString()),t(this.geometryHelper.drawPolyline(e.pathMesh,e.path.points,e.updatable,e.width,e.opacity,i))}))}))}transformSolids(e){return hU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("transformSolids",e)}))}transformSolid(e){return hU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("transformSolid",e)}))}downloadSolidSTL(e){return hU(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadSolidSTL",e);this.downloadFile(t.blob,e.fileName,"stl")}))}downloadSolidsSTL(e){return hU(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadSolidsSTL",e);this.downloadFile(t.blob,e.fileName,"stl")}))}downloadGeometryDxf(e){return hU(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadGeometryDxf",e);this.downloadFile(t.blob,e.fileName,"dxf")}))}downloadFile(e,t,i){const s=URL.createObjectURL(e),r=document.createElement("a");r.href=s,r.target="_self",r.download=t+"."+i,r.click(),r.remove()}createMesh(e,t,i,s,r,n){const o=new cn;o.positions=e,o.indices=t,cn.ComputeNormals(e,t,i,{useRightHandedSystem:!0}),o.normals=i,o.applyToMesh(s,n),s.setPreTransformMatrix(fe.FromArray(r))}}var uU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class dU extends tL{constructor(e,t,i){super(e),this.occWorkerManager=e,this.context=t,this.geometryHelper=i}loadSTEPorIGES(e){return this.context.getFile(e.assetFile).then((t=>this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new rk.LoadStepOrIgesDto(t,e.assetFile.name,e.adjustZtoY))))}loadSTEPorIGESFromText(e){return this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new rk.LoadStepOrIgesDto(e.text,`fake.${e.fileType}`,e.adjustZtoY))}saveShapeStl(e){return uU(this,void 0,void 0,(function*(){this.saveStl(e)}))}saveShapeStlAndReturn(e){return uU(this,void 0,void 0,(function*(){return this.saveStl(e)}))}saveStl(e){return uU(this,void 0,void 0,(function*(){const t=new rk.DrawShapeDto;t.drawEdges=!1,t.shape=e.shape,t.precision=e.precision;const i=(yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",t)).faceList.map((e=>this.geometryHelper.createOrUpdateSurfaceMesh({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes},void 0,!1,void 0,!0,!1)));let s;return e.fileName.includes(".stl")&&(e.fileName=e.fileName.replace(".stl","")),s=document&&e.tryDownload?nV.CreateSTL(i,!0,e.fileName,e.binary,!0,!0):nV.CreateSTL(i,!1,e.fileName,e.binary,!0,!0),i.forEach((e=>e.dispose())),s}))}}var _U,pU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class fU extends bL{constructor(e,t,i,s,r){super(t),this.context=e,this.occWorkerManager=t,this.geometryHelper=i,this.solidText=s,this.vector=r,this.usedMaterials=[],this.io=new dU(t,e,i)}drawShape(e){return pU(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);return this.handleDecomposedMesh(e,i,t)}))}drawShapes(e){return pU(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e),s=yield Promise.all(i.map((i=>pU(this,void 0,void 0,(function*(){return this.handleDecomposedMesh(e,i,t)}))))),r=new bo("shapesMeshContainer"+Math.random(),this.context.scene);return s.forEach((e=>{e.parent=r})),r}))}handleDecomposedMesh(e,t,i){return pU(this,void 0,void 0,(function*(){const s=new bo("brepMesh"+Math.random(),this.context.scene);let r;if(s.isVisible=!1,e.drawFaces&&t&&t.faceList&&t.faceList.length){let n;if(i.faceMaterial)n=i.faceMaterial;else{const t=Array.isArray(e.faceColour)?e.faceColour[0]:e.faceColour,i=e.faceOpacity,s=e.drawEdges?2:0,r=this.usedMaterials.find((e=>e.sceneId===this.context.scene.uid&&e.hex===t&&e.alpha===i&&e.zOffset===s));if(this.usedMaterials=this.usedMaterials.filter((e=>e.sceneId===this.context.scene.uid)),r)n=r.material;else{const e=new zv("pbr"+Math.random(),this.context.scene);e.baseColor=Ce.FromHexString(t),e.metallic=1,e.roughness=.6,e.alpha=i,e.alphaMode=1,e.backFaceCulling=!0,e.doubleSided=!1,e.zOffset=s,this.usedMaterials.push({sceneId:this.context.scene.uid,hex:t,alpha:i,zOffset:s,material:e}),n=e}}const o=t.faceList.map((e=>({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes,uvs:e.uvs})));this.geometryHelper.createOrUpdateSurfacesMesh(o,r,!1,n,!0,!1).parent=s}if(e.drawEdges&&t&&t.edgeList&&t.edgeList.length){const i=[];t.edgeList.forEach((e=>{const t=e.vertex_coord.filter((e=>void 0!==e));i.push(t)})),this.geometryHelper.drawPolylines(r,i,!1,e.edgeWidth,e.edgeOpacity,e.edgeColour).parent=s}if(e.drawVertices&&t&&t.pointsList&&t.pointsList.length&&(this.geometryHelper.drawPoints({pointsMesh:r,points:t.pointsList,opacity:1,size:e.vertexSize,colours:e.vertexColour,updatable:!1}).parent=s),e.drawEdgeIndexes){const i=t.edgeList.map((t=>pU(this,void 0,void 0,(function*(){const i=this.computeEdgeMiddlePos(t),s=new vV.TextDto;return s.text=`${t.edge_index+1}`,s.height=e.edgeIndexHeight,s.lineSpacing=1.5,(yield this.solidText.createVectorText(s)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),r=yield Promise.all(i),n=this.geometryHelper.drawPolylines(null,r.flat(),!1,.2,1,e.edgeIndexColour);n.parent=s,n.material.zOffset=-2}if(e.drawFaceIndexes){const i=t.faceList.map((t=>pU(this,void 0,void 0,(function*(){const i=this.computeFaceMiddlePos(t.vertex_coord_vec),s=new vV.TextDto;return s.text=`${t.face_index}`,s.height=e.faceIndexHeight,s.lineSpacing=1.5,(yield this.solidText.createVectorText(s)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),r=yield Promise.all(i),n=this.geometryHelper.drawPolylines(null,r.flat(),!1,.2,1,e.faceIndexColour);n.parent=s,e.drawEdges&&(n.material.zOffset=-2)}return s}))}computeFaceMiddlePos(e){let t=0,i=0,s=0,r=0;return e.forEach((e=>{t+=e[0],i+=e[1],s+=e[2],r++})),[t/r,i/r,s/r]}computeEdgeMiddlePos(e){let t;if(2===e.vertex_coord.length){const i=e.vertex_coord[0],s=e.vertex_coord[1];t=this.vector.lerp({first:i,second:s,fraction:.5})}else if(3===e.vertex_coord.length)t=e.vertex_coord[1];else{const i=e.vertex_coord[Math.floor(e.vertex_coord.length/2)],s=e.vertex_coord[Math.floor(e.vertex_coord.length/2+1)];t=this.vector.lerp({first:i,second:s,fraction:.5})}return t}}class mU{constructor(e){this.context=e}createCircle(e){return new this.context.verb.geom.Circle(e.center,e.xAxis,e.yAxis,e.radius)}createArc(e){return new this.context.verb.geom.Arc(e.center,e.xAxis,e.yAxis,e.radius,vr.FromDegrees(e.minAngle).radians(),vr.FromDegrees(e.maxAngle).radians())}center(e){return e.circle.center()}radius(e){return e.circle.radius()}maxAngle(e){return vr.FromRadians(e.circle.maxAngle()).degrees()}minAngle(e){return vr.FromRadians(e.circle.minAngle()).degrees()}xAxis(e){return e.circle.xaxis()}yAxis(e){return e.circle.yaxis()}}class gU{constructor(e){this.context=e}createEllipse(e){return new this.context.verb.geom.Ellipse(e.center,e.xAxis,e.yAxis)}createArc(e){return new this.context.verb.geom.EllipseArc(e.center,e.xAxis,e.yAxis,vr.FromDegrees(e.minAngle).radians(),vr.FromDegrees(e.maxAngle).radians())}center(e){return e.ellipse.center()}maxAngle(e){return vr.FromRadians(e.ellipse.maxAngle()).degrees()}minAngle(e){return vr.FromRadians(e.ellipse.minAngle()).degrees()}xAxis(e){return e.ellipse.xaxis()}yAxis(e){return e.ellipse.yaxis()}}class vU{constructor(e,t){this.context=e,this.geometryHelper=t,this.circle=new mU(e),this.ellipse=new gU(e)}drawCurve(e){const t=e.curve.tessellate();return this.geometryHelper.drawPolyline(e.curveMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawCurves(e){const t=e.curves.map((e=>e.tessellate()));return this.geometryHelper.drawPolylines(e.curvesMesh,t,e.updatable,e.size,e.opacity,e.colours)}createCurveByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.degree,e.knots,e.points,e.weights)}createCurveByPoints(e){return this.context.verb.geom.NurbsCurve.byPoints(e.points,e.degree)}createBezierCurve(e){return new this.context.verb.geom.BezierCurve(e.points,e.weights)}clone(e){return e.curve.clone()}closestParam(e){return e.curve.closestParam(e.point)}closestParams(e){return e.points.map((t=>e.curve.closestParam(t)))}closestPoint(e){return e.curve.closestPoint(e.point)}closestPoints(e){return e.points.map((t=>e.curve.closestPoint(t)))}controlPoints(e){return e.curve.controlPoints()}degree(e){return e.curve.degree()}derivatives(e){return e.curve.derivatives(e.parameter,e.numDerivatives)}divideByEqualArcLengthToParams(e){return e.curve.divideByEqualArcLength(e.subdivision).map((e=>e.u))}divideByEqualArcLengthToPoints(e){return e.curve.divideByEqualArcLength(e.subdivision).map((t=>e.curve.point(t.u)))}divideByArcLengthToParams(e){return e.curve.divideByArcLength(e.length).map((e=>e.u))}divideByArcLengthToPoints(e){return e.curve.divideByArcLength(e.length).map((t=>e.curve.point(t.u)))}divideCurvesByEqualArcLengthToPoints(e){return e.curves.map((t=>this.divideByEqualArcLengthToPoints({curve:t,subdivision:e.subdivision})))}divideCurvesByArcLengthToPoints(e){return e.curves.map((t=>this.divideByArcLengthToPoints({curve:t,length:e.length})))}domain(e){return e.curve.domain()}startPoint(e){return e.curve.point(e.curve.domain().min)}endPoint(e){return e.curve.point(e.curve.domain().max)}startPoints(e){return e.curves.map((e=>this.startPoint({curve:e})))}endPoints(e){return e.curves.map((e=>this.endPoint({curve:e})))}knots(e){return e.curve.knots()}lengthAtParam(e){return e.curve.lengthAtParam(e.parameter)}length(e){return e.curve.length()}paramAtLength(e){return e.curve.paramAtLength(e.length,e.tolerance)}pointAtParam(e){return e.curve.point(e.parameter)}pointsAtParam(e){return e.curves.map((t=>this.pointAtParam({curve:t,parameter:e.parameter})))}reverse(e){return e.curve.reverse()}split(e){return e.curve.split(e.parameter)}tangent(e){return e.curve.tangent(e.parameter)}tessellate(e){return e.curve.tessellate(e.tolerance)}transform(e){const t=e.curve.controlPoints(),i=this.geometryHelper.transformControlPoints(e.transformation,t);return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.curve.degree(),e.curve.knots(),i,e.curve.weights())}transformCurves(e){return e.curves.map((t=>this.transform({curve:t,transformation:e.transformation})))}weights(e){return e.curve.weights()}}class xU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.RevolvedSurface(e.profile,e.center,e.axis,vr.FromDegrees(e.angle).radians())}profile(e){return e.revolution.profile()}center(e){return e.revolution.center()}axis(e){return e.revolution.axis()}angle(e){return vr.FromRadians(e.revolution.angle()).degrees()}}class bU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ConicalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cone.axis()}base(e){return e.cone.base()}height(e){return e.cone.height()}radius(e){return e.cone.radius()}xAxis(e){return e.cone.xaxis()}}class TU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.CylindricalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cylinder.axis()}base(e){return e.cylinder.base()}height(e){return e.cylinder.height()}radius(e){return e.cylinder.radius()}xAxis(e){return e.cylinder.xaxis()}}class yU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ExtrudedSurface(e.profile,e.direction)}direction(e){return e.extrusion.direction()}profile(e){return e.extrusion.profile()}}class SU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SphericalSurface(e.center,e.radius)}radius(e){return e.sphere.radius()}center(e){return e.sphere.center()}}class CU{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SweptSurface(e.profile,e.rail)}profile(e){return e.sweep.profile()}rail(e){return e.sweep.rail()}}class EU{constructor(e,t){this.context=e,this.geometryHelper=t,this.cone=new bU(e),this.cylinder=new TU(e),this.extrusion=new yU(e),this.sphere=new SU(e),this.revolved=new xU(e),this.sweep=new CU(e)}drawSurface(e){const t=e.surface.tessellate(),i={positions:[],indices:[],normals:[]};let s=0;t.faces.forEach((e=>{s=this.parseFaces(e,t,i,s)}));const r=new zv("pbr"+Math.random(),this.context.scene);return r.baseColor=Ce.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!1,r.doubleSided=!0,this.geometryHelper.createOrUpdateSurfaceMesh(i,e.surfaceMesh,e.updatable,r,!0,e.hidden)}drawSurfaces(e){const t=[];e.surfaces.forEach((e=>{t.push(e.tessellate())}));const i={positions:[],indices:[],normals:[]};let s=0;t.forEach((e=>{e.faces.forEach((t=>{s=this.parseFaces(t,e,i,s)}))}));const r=new zv("pbr"+Math.random(),this.context.scene);return r.baseColor=Ce.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!0,r.doubleSided=!1,this.geometryHelper.createOrUpdateSurfaceMesh(i,e.surfacesMesh,e.updatable,r,!0,e.hidden)}drawSurfacesMultiColour(e){return e.surfacesMesh&&e.updatable&&e.surfacesMesh.getChildren().forEach((e=>e.dispose())),e.surfacesMesh=new bo(`ColouredSurfaces${Math.random()}`,this.context.scene),Array.isArray(e.colours)?e.surfaces.forEach(((t,i)=>{const s=this.drawSurface({surface:t,colours:e.colours[i]?e.colours[i]:e.colours[0],updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(s)})):e.surfaces.forEach(((t,i)=>{const s=this.drawSurface({surface:t,colours:e.colours,updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(s)})),e.surfacesMesh}boundaries(e){return e.surface.boundaries()}createSurfaceByCorners(e){return this.context.verb.geom.NurbsSurface.byCorners(e.point1,e.point2,e.point3,e.point4)}createSurfaceByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.degreeU,e.degreeV,e.knotsU,e.knotsV,e.points,e.weights)}createSurfaceByLoftingCurves(e){return this.context.verb.geom.NurbsSurface.byLoftingCurves(e.curves,e.degreeV)}clone(e){return e.surface.clone()}closestParam(e){return e.surface.closestParam(e.point)}closestPoint(e){return e.surface.closestPoint(e.point)}controlPoints(e){return e.surface.controlPoints()}degreeU(e){return e.surface.degreeU()}degreeV(e){return e.surface.degreeV()}derivatives(e){return e.surface.derivatives(e.u,e.v,e.numDerivatives)}domainU(e){return e.surface.domainU()}domainV(e){return e.surface.domainV()}isocurve(e){return e.surface.isocurve(e.parameter,e.useV)}isocurvesSubdivision(e){const t=.999999/e.isocurveSegments,i=this.context.verb.core.Vec.span(1e-7,.9999999,t);return e.includeLast||i.pop(),e.includeFirst||i.shift(),i.map((t=>e.surface.isocurve(t,e.useV)))}isocurvesAtParams(e){return e.parameters.map((t=>e.surface.isocurve(t,e.useV)))}knotsU(e){return e.surface.knotsU()}knotsV(e){return e.surface.knotsV()}normal(e){return e.surface.normal(e.u,e.v)}point(e){return e.surface.point(e.u,e.v)}reverse(e){return e.surface.reverse()}split(e){return e.surface.split(e.parameter,e.useV)}transformSurface(e){const t=e.surface.controlPoints(),i=e.transformation,s=[];return t.forEach((e=>{let t=e;t=this.geometryHelper.transformControlPoints(i,t),s.push(t)})),this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.surface.degreeU(),e.surface.degreeV(),e.surface.knotsU(),e.surface.knotsV(),s,e.surface.weights())}weights(e){return e.surface.weights()}parseFaces(e,t,i,s){return e.reverse().forEach((e=>{const r=t.normals[e];i.normals.push(r[0],r[1],r[2]);const n=t.points[e];i.positions.push(n[0],n[1],n[2]),i.indices.push(s),s++})),s}}class AU{constructor(e,t){this.context=e,this.geometryHelper=t}curves(e){return this.context.verb.geom.Intersect.curves(e.firstCurve,e.secondCurve,e.tolerance)}curveAndSurface(e){return this.context.verb.geom.Intersect.curveAndSurface(e.curve,e.surface,e.tolerance)}surfaces(e){return this.context.verb.geom.Intersect.surfaces(e.firstSurface,e.secondSurface)}curveCurveFirstParams(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.u0))}curveCurveSecondParams(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.u1))}curveCurveFirstPoints(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.point0))}curveCurveSecondPoints(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.point1))}curveSurfaceCurveParams(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.u))}curveSurfaceSurfaceParams(e){return e.intersections.map((e=>e.uv))}curveSurfaceCurvePoints(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.curvePoint))}curveSurfaceSurfacePoints(e){return e.intersections.map((e=>e.surfacePoint))}}class PU{constructor(e,t){this.curve=new vU(e,t),this.surface=new EU(e,t),this.intersect=new AU(e,t)}}!function(e){e.IntervalDto=class{constructor(){this.min=0,this.max=1}},e.UVDto=class{constructor(){this.u=0,this.v=0}},e.CurveCurveIntersection=class{},e.CurveSurfaceIntersection=class{},e.SurfaceSurfaceIntersectionPoint=class{}}(_U||(_U={}));bi.ShadersStore.cellPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{diffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;if (info.ndl<0.5)\nlevel=0.5;diffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];ToonThresholds[0]=0.95;ToonThresholds[1]=0.5;ToonThresholds[2]=0.2;ToonThresholds[3]=0.03;float ToonBrightnessLevels[5];ToonBrightnessLevels[0]=1.0;ToonBrightnessLevels[1]=0.8;ToonBrightnessLevels[2]=0.6;ToonBrightnessLevels[3]=0.35;ToonBrightnessLevels[4]=0.2;if (info.ndl>ToonThresholds[0])\n{diffuseBase.rgb*=ToonBrightnessLevels[0];}\nelse if (info.ndl>ToonThresholds[1])\n{diffuseBase.rgb*=ToonBrightnessLevels[1];}\nelse if (info.ndl>ToonThresholds[2])\n{diffuseBase.rgb*=ToonBrightnessLevels[2];}\nelse if (info.ndl>ToonThresholds[3])\n{diffuseBase.rgb*=ToonBrightnessLevels[3];}\nelse\n{diffuseBase.rgb*=ToonBrightnessLevels[4];}\n#endif\nreturn max(diffuseBase,vec3(0.2));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nlightingInfo info;vec3 diffuseBase=vec3(0.,0.,0.);float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.cellVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class RU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NDOTL=!0,this.CUSTOMUSERLIGHTING=!0,this.CELLBASIC=!0,this.DEPTHPREPASS=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class IU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this._computeHighLevel=!1,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new RU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(r.CELLBASIC=!this.computeHighLevel,qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="cell",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),In(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this._maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}getClassName(){return"CellMaterial"}clone(e){return yt.Clone((()=>new IU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.CellMaterial",e}static Parse(e,t,i){return yt.Parse((()=>new IU(e.name,t)),e,t,i)}}qe([rt("diffuseTexture")],IU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],IU.prototype,"diffuseTexture",void 0),qe([nt("diffuse")],IU.prototype,"diffuseColor",void 0),qe([st("computeHighLevel")],IU.prototype,"_computeHighLevel",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],IU.prototype,"computeHighLevel",void 0),qe([st("disableLighting")],IU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],IU.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],IU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],IU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.CellMaterial",IU);class MU{constructor(){}}class OU extends yc{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof Ce?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof Ee?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s);const o=this._createdShaderName;return Ti.ShadersStore[o+"VertexShader"]&&Ti.ShadersStore[o+"PixelShader"]||(Ti.ShadersStore[o+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),Ti.ShadersStore[o+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),o}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const s=i[t];if(s&&s.length>0){const i="#define "+t;e=e.replace(i,"\n"+s+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_UPDATE_DIFFUSE:this.CustomParts.Fragment_Custom_Diffuse,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t),this.CustomParts=new MU,this.customShaderNameResolve=this.Builder,this.FragmentShader=Ti.ShadersStore.defaultPixelShader,this.VertexShader=Ti.ShadersStore.defaultVertexShader,OU.ShaderIndexer++,this._createdShaderName="custom_"+OU.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Fragment_Custom_Diffuse(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}OU.ShaderIndexer=1,ee("BABYLON.CustomMaterial",OU);class DU{constructor(){}}class wU extends Um{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof Ce?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof Ee?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e{if("vertex"===t)return e?e(t,i):i;const s=new U_(i);return s.inlineToken="#define pbr_inline",s.processCode(),e?e(t,s.code):s.code}}n&&this._customAttributes&&this._customAttributes.length>0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s);const a=this._createdShaderName;return Ti.ShadersStore[a+"VertexShader"]&&Ti.ShadersStore[a+"PixelShader"]||(Ti.ShadersStore[a+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),Ti.ShadersStore[a+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),a}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const s=i[t];if(s&&s.length>0){const i="#define "+t;e=e.replace(i,"\n"+s+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.CustomParts.Fragment_Custom_Albedo,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS:this.CustomParts.Fragment_Custom_MetallicRoughness,CUSTOM_FRAGMENT_UPDATE_MICROSURFACE:this.CustomParts.Fragment_Custom_MicroSurface,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:this.CustomParts.Fragment_Before_FinalColorComposition,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t),this.CustomParts=new DU,this.customShaderNameResolve=this.Builder,this.FragmentShader=Ti.ShadersStore.pbrPixelShader,this.VertexShader=Ti.ShadersStore.pbrVertexShader,this.FragmentShader=this.FragmentShader.replace(/#include/g,Ti.IncludesShadersStore.pbrBlockAlbedoOpacity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Ti.IncludesShadersStore.pbrBlockReflectivity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Ti.IncludesShadersStore.pbrBlockFinalColorComposition),wU.ShaderIndexer++,this._createdShaderName="custompbr_"+wU.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_Custom_Albedo(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Custom_MetallicRoughness(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}Fragment_Custom_MicroSurface(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FinalColorComposition(e){return this.CustomParts.Fragment_Before_FinalColorComposition=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}wU.ShaderIndexer=1,ee("BABYLON.PBRCustomMaterial",wU);bi.ShadersStore.firePixelShader="precision highp float;uniform vec4 vEyePosition;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\nuniform sampler2D distortionSampler;uniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec4 bx2(vec4 x)\n{return vec4(2.0)*x-vec4(1.0);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);float alpha=1.0;\n#ifdef DIFFUSE\nconst float distortionAmount0 =0.092;const float distortionAmount1 =0.092;const float distortionAmount2 =0.092;vec2 heightAttenuation=vec2(0.3,0.39);vec4 noise0=texture2D(distortionSampler,vDistortionCoords1);vec4 noise1=texture2D(distortionSampler,vDistortionCoords2);vec4 noise2=texture2D(distortionSampler,vDistortionCoords3);vec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;vec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);vec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;baseColor*=opacityColor;baseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec4 color=vec4(baseColor.rgb,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.fireVertexShader="precision highp float;attribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\nuniform float time;uniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSE\nvDiffuseUV=uv;vDiffuseUV.y-=0.2;\n#endif\n#include\n#include\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;vDistortionCoords1.x=uv.x;vDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;vDistortionCoords2.x=uv.x;vDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;vDistortionCoords3.x=uv.x;vDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class NU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.UV1=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.BonesPerMesh=0,this.NUM_BONE_INFLUENCERS=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class FU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this.speed=1,this._scaledDiffuse=new Ce,this._lastTime=0}needAlphaBlending(){return!1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new NU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(r.ALPHATEST=!!this._opacityTexture,r._areMiscDirty&&(r.POINTSIZE=this.pointsCloud||n.forcePointsCloud,r.FOG=n.fogEnabled&&e.applyFog&&n.fogMode!==dr.FOGMODE_NONE&&this.fogEnabled,r.LOGARITHMICDEPTH=this._useLogarithmicDepth),eo(n,o,this,r,!!i),ro(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.UV1&&s.push(ys.UVKind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="fire",l=["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed"];An(l);const h=r.toString();t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:l,uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),In(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._distortionTexture===e||this._opacityTexture===e}getClassName(){return"FireMaterial"}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new FU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e}static Parse(e,t,i){const s=new FU(e.name,t);return s.diffuseColor=Ce.FromArray(e.diffuseColor),s.speed=e.speed,s.alpha=e.alpha,s.id=e.id,bt.AddTagsTo(s,e.tags),s.backFaceCulling=e.backFaceCulling,s.wireframe=e.wireframe,e._diffuseTexture&&(s._diffuseTexture=Vo.Parse(e._diffuseTexture,t,i)),e._distortionTexture&&(s._distortionTexture=Vo.Parse(e._distortionTexture,t,i)),e._opacityTexture&&(s._opacityTexture=Vo.Parse(e._opacityTexture,t,i)),s}}qe([rt("diffuseTexture")],FU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],FU.prototype,"diffuseTexture",void 0),qe([rt("distortionTexture")],FU.prototype,"_distortionTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],FU.prototype,"distortionTexture",void 0),qe([rt("opacityTexture")],FU.prototype,"_opacityTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],FU.prototype,"opacityTexture",void 0),qe([nt("diffuse")],FU.prototype,"diffuseColor",void 0),qe([st()],FU.prototype,"speed",void 0),ee("BABYLON.FireMaterial",FU);bi.ShadersStore.furPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 furColor;uniform float furLength;varying vec3 vPositionW;varying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform float furOcclusion;uniform sampler2D furTexture;varying vec2 vFurUV;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=furColor;vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));if (furTextureColor.a<=0.0 || furTextureColor.g[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;vec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.furVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\nuniform float furLength;uniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform vec3 furGravity;uniform float furTime;uniform float furSpacing;uniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);vec3 tangent2=vec3(-normal.z,0,normal.x);r=Rand(tangent1*r);float J=(2.0+4.0*r);r=Rand(tangent2*r);float K=(2.0+2.0*r);tangent1=tangent1*J+tangent2*K;tangent1=normalize(tangent1);vec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\nvec3 forceDirection=vec3(0.0,0.0,0.0);forceDirection.x=sin(furTime+position.x*0.05)*0.2;forceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;forceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;vec3 displacement=vec3(0.0,0.0,0.0);displacement=furGravity+forceDirection;float displacementFactor=pow(furOffset,3.0);vec3 aNormal=normal;aNormal.xyz+=displacement*displacementFactor;newPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class BU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.HEIGHTMAP=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.HIGHLEVEL=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class LU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this.furLength=1,this.furAngle=0,this.furColor=new Ce(.44,.21,.02),this.furOffset=0,this.furSpacing=12,this.furGravity=new de(0,0,0),this.furSpeed=100,this.furDensity=20,this.furOcclusion=0,this._disableLighting=!1,this._maxSimultaneousLights=4,this.highLevelFur=!0,this._furTime=0}get furTime(){return this._furTime}set furTime(e){this._furTime=e}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}updateFur(){for(let e=1;e0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="fur",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"];An(h);const c=["diffuseSampler","heightTexture","furTexture"],u=[];co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),In(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e||this._heightTexture===e}dispose(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(let t=1;tnew LU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e}getClassName(){return"FurMaterial"}static Parse(e,t,i){const s=yt.Parse((()=>new LU(e.name,t)),e,t,i);return e.sourceMeshName&&s.highLevelFur&&t.executeWhenReady((()=>{const i=t.getMeshByName(e.sourceMeshName);if(i){const r=LU.GenerateTexture("Fur Texture",t);s.furTexture=r,LU.FurifyMesh(i,e.quality)}})),s}static GenerateTexture(e,t){const i=new Sc("FurTexture "+e,256,t,!0),s=i.getContext();for(let e=0;e<2e4;++e)s.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",s.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=Vo.WRAP_ADDRESSMODE,i.wrapV=Vo.WRAP_ADDRESSMODE,i}static FurifyMesh(e,t){const i=[e],s=e.material;let r;if(!(s instanceof LU))throw"The material of the source mesh must be a Fur Material";for(r=1;r0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="gradient",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","logarithmicDepthConstant","topColor","bottomColor","offset","smoothness","scale"];An(h);const c=[],u=[];co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,n),this._mustRebind(s,n,i)&&(In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new VU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GradientMaterial",e}getClassName(){return"GradientMaterial"}static Parse(e,t,i){return yt.Parse((()=>new VU(e.name,t)),e,t,i)}}qe([st("maxSimultaneousLights")],VU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],VU.prototype,"maxSimultaneousLights",void 0),qe([nt()],VU.prototype,"topColor",void 0),qe([st()],VU.prototype,"topColorAlpha",void 0),qe([nt()],VU.prototype,"bottomColor",void 0),qe([st()],VU.prototype,"bottomColorAlpha",void 0),qe([st()],VU.prototype,"offset",void 0),qe([st()],VU.prototype,"scale",void 0),qe([st()],VU.prototype,"smoothness",void 0),qe([st("disableLighting")],VU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],VU.prototype,"disableLighting",void 0),ee("BABYLON.GradientMaterial",VU);bi.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;uniform float visibility;uniform vec3 mainColor;uniform vec3 lineColor;uniform vec4 gridControl;uniform vec3 gridOffset;varying vec3 vPosition;varying vec3 vNormal;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform vec2 vOpacityInfos;\n#endif\nfloat getDynamicVisibility(float position) {float majorGridFrequency=gridControl.y;if (floor(position+0.5)==floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{return 1.0;}\nreturn gridControl.z;}\nfloat getAnisotropicAttenuation(float differentialLength) {const float maxNumberOfLines=10.0;return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);}\nfloat isPointOnLine(float position,float differentialLength) {float fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \n#ifdef ANTIALIAS\nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);float result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result;\n#else\nreturn abs(fractionPartOfPosition)\n#endif\nfloat opacity=1.0;\n#ifdef TRANSPARENT\nopacity=clamp(grid,0.08,gridControl.w*grid);\n#endif\n#ifdef OPACITY\nopacity*=texture2D(opacitySampler,vOpacityUV).a;\n#endif\ngl_FragColor=vec4(color.rgb,opacity*visibility);\n#ifdef TRANSPARENT\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.gridVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#include\nuniform mat4 projection;uniform mat4 view;varying vec3 vPosition;varying vec3 vNormal;\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\nvec4 cameraSpacePosition=view*worldPos;gl_Position=projection*cameraSpacePosition;\n#ifdef OPACITY\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\nif (vOpacityInfos.x==0.)\n{vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));}\nelse\n{vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));}\n#endif \n#include\nvPosition=position;vNormal=normal;\n#define CUSTOM_VERTEX_MAIN_END\n}";class UU extends Oa{constructor(){super(),this.OPACITY=!1,this.ANTIALIAS=!1,this.TRANSPARENT=!1,this.FOG=!1,this.PREMULTIPLYALPHA=!1,this.MAX_LINE=!1,this.UV1=!1,this.UV2=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class GU extends Ra{constructor(e,t){super(e,t),this.mainColor=Ce.Black(),this.lineColor=Ce.Teal(),this.gridRatio=1,this.gridOffset=de.Zero(),this.majorUnitFrequency=10,this.minorUnitVisibility=.33,this.opacity=1,this.antialias=!0,this.preMultiplyAlpha=!1,this.useMaxLine=!1,this._gridControl=new _e(this.gridRatio,this.majorUnitFrequency,this.minorUnitVisibility,this.opacity)}needAlphaBlending(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()}needAlphaBlendingForMesh(e){return e.visibility<1||this.needAlphaBlending()}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new UU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(r.TRANSPARENT!==this.opacity<1&&(r.TRANSPARENT=!r.TRANSPARENT,r.markAsUnprocessed()),r.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(r.PREMULTIPLYALPHA=!r.PREMULTIPLYALPHA,r.markAsUnprocessed()),r.MAX_LINE!==this.useMaxLine&&(r.MAX_LINE=!r.MAX_LINE,r.markAsUnprocessed()),r.ANTIALIAS!==this.antialias&&(r.ANTIALIAS=!r.ANTIALIAS,r.markAsUnprocessed()),r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._opacityTexture&&lc.OpacityTextureEnabled)){if(!this._opacityTexture.isReady())return!1;r._needUVs=!0,r.OPACITY=!0}if(qn(e,n,this._useLogarithmicDepth,!1,this.fogEnabled,!1,r),eo(n,n.getEngine(),this,r,!!i),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial(),ro(e,r,!1,!1);const i=[ys.PositionKind,ys.NormalKind];r.UV1&&i.push(ys.UVKind),r.UV2&&i.push(ys.UV2Kind),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess,jn(i,r);const s=r.toString();t.setEffect(n.getEngine().createEffect("grid",i,["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility","logarithmicDepthConstant"],["opacitySampler"],s,void 0,this.onCompiled,this.onError),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this._activeEffect.setFloat("visibility",t.visibility),r.INSTANCES&&!r.THIN_INSTANCE||this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",s.getViewMatrix()),this._activeEffect.setMatrix("projection",s.getProjectionMatrix()),this._mustRebind(s,n,i)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&lc.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),this._useLogarithmicDepth&&wn(r,n,s)),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new GU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return yt.Parse((()=>new GU(e.name,t)),e,t,i)}}qe([nt()],GU.prototype,"mainColor",void 0),qe([nt()],GU.prototype,"lineColor",void 0),qe([st()],GU.prototype,"gridRatio",void 0),qe([lt()],GU.prototype,"gridOffset",void 0),qe([st()],GU.prototype,"majorUnitFrequency",void 0),qe([st()],GU.prototype,"minorUnitVisibility",void 0),qe([st()],GU.prototype,"opacity",void 0),qe([st()],GU.prototype,"antialias",void 0),qe([st()],GU.prototype,"preMultiplyAlpha",void 0),qe([st()],GU.prototype,"useMaxLine",void 0),qe([rt("opacityTexture")],GU.prototype,"_opacityTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],GU.prototype,"opacityTexture",void 0),ee("BABYLON.GridMaterial",GU);bi.ShadersStore.lavaPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;uniform float time;uniform float speed;uniform float movingSpeed;uniform vec3 fogColor;uniform sampler2D noiseTexture;uniform float fogDensity;varying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nfloat random( vec3 scale,float seed ){return fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );vec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time *0.02;vec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;T1.x+=noiseTex.x*2.0;T1.y+=noiseTex.y*2.0;T2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;T2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;float p=texture2D( noiseTexture,T1*3.0 ).a;vec4 lavaColor=texture2D( diffuseSampler,T2*4.0);vec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );baseColor=temp;float depth=gl_FragCoord.z*4.0;const float LOG2=1.442695;float fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );fogFactor=1.0-clamp( fogFactor,0.0,1.0 );baseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );diffuseColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.lavaVertexShader="precision highp float;uniform float time;uniform float lowFrequencySpeed;varying float noise;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n/* NOISE FUNCTIONS */\nvec3 mod289(vec3 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 permute(vec4 x)\n{return mod289(((x*34.0)+1.0)*x);}\nvec4 taylorInvSqrt(vec4 r)\n{return 1.79284291400159-0.85373472095314*r;}\nvec3 fade(vec3 t) {return t*t*t*(t*(t*6.0-15.0)+10.0);}\nfloat pnoise(vec3 P,vec3 rep)\n{vec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);Pi1=mod289(Pi1);vec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);vec4 iy=vec4(Pi0.yy,Pi1.yy);vec4 iz0=Pi0.zzzz;vec4 iz1=Pi1.zzzz;vec4 ixy=permute(permute(ix)+iy);vec4 ixy0=permute(ixy+iz0);vec4 ixy1=permute(ixy+iz1);vec4 gx0=ixy0*(1.0/7.0);vec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;gx0=fract(gx0);vec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);vec4 sz0=step(gz0,vec4(0.0));gx0-=sz0*(step(0.0,gx0)-0.5);gy0-=sz0*(step(0.0,gy0)-0.5);vec4 gx1=ixy1*(1.0/7.0);vec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;gx1=fract(gx1);vec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);vec4 sz1=step(gz1,vec4(0.0));gx1-=sz1*(step(0.0,gx1)-0.5);gy1-=sz1*(step(0.0,gy1)-0.5);vec3 g000=vec3(gx0.x,gy0.x,gz0.x);vec3 g100=vec3(gx0.y,gy0.y,gz0.y);vec3 g010=vec3(gx0.z,gy0.z,gz0.z);vec3 g110=vec3(gx0.w,gy0.w,gz0.w);vec3 g001=vec3(gx1.x,gy1.x,gz1.x);vec3 g101=vec3(gx1.y,gy1.y,gz1.y);vec3 g011=vec3(gx1.z,gy1.z,gz1.z);vec3 g111=vec3(gx1.w,gy1.w,gz1.w);vec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));g000*=norm0.x;g010*=norm0.y;g100*=norm0.z;g110*=norm0.w;vec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));g001*=norm1.x;g011*=norm1.y;g101*=norm1.z;g111*=norm1.w;float n000=dot(g000,Pf0);float n100=dot(g100,vec3(Pf1.x,Pf0.yz));float n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));float n110=dot(g110,vec3(Pf1.xy,Pf0.z));float n001=dot(g001,vec3(Pf0.xy,Pf1.z));float n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));float n011=dot(g011,vec3(Pf0.x,Pf1.yz));float n111=dot(g111,Pf1);vec3 fade_xyz=fade(Pf0);vec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);vec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);float n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);return 2.2*n_xyz;}\n/* END FUNCTION */\nfloat turbulence( vec3 p ) {float w=100.0;float t=-.5;for (float f=1.0 ; f<=10.0 ; f++ ){float power=pow( 2.0,f );t+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );}\nreturn t;}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\n#ifdef NORMAL\nnoise=10.0* -.10*turbulence( .5*normal+time*1.15 );float b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );float displacement=- 1.5*noise+b;vec3 newPosition=position+normal*displacement;gl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class zU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.UNLIT=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class WU extends Ra{constructor(e,t){super(e,t),this.speed=1,this.movingSpeed=1,this.lowFrequencySpeed=1,this.fogDensity=.15,this._lastTime=0,this.diffuseColor=new Ce(1,1,1),this._disableLighting=!1,this._unlit=!1,this._maxSimultaneousLights=4,this._scaledDiffuse=new Ce}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new zU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=!0,Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="lava",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"];An(h);const c=["diffuseSampler","noiseTexture"],u=[];co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,r.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=Ce.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new WU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.LavaMaterial",e}getClassName(){return"LavaMaterial"}static Parse(e,t,i){return yt.Parse((()=>new WU(e.name,t)),e,t,i)}}qe([rt("diffuseTexture")],WU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],WU.prototype,"diffuseTexture",void 0),qe([rt()],WU.prototype,"noiseTexture",void 0),qe([nt()],WU.prototype,"fogColor",void 0),qe([st()],WU.prototype,"speed",void 0),qe([st()],WU.prototype,"movingSpeed",void 0),qe([st()],WU.prototype,"lowFrequencySpeed",void 0),qe([st()],WU.prototype,"fogDensity",void 0),qe([nt()],WU.prototype,"diffuseColor",void 0),qe([st("disableLighting")],WU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],WU.prototype,"disableLighting",void 0),qe([st("unlit")],WU.prototype,"_unlit",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],WU.prototype,"unlit",void 0),qe([st("maxSimultaneousLights")],WU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],WU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.LavaMaterial",WU);bi.ShadersStore.mixPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D mixMap1Sampler;uniform vec2 vTextureInfos;\n#ifdef MIXMAP2\nuniform sampler2D mixMap2Sampler;\n#endif\nuniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform sampler2D diffuse4Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;uniform vec2 diffuse4Infos;\n#ifdef MIXMAP2\nuniform sampler2D diffuse5Sampler;uniform sampler2D diffuse6Sampler;uniform sampler2D diffuse7Sampler;uniform sampler2D diffuse8Sampler;uniform vec2 diffuse5Infos;uniform vec2 diffuse6Infos;uniform vec2 diffuse7Infos;uniform vec2 diffuse8Infos;\n#endif\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 finalMixColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef MIXMAP2\nvec4 mixColor2=vec4(1.,1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec4 mixColor=texture2D(mixMap1Sampler,vTextureUV);\n#include\nmixColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);vec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);diffuse1Color.rgb*=mixColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);diffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a);\n#ifdef MIXMAP2\nmixColor=texture2D(mixMap2Sampler,vTextureUV);mixColor.rgb*=vTextureInfos.y;vec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);vec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);vec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);vec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);diffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);diffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);diffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a);\n#endif\n#endif\n#ifdef VERTEXCOLOR\nfinalMixColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.mixVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class HU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.MIXMAP2=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class XU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new HU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this._mixTexture1||!this._mixTexture1.isReady())return!1;if(r._needUVs=!0,lc.DiffuseTextureEnabled){if(!this._diffuseTexture1||!this._diffuseTexture1.isReady())return!1;if(r.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())return!1;if(!this._diffuseTexture3||!this._diffuseTexture3.isReady())return!1;if(!this._diffuseTexture4||!this._diffuseTexture4.isReady())return!1;if(this._mixTexture2){if(!this._mixTexture2.isReady())return!1;if(r.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())return!1;if(!this._diffuseTexture6||!this._diffuseTexture6.isReady())return!1;if(!this._diffuseTexture7||!this._diffuseTexture7.isReady())return!1;if(!this._diffuseTexture8||!this._diffuseTexture8.isReady())return!1}}}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="mix",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","logarithmicDepthConstant","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],c=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),lc.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),lc.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture1&&e.push(this._mixTexture1),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._diffuseTexture4&&e.push(this._diffuseTexture4),this._mixTexture2&&e.push(this._mixTexture2),this._diffuseTexture5&&e.push(this._diffuseTexture5),this._diffuseTexture6&&e.push(this._diffuseTexture6),this._diffuseTexture7&&e.push(this._diffuseTexture7),this._diffuseTexture8&&e.push(this._diffuseTexture8),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture1===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._diffuseTexture4===e||this._mixTexture2===e||this._diffuseTexture5===e||this._diffuseTexture6===e||this._diffuseTexture7===e||this._diffuseTexture8===e}dispose(e){this._mixTexture1&&this._mixTexture1.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new XU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MixMaterial",e}getClassName(){return"MixMaterial"}static Parse(e,t,i){return yt.Parse((()=>new XU(e.name,t)),e,t,i)}}qe([rt("mixTexture1")],XU.prototype,"_mixTexture1",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"mixTexture1",void 0),qe([rt("mixTexture2")],XU.prototype,"_mixTexture2",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"mixTexture2",void 0),qe([rt("diffuseTexture1")],XU.prototype,"_diffuseTexture1",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture1",void 0),qe([rt("diffuseTexture2")],XU.prototype,"_diffuseTexture2",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture2",void 0),qe([rt("diffuseTexture3")],XU.prototype,"_diffuseTexture3",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture3",void 0),qe([rt("diffuseTexture4")],XU.prototype,"_diffuseTexture4",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture4",void 0),qe([rt("diffuseTexture1")],XU.prototype,"_diffuseTexture5",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture5",void 0),qe([rt("diffuseTexture2")],XU.prototype,"_diffuseTexture6",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture6",void 0),qe([rt("diffuseTexture3")],XU.prototype,"_diffuseTexture7",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture7",void 0),qe([rt("diffuseTexture4")],XU.prototype,"_diffuseTexture8",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],XU.prototype,"diffuseTexture8",void 0),qe([nt()],XU.prototype,"diffuseColor",void 0),qe([nt()],XU.prototype,"specularColor",void 0),qe([st()],XU.prototype,"specularPower",void 0),qe([st("disableLighting")],XU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],XU.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],XU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],XU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.MixMaterial",XU);bi.ShadersStore.normalPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef LIGHTING\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef LIGHTING\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse= baseColor.rgb;\n#endif\nvec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.normalVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class YU extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.LIGHTING=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class QU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaBlendingForMesh(e){return this.needAlphaBlending()||e.visibility<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new YU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=!0,Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),r.LIGHTING=!this._disableLighting,ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),Qn(s,e,r,i),jn(s,r);const a="normal",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new QU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.NormalMaterial",e}getClassName(){return"NormalMaterial"}static Parse(e,t,i){return yt.Parse((()=>new QU(e.name,t)),e,t,i)}}qe([rt("diffuseTexture")],QU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],QU.prototype,"diffuseTexture",void 0),qe([nt()],QU.prototype,"diffuseColor",void 0),qe([st("disableLighting")],QU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],QU.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],QU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],QU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.NormalMaterial",QU);bi.ShadersStore.shadowOnlyPixelShader="precision highp float;uniform vec4 vEyePosition;uniform float alpha;uniform vec3 shadowColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0..1]\nvec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.shadowOnlyVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class jU extends Oa{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class KU extends Ra{constructor(e,t){super(e,t),this._needAlphaBlending=!0,this.shadowColor=Ce.Black()}needAlphaBlending(){return this._needAlphaBlending}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}get activeLight(){return this._activeLight}set activeLight(e){this._activeLight=e}_getFirstShadowLightForMesh(e){for(const t of e.lightSources)if(t.shadowEnabled)return t;return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new jU);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(this._activeLight)for(const t of e.lightSources)if(t.shadowEnabled){if(this._activeLight===t)break;const i=e.lightSources.indexOf(this._activeLight);-1!==i&&(e.lightSources.splice(i,1),e.lightSources.splice(0,0,this._activeLight));break}eo(n,o,this,r,!!i),qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,1);const a=this._getFirstShadowLightForMesh(e)?.getShadowGenerator();if(this._needAlphaBlending=!0,a&&a.getClassName&&"CascadedShadowGenerator"===a.getClassName()){const e=a;this._needAlphaBlending=!e.autoCalcDepthBounds}if(ro(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,1),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),Qn(s,e,r,i),jn(s,r);const a="shadowOnly",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones","logarithmicDepthConstant"],c=[],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:1}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),s.lightsEnabled){Yn(s,t,this._activeEffect,r,1);const e=this._getFirstShadowLightForMesh(t);e&&(e._renderId=-1)}(s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE||r.SHADOWCSM0)&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i)}}clone(e){return yt.Clone((()=>new KU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.ShadowOnlyMaterial",e}getClassName(){return"ShadowOnlyMaterial"}static Parse(e,t,i){return yt.Parse((()=>new KU(e.name,t)),e,t,i)}}ee("BABYLON.ShadowOnlyMaterial",KU);bi.ShadersStore.simplePixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";bi.ShadersStore.simpleVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class $U extends Oa{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class qU extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new $U);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&lc.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="simple",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&lc.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new qU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SimpleMaterial",e}getClassName(){return"SimpleMaterial"}static Parse(e,t,i){return yt.Parse((()=>new qU(e.name,t)),e,t,i)}}qe([rt("diffuseTexture")],qU.prototype,"_diffuseTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],qU.prototype,"diffuseTexture",void 0),qe([nt("diffuse")],qU.prototype,"diffuseColor",void 0),qe([st("disableLighting")],qU.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],qU.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],qU.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],qU.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.SimpleMaterial",qU);bi.ShadersStore.skyPixelShader="precision highp float;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\nuniform vec3 cameraPosition;uniform vec3 cameraOffset;uniform vec3 up;uniform float luminance;uniform float turbidity;uniform float rayleigh;uniform float mieCoefficient;uniform float mieDirectionalG;uniform vec3 sunPosition;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nconst float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float pn=0.035;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 K=vec3(0.686,0.678,0.666);const float v=4.0;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float EE=1000.0;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float cutoffAngle=pi/1.95;const float steepness=1.5;vec3 totalRayleigh(vec3 lambda)\n{return (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));}\nvec3 simplifiedRayleigh()\n{return 0.0005/vec3(94,40,18);}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{float c=(0.2*T )*10E-18;return 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;}\nfloat hgPhase(float cosTheta,float g)\n{return (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));}\nfloat sunIntensity(float zenithAngleCos)\n{return EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));}\nfloat A=0.15;float B=0.50;float C=0.10;float D=0.20;float EEE=0.02;float F=0.30;float W=1000.0;vec3 Uncharted2Tonemap(vec3 x)\n{return ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;}\n#if DITHER\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));vec3 sunDirection=normalize(sunPosition);float sunE=sunIntensity(dot(sunDirection,up));vec3 betaR=simplifiedRayleigh()*rayleighCoefficient;vec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;float zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));float sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));vec3 Fex=exp(-(betaR*sR+betaM*sM));float cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=betaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=betaM*mPhase;vec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));vec3 direction=normalize(vPositionW-cameraPosition);float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(sunE*19000.0*Fex)*sundisk;vec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));vec3 texColor=(Lin+L0);texColor*=0.04 ;texColor+=vec3(0.0,0.001,0.0025)*0.3;float g_fMaxLuminance=1.0;float fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;vec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);vec3 retColor=curr*whiteScale;/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if DITHER\nretColor.rgb+=dither(gl_FragCoord.xy,0.5);\n#endif\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.skyVertexShader="precision highp float;attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\nuniform mat4 world;uniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=viewProjection*world*vec4(position,1.0);vec4 worldPos=world*vec4(position,1.0);vPositionW=vec3(worldPos);\n#include\n#include\n#include\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class ZU extends Oa{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.DITHER=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class JU extends Ra{constructor(e,t){super(e,t),this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.sunPosition=new de(0,100,0),this.useSunPosition=!1,this.cameraOffset=de.Zero(),this.up=de.Up(),this.dithering=!1,this._cameraPosition=de.Zero(),this._skyOrientation=new pe}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new ZU);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(qn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,s),ro(e,s,!0,!1),s.IMAGEPROCESSINGPOSTPROCESS!==r.imageProcessingConfiguration.applyByPostProcess&&s.markAsMiscDirty(),s.DITHER!==this.dithering&&s.markAsMiscDirty(),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new ja;s.FOG&&e.addFallback(1,"FOG"),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess,s.DITHER=this.dithering;const i=[ys.PositionKind];s.VERTEXCOLOR&&i.push(ys.ColorKind);const n="sky",o=["world","viewProjection","view","vFogInfos","vFogColor","logarithmicDepthConstant","pointSize","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset","up"];An(o);const a=s.toString();t.setEffect(r.getEngine().createEffect(n,i,o,[],a,e,this.onCompiled,this.onError),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n,i)&&(In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s)),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect);const o=s.activeCamera;if(o){const e=o.getWorldMatrix();this._cameraPosition.x=e.m[12],this._cameraPosition.y=e.m[13],this._cameraPosition.z=e.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this._activeEffect.setVector3("up",this.up),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){const e=Math.PI*(this.inclination-.5),t=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(t)*Math.cos(e),this.sunPosition.y=this.distance*Math.sin(-e),this.sunPosition.z=this.distance*Math.sin(t)*Math.cos(e),pe.FromUnitVectorsToRef(de.UpReadOnly,this.up,this._skyOrientation),this.sunPosition.rotateByQuaternionToRef(this._skyOrientation,this.sunPosition)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect,i)}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return yt.Clone((()=>new JU(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SkyMaterial",e}getClassName(){return"SkyMaterial"}static Parse(e,t,i){return yt.Parse((()=>new JU(e.name,t)),e,t,i)}}qe([st()],JU.prototype,"luminance",void 0),qe([st()],JU.prototype,"turbidity",void 0),qe([st()],JU.prototype,"rayleigh",void 0),qe([st()],JU.prototype,"mieCoefficient",void 0),qe([st()],JU.prototype,"mieDirectionalG",void 0),qe([st()],JU.prototype,"distance",void 0),qe([st()],JU.prototype,"inclination",void 0),qe([st()],JU.prototype,"azimuth",void 0),qe([lt()],JU.prototype,"sunPosition",void 0),qe([st()],JU.prototype,"useSunPosition",void 0),qe([lt()],JU.prototype,"cameraOffset",void 0),qe([lt()],JU.prototype,"up",void 0),qe([st()],JU.prototype,"dithering",void 0),ee("BABYLON.SkyMaterial",JU);bi.ShadersStore.terrainPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D textureSampler;uniform vec2 vTextureInfos;uniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;uniform sampler2D bump2Sampler;uniform sampler2D bump3Sampler;\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));return mat3(tangent*invmax,binormal*invmax,normal);}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{vec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;vec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;vec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;bump1Color.rgb*=mixColor.r;bump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);vec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);map=map*255./127.-128./127.;mat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);return normalize(TBN*map);}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);diffuse1Color.rgb*=baseColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);baseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.terrainVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class eG extends Oa{constructor(){super(),this.DIFFUSE=!1,this.BUMP=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class tG extends Ra{constructor(e,t){super(e,t),this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new eG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(r._needUVs=!0,lc.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady())return!1;if(!this.diffuseTexture2||!this.diffuseTexture2.isReady())return!1;if(!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;r.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&lc.BumpTextureEnabled){if(!this.bumpTexture1.isReady())return!1;if(!this.bumpTexture2.isReady())return!1;if(!this.bumpTexture3.isReady())return!1;r._needNormals=!0,r.BUMP=!0}}if(qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=Zn(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),eo(n,o,this,r,!!i),ro(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new ja;r.FOG&&i.addFallback(1,"FOG"),Kn(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="terrain",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],c=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler","logarithmicDepthConstant"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),lc.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),lc.BumpTextureEnabled&&s.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._bumpTexture1===e||this._bumpTexture2===e||this._bumpTexture3===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new tG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TerrainMaterial",e}getClassName(){return"TerrainMaterial"}static Parse(e,t,i){return yt.Parse((()=>new tG(e.name,t)),e,t,i)}}qe([rt("mixTexture")],tG.prototype,"_mixTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"mixTexture",void 0),qe([rt("diffuseTexture1")],tG.prototype,"_diffuseTexture1",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"diffuseTexture1",void 0),qe([rt("diffuseTexture2")],tG.prototype,"_diffuseTexture2",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"diffuseTexture2",void 0),qe([rt("diffuseTexture3")],tG.prototype,"_diffuseTexture3",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"diffuseTexture3",void 0),qe([rt("bumpTexture1")],tG.prototype,"_bumpTexture1",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"bumpTexture1",void 0),qe([rt("bumpTexture2")],tG.prototype,"_bumpTexture2",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"bumpTexture2",void 0),qe([rt("bumpTexture3")],tG.prototype,"_bumpTexture3",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],tG.prototype,"bumpTexture3",void 0),qe([nt()],tG.prototype,"diffuseColor",void 0),qe([nt()],tG.prototype,"specularColor",void 0),qe([st()],tG.prototype,"specularPower",void 0),qe([st("disableLighting")],tG.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],tG.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],tG.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],tG.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.TerrainMaterial",tG);bi.ShadersStore.triplanarPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;uniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;uniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;uniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(0.,0.,0.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);normalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.triplanarVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\nvec3 xtan=vec3(0,0,1);vec3 xbin=vec3(0,1,0);vec3 ytan=vec3(1,0,0);vec3 ybin=vec3(0,0,1);vec3 ztan=vec3(1,0,0);vec3 zbin=vec3(0,1,0);vec3 normalizedNormal=normalize(normal);normalizedNormal*=normalizedNormal;vec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);vec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);mat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nworldTangent=normalize((normalWorld*worldTangent).xyz);worldBinormal=normalize((normalWorld*worldBinormal).xyz);vec3 worldNormal=normalize((normalWorld*normalize(normal)).xyz);tangentSpace[0]=worldTangent;tangentSpace[1]=worldBinormal;tangentSpace[2]=worldNormal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class iG extends Oa{constructor(){super(),this.DIFFUSEX=!1,this.DIFFUSEY=!1,this.DIFFUSEZ=!1,this.BUMPX=!1,this.BUMPY=!1,this.BUMPZ=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.NONUNIFORMSCALING=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class sG extends Ra{constructor(e,t){super(e,t),this.tileSize=1,this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(.2,.2,.2),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new iG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&n.texturesEnabled){if(lc.DiffuseTextureEnabled){const e=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],t=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"];for(let i=0;i0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="triplanar",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","tileSize"],c=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ","logarithmicDepthConstant"],u=[];An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),this._mustRebind(s,n,i)&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTextureX===e||this._diffuseTextureY===e||this._diffuseTextureZ===e||this._normalTextureX===e||this._normalTextureY===e||this._normalTextureZ===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return yt.Clone((()=>new sG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TriPlanarMaterial",e}getClassName(){return"TriPlanarMaterial"}static Parse(e,t,i){return yt.Parse((()=>new sG(e.name,t)),e,t,i)}}qe([rt()],sG.prototype,"mixTexture",void 0),qe([rt("diffuseTextureX")],sG.prototype,"_diffuseTextureX",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"diffuseTextureX",void 0),qe([rt("diffuseTexturY")],sG.prototype,"_diffuseTextureY",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"diffuseTextureY",void 0),qe([rt("diffuseTextureZ")],sG.prototype,"_diffuseTextureZ",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"diffuseTextureZ",void 0),qe([rt("normalTextureX")],sG.prototype,"_normalTextureX",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"normalTextureX",void 0),qe([rt("normalTextureY")],sG.prototype,"_normalTextureY",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"normalTextureY",void 0),qe([rt("normalTextureZ")],sG.prototype,"_normalTextureZ",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],sG.prototype,"normalTextureZ",void 0),qe([st()],sG.prototype,"tileSize",void 0),qe([nt()],sG.prototype,"diffuseColor",void 0),qe([nt()],sG.prototype,"specularColor",void 0),qe([st()],sG.prototype,"specularPower",void 0),qe([st("disableLighting")],sG.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],sG.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],sG.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],sG.prototype,"maxSimultaneousLights",void 0),ee("BABYLON.TriPlanarMaterial",sG);bi.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform sampler2D normalSampler;uniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;uniform sampler2D reflectionSampler;const float LOG2=1.442695;uniform vec3 cameraPosition;uniform vec4 waterColor;uniform float colorBlendFactor;uniform vec4 waterColor2;uniform float colorBlendFactor2;uniform float bumpHeight;uniform float time;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));if (normalW.y<0.0) {normalW.y=-normalW.y;}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);vec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);float IfresnelTerm=1.0-fresnelTerm;refractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;reflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;baseColor=combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=max(dot(viewDirectionW,upVector),0.0);vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);baseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#elif defined(IMAGEPROCESSING)\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";bi.ShadersStore.waterVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;uniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\nuniform mat4 reflectionViewProjection;uniform vec2 windDirection;uniform float waveLength;uniform float time;uniform float windForce;uniform float waveHeight;uniform float waveSpeed;uniform float waveCount;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x==0.)\n{vNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{vNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\nfloat finalWaveCount=1.0/(waveCount*0.5);\n#ifdef USE_WORLD_COORDINATES\nvec3 p=worldPos.xyz;\n#else\nvec3 p=position;\n#endif\nfloat newY=(sin(((p.x/finalWaveCount)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+ (cos(((p.z/finalWaveCount)+ time*waveSpeed))*waveHeight*windDirection.y*5.0);p.y+=abs(newY);\n#ifdef USE_WORLD_COORDINATES\ngl_Position=viewProjection*vec4(p,1.0);\n#else\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#endif\n#ifdef REFLECTION\nvRefractionMapTexCoord.x=0.5*(gl_Position.w+gl_Position.x);vRefractionMapTexCoord.y=0.5*(gl_Position.w+gl_Position.y);vRefractionMapTexCoord.z=gl_Position.w;worldPos=reflectionViewProjection*finalWorld*vec4(position,1.0);vReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);vReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);vReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class rG extends Oa{constructor(){super(),this.BUMP=!1,this.REFLECTION=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class nG extends Ra{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new ue(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new Ce(1,1,1),this.specularColor=new Ce(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new ue(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new Ce(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new Ce(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new ds(16),this._mesh=null,this._reflectionTransform=fe.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);-1!==t&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);-1!==t&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&0===this._refractionRTT.refreshRate)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new rG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled)){if(this.bumpTexture&&lc.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;r._needUVs=!0,r.BUMP=!0}lc.ReflectionTextureEnabled&&(r.REFLECTION=!0)}if(eo(n,o,this,r,!!i),qn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._areMiscDirty&&(r.FRESNELSEPARATE=this._fresnelSeparate,r.BUMPSUPERIMPOSE=this._bumpSuperimpose,r.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,r.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),r._needNormals=Zn(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(ro(e,r,!0,!0),this._mesh=e,this._waitingRenderList){for(let e=0;e0&&i.addCPUSkinningFallback(0,e);const s=[ys.PositionKind];r.NORMAL&&s.push(ys.NormalKind),r.UV1&&s.push(ys.UVKind),r.UV2&&s.push(ys.UV2Kind),r.VERTEXCOLOR&&s.push(ys.ColorKind),Qn(s,e,r,i),jn(s,r);const a="water",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],c=["normalSampler","refractionSampler","reflectionSampler"],u=[];xs&&(xs.PrepareUniforms(h,r),xs.PrepareSamplers(c,r)),An(h),co({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),Wn(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.bumpTexture&&lc.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),In(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&wn(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Yn(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==dr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Nn(s,t,this._activeEffect),wn(r,this._activeEffect,s),lc.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(s.getProjectionMatrix()),a=s.getEngine().getDeltaTime();a!==this._lastDeltaTime&&(this._lastDeltaTime=a,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect,i)}_createRenderTargets(e,t){let i;this._refractionRTT=new pl(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=Yd.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=Yd.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0,this._reflectionRTT=new pl(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=Yd.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=Yd.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let s,r=null;const n=fe.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){r=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=ir.FromPositionAndNormal(new de(0,t+.05,0),new de(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),this.disableClipPlane||(e.clipPlane=r)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){r=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=ir.FromPositionAndNormal(new de(0,t-.05,0),new de(0,-1,0)),fe.ReflectionToRef(e.clipPlane,n)}s=e.getViewMatrix(),n.multiplyToRef(s,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=de.TransformCoordinates(e.activeCamera.position,n)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),e.clipPlane=r,e.setTransformMatrix(s,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._bumpTexture===e}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=t&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=t&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return yt.Clone((()=>new nG(e,this.getScene())),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew nG(e.name,t)),e,t,i);return s._waitingRenderList=e.renderList,s}static CreateDefaultMesh(e,t){return Uc(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}qe([rt("bumpTexture")],nG.prototype,"_bumpTexture",void 0),qe([it("_markAllSubMeshesAsTexturesDirty")],nG.prototype,"bumpTexture",void 0),qe([nt()],nG.prototype,"diffuseColor",void 0),qe([nt()],nG.prototype,"specularColor",void 0),qe([st()],nG.prototype,"specularPower",void 0),qe([st("disableLighting")],nG.prototype,"_disableLighting",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],nG.prototype,"disableLighting",void 0),qe([st("maxSimultaneousLights")],nG.prototype,"_maxSimultaneousLights",void 0),qe([it("_markAllSubMeshesAsLightsDirty")],nG.prototype,"maxSimultaneousLights",void 0),qe([st()],nG.prototype,"windForce",void 0),qe([at()],nG.prototype,"windDirection",void 0),qe([st()],nG.prototype,"waveHeight",void 0),qe([st()],nG.prototype,"bumpHeight",void 0),qe([st("bumpSuperimpose")],nG.prototype,"_bumpSuperimpose",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],nG.prototype,"bumpSuperimpose",void 0),qe([st("fresnelSeparate")],nG.prototype,"_fresnelSeparate",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],nG.prototype,"fresnelSeparate",void 0),qe([st("bumpAffectsReflection")],nG.prototype,"_bumpAffectsReflection",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],nG.prototype,"bumpAffectsReflection",void 0),qe([nt()],nG.prototype,"waterColor",void 0),qe([st()],nG.prototype,"colorBlendFactor",void 0),qe([nt()],nG.prototype,"waterColor2",void 0),qe([st()],nG.prototype,"colorBlendFactor2",void 0),qe([st()],nG.prototype,"waveLength",void 0),qe([st()],nG.prototype,"waveSpeed",void 0),qe([st()],nG.prototype,"waveCount",void 0),qe([st()],nG.prototype,"disableClipPlane",void 0),qe([st("useWorldCoordinatesForWaveDeformation")],nG.prototype,"_useWorldCoordinatesForWaveDeformation",void 0),qe([it("_markAllSubMeshesAsMiscDirty")],nG.prototype,"useWorldCoordinatesForWaveDeformation",void 0),ee("BABYLON.WaterMaterial",nG);var oG,aG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class lG{constructor(e,t,i,s,r,n,o,a,l,h){this.point=e,this.line=t,this.polyline=i,this.node=s,this.verbCurve=r,this.verbSurface=n,this.jscad=o,this.occt=a,this.tag=l,this.context=h,this.defaultBasicOptions=new gV.DrawBasicGeometryOptions,this.defaultNodeOptions={colorX:"#ff0000",colorY:"#00ff00",colorZ:"#0000ff",size:2}}drawAnyAsyncNoReturn(e){return aG(this,void 0,void 0,(function*(){this.drawAnyAsync(e)}))}drawAnyAsync(e){return aG(this,void 0,void 0,(function*(){const t=e.entity;return void 0===t||Array.isArray(t)&&0===t.length?Promise.resolve(void 0):this.detectJscadMesh(t)?this.handleJscadMesh(e):this.detectOcctShape(t)?this.handleOcctShape(e):this.detectOcctShapes(t)?this.handleOcctShapes(e):this.detectJscadMeshes(t)?this.handleJscadMeshes(e):Promise.resolve(this.drawAny(e))}))}updateAny(e){let t;if(e.babylonMesh&&e.babylonMesh.metadata)switch(e.babylonMesh.metadata.type){case gV.drawingTypes.point:t=this.handlePoint(e);break;case gV.drawingTypes.points:t=this.handlePoints(e);break;case gV.drawingTypes.line:t=this.handleLine(e);break;case gV.drawingTypes.lines:t=this.handleLines(e);break;case gV.drawingTypes.polyline:t=this.handlePolyline(e);break;case gV.drawingTypes.polylines:t=this.handlePolylines(e);break;case gV.drawingTypes.verbCurve:t=this.handleVerbCurve(e);break;case gV.drawingTypes.verbCurves:t=this.handleVerbCurves(e);break;case gV.drawingTypes.verbSurface:t=this.handleVerbSurface(e);break;case gV.drawingTypes.verbSurfaces:t=this.handleVerbSurfaces(e);break;case gV.drawingTypes.tag:t=this.handleTag(e);break;case gV.drawingTypes.tags:t=this.handleTags(e);break;case gV.drawingTypes.node:t=this.handleNode(e);break;case gV.drawingTypes.nodes:t=this.handleNodes(e)}return t}drawAnyNoReturn(e){this.drawAny(e)}drawAny(e){let t;const i=e.entity;return e.babylonMesh?t=this.updateAny(e):this.detectLine(i)?t=this.handleLine(e):this.detectPoint(i)?t=this.handlePoint(e):this.detectPolyline(i)?t=this.handlePolyline(e):this.detectNode(i)?t=this.handleNode(e):this.detectVerbCurve(i)?t=this.handleVerbCurve(e):this.detectVerbSurface(i)?t=this.handleVerbSurface(e):this.detectPolylines(i)?t=this.handlePolylines(e):this.detectLines(i)?t=this.handleLines(e):this.detectPoints(i)?t=this.handlePoints(e):this.detectNodes(i)?t=this.handleNodes(e):this.detectVerbCurves(i)?t=this.handleVerbCurves(e):this.detectVerbSurfaces(i)?t=this.handleVerbSurfaces(e):this.detectTag(i)?t=this.handleTag(e):this.detectTags(i)&&(t=this.handleTags(e)),t}drawGridMeshNoReturn(e){this.drawGridMesh(e)}drawGridMesh(e){try{const t=new GU(`groundMaterial${Math.random()}`,this.context.scene);t.majorUnitFrequency=e.majorUnitFrequency,t.minorUnitVisibility=e.minorUnitVisibility,t.gridRatio=e.gridRatio,t.backFaceCulling=e.backFaceCulling,t.mainColor=Ce.FromHexString(e.mainColor),t.lineColor=Ce.FromHexString(e.secondaryColor),t.opacity=e.opacity;const i=Gd.CreateGround(`bitbybit-ground${Math.random()}`,{width:e.width,height:e.height,subdivisions:e.subdivisions,updatable:!1},this.context.scene);return i.material=t,i}catch(e){return console.log("Error happened: ",e),new bo("error-ground",this.context.scene)}}optionsSimple(e){return e}optionsOcctShape(e){return e}optionsOcctShapeSimple(e){return e}optionsOcctShapeMaterial(e){return e}optionsBabylonNode(e){return e}handleTags(e){const t=e.options?e.options:{updatable:!1},i=this.tag.drawTags(Object.assign({tagsVariable:e.babylonMesh,tags:e.entity},t));return i.metadata={type:gV.drawingTypes.tags,options:t},i}handleTag(e){let t=e.options?e.options:{updatable:!1};!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.tag.drawTag(Object.assign({tagVariable:e.babylonMesh,tag:e.entity},t));return i.metadata={type:gV.drawingTypes.tag,options:t},i}handleVerbSurfaces(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbSurface.drawSurfacesMultiColour(Object.assign({surfacesMesh:e.babylonMesh,surfaces:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.verbSurfaces,t,i),i}handleVerbCurves(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbCurve.drawCurves(Object.assign({curvesMesh:e.babylonMesh,curves:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.verbCurves,t,i),i}handleNodes(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNodes(Object.assign({nodes:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.nodes,t,i),i}handlePoints(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.point.drawPoints(Object.assign({pointsMesh:e.babylonMesh,points:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.points,t,i),i}handleLines(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity.map((e=>({points:[e.start,e.end]})))},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.lines,t,i),i}handlePolylines(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.polylines,t,i),i}handleVerbSurface(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbSurface.drawSurface(Object.assign({surfaceMesh:e.babylonMesh,surface:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.verbSurface,t,i),i}handleVerbCurve(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbCurve.drawCurve(Object.assign({curveMesh:e.babylonMesh,curve:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.verbCurve,t,i),i}handleNode(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNode(Object.assign({node:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.node,t,i),i}handlePolyline(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolyline(Object.assign({polylineMesh:e.babylonMesh,polyline:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.polyline,t,i),i}handlePoint(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.point.drawPoint(Object.assign({pointMesh:e.babylonMesh,point:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.point,t,i),i}handleLine(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:[{points:[e.entity.start,e.entity.end]}]},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.line,t,i),i}handleJscadMeshes(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.jscad.drawSolidOrPolygonMeshes(Object.assign({jscadMesh:e.babylonMesh,meshes:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.jscadMeshes,t,e),e)))}handleOcctShape(e){let t=e.options?e.options:new rk.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.occt.drawShape(Object.assign(Object.assign({shape:e.entity},new gV.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.occt,t,e),e)))}handleOcctShapes(e){let t=e.options?e.options:new rk.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.occt.drawShapes(Object.assign(Object.assign({shapes:e.entity},new gV.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.occt,t,e),e)))}handleJscadMesh(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.jscad.drawSolidOrPolygonMesh(Object.assign({jscadMesh:e.babylonMesh,mesh:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(gV.drawingTypes.jscadMesh,t,e),e)))}applyGlobalSettingsAndMetadataAndShadowCasting(e,t,i){const s={type:e,options:t},r=this.context.scene.metadata.shadowGenerators;i.isPickable=!1,i.getChildMeshes().forEach((e=>{e.isPickable=!1})),r.length>0&&(i.receiveShadows=!0,r.forEach((e=>e.addShadowCaster(i))),i.getChildMeshes().forEach((e=>{e.receiveShadows=!0,r.forEach((t=>t.addShadowCaster(e)))}))),i.metadata=i.metadata?Object.assign(Object.assign({},i.metadata),s):s}detectPoint(e){return Array.isArray(e)&&3===e.length&&this.checkIfElementsInArrayAreNumbers(e)}detectPoints(e){return Array.isArray(e)&&this.checkIfElementsInArrayAreArrays(e)&&this.arraysInChildrenArraysContainNumbers(e)&&this.arraysInChildrenArraysAreOfLength3(e)}detectLine(e){return e.start&&e.end&&Array.isArray(e.start)&&Array.isArray(e.end)}detectLines(e){return Array.isArray(e)&&!e.some((e=>!this.detectLine(e)))}detectPolyline(e){return e.points&&Array.isArray(e.points)}detectPolylines(e){return Array.isArray(e)&&!e.some((e=>!this.detectPolyline(e)))}detectNode(e){return!Array.isArray(e)&&e.id&&e.id.includes("node")}detectNodes(e){return Array.isArray(e)&&!e.some((e=>!this.detectNode(e)))}detectVerbCurve(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.knots&&e._data.degree}detectVerbSurface(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.degreeU&&e._data.degreeV&&e._data.knotsU&&e._data.knotsV}detectVerbCurves(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbCurve(e)))}detectVerbSurfaces(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbSurface(e)))}detectJscadMesh(e){return!Array.isArray(e)&&(e.sides||e.polygons)}detectJscadMeshes(e){return Array.isArray(e)&&!e.some((e=>!this.detectJscadMesh(e)))}detectOcctShape(e){return"occ-shape"===(null==e?void 0:e.type)}detectOcctShapes(e){return Array.isArray(e)&&!e.some((e=>!this.detectOcctShape(e)))}detectTag(e){return!Array.isArray(e)&&e.text}detectTags(e){return Array.isArray(e)&&!e.some((e=>!this.detectTag(e)))}checkIfElementsInArrayAreNumbers(e){return!e.some((e=>isNaN(e)))}checkIfElementsInArrayAreArrays(e){return!e.some((e=>!Array.isArray(e)))}arraysInChildrenArraysContainNumbers(e){return!e.some((e=>!this.checkIfElementsInArrayAreNumbers(e)))}arraysInChildrenArraysAreOfLength3(e){return!e.some((e=>3!==e.length))}}class hG{constructor(e,t){this.context=e,this.geometryHelper=t}drawLines(e){const t=[],i=[];return e.lines.forEach(((s,r)=>{let n;t.push([new de(s.start[0],s.start[1],s.start[2]),new de(s.end[0],s.end[1],s.end[2])]),n=Array.isArray(e.colours)&&e.colours.length===e.lines.length?Ce.FromHexString(e.colours[r]):Array.isArray(e.colours)?Ce.FromHexString(e.colours[0]):Ce.FromHexString(e.colours),i.push([new Ee(n.r,n.g,n.b,e.opacity),new Ee(n.r,n.g,n.b,e.opacity)])})),e.linesMesh&&e.updatable?e.linesMesh.getTotalVertices()/2===t.length?e.linesMesh=Gd.CreateLineSystem(null,{lines:t,instance:e.linesMesh,colors:i,useVertexAlpha:!0,updatable:e.updatable},null):(e.linesMesh.dispose(),e.linesMesh=this.createLineSystemMesh(e.updatable,t,i)):e.linesMesh=this.createLineSystemMesh(e.updatable,t,i),this.geometryHelper.edgesRendering(e.linesMesh,e.size,e.opacity,e.colours),e.linesMesh}convertToNurbsCurve(e){return new this.context.verb.geom.Line(e.line.start,e.line.end)}convertLinesToNurbsCurves(e){return e.lines.map((e=>new this.context.verb.geom.Line(e.start,e.end)))}getStartPoint(e){return e.line.start}getEndPoint(e){return e.line.end}length(e){return this.context.verb.core.Vec.dist(e.line.start,e.line.end)}reverse(e){return{start:e.line.end,end:e.line.start}}transformLine(e){const t=e.transformation;let i=[e.line.start,e.line.end];return i=this.geometryHelper.transformControlPoints(t,i),{start:i[0],end:i[1]}}transformsForLines(e){return e.lines.map(((t,i)=>{const s=e.transformation[i];let r=[t.start,t.end];return r=this.geometryHelper.transformControlPoints(s,r),{start:r[0],end:r[1]}}))}create(e){return{start:e.start,end:e.end}}createAsync(e){return Promise.resolve({start:e.start,end:e.end})}getPointOnLine(e){const t=e.line.start,i=e.line.end,s=e.param,r=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];return[t[0]+s*r[0],t[1]+s*r[1],t[2]+s*r[2]]}linesBetweenPoints(e){const t=[];for(let i=1;i({start:t,end:e.endPoints[i]}))).filter((e=>0!==this.context.verb.core.Vec.dist(e.start,e.end)))}linesBetweenStartAndEndPointsAsync(e){return Promise.resolve(this.linesBetweenStartAndEndPoints(e))}createLineSystemMesh(e,t,i){return Gd.CreateLineSystem(`lines${Math.random()}`,{lines:t,colors:i,useVertexAlpha:!0,updatable:e},this.context.scene)}}class cG{getItem(e){if(e.index<0||e.index>=e.list.length)throw new Error("Index out of bounds");let t;return t=e.clone?structuredClone(e.list[e.index]):e.list[e.index],t}getSubList(e){let t;return t=e.clone?structuredClone(e.list.slice(e.indexStart,e.indexEnd)):e.list.slice(e.indexStart,e.indexEnd),t}getNthItem(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let s=0;s=r)t.forEach(((e,t)=>{!0===i[t]&&n.push(e)}));else{const e=[],o=Math.ceil(r/s);for(let t=0;t{!0===e[i]&&n.push(t)}))}return n}mergeElementsOfLists(e){const t=e.lists,i=e.level,s=[],r=[];t.forEach((e=>{const t=e.flat(i);s.push(t)}));const n=this.getLongestListLength({lists:s});for(let e=0;e0&&r.push(t)}let o=[];if(i>0)for(let e=0;e{e.length>t&&(t=e.length)})),t):void 0}reverse(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.reverse()}flipLists(e){if(e.list.length>0){const t=e.list[0].length;let i=!0;if(e.list.forEach((e=>{e.length!==t&&(i=!1)})),i){const i=[];for(let s=0;s{t.push(e[s])})),i.push(t)}return i}throw new Error("Lists are not of the same length")}throw new Error("List is empty")}groupNth(e){return(e=>{const{nrElements:t,list:i,keepRemainder:s}=e,r=t,n=[];let o=[];return i.forEach(((e,t)=>{o.push(e),(t+1)%r==0&&(n.push(o),o=[]),s&&t===i.length-1&&n.push(o)})),n})(e)}getListDepth(e){let t=0,i=!0,s=e.list;for(;i;){let e=!1;for(let t=0;t=0&&e.index<=t.length&&t.splice(e.index,0,e.item),t}addItemAtIndexes(e){let t=e.list;e.clone&&(t=structuredClone(e.list));let i=[...e.indexes];return i=i.filter((e=>e>=0&&e<=t.length)),i.sort(((e,t)=>e-t)),i.forEach(((i,s)=>{i>=0&&i+s<=t.length&&t.splice(i+s,0,e.item)})),t}addItemsAtIndexes(e){if(e.items.length!==e.indexes.length)throw new Error("Items and indexes must have the same length");for(let t=0;t0&&e.indexes[t-1]>e.indexes[t])throw new Error("Indexes must be in ascending order");let t=e.list;return e.clone&&(t=structuredClone(e.list)),[...e.indexes].forEach(((i,s)=>{i>=0&&i+s<=t.length&&t.splice(i+s,0,e.items[s])})),t}removeItemAtIndex(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.index>=0&&e.index<=t.length&&t.splice(e.index,1),t}removeNthItem(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let s=0;s{const s=e.points;return e.isClosed&&s.push(s[0]),e.color&&(Array.isArray(t)||(t=[]),Array.isArray(e.color)?t[i]=Ce.FromArray(e.color).toHexString():t[i]=e.color),s}));return this.geometryHelper.drawPolylines(e.polylinesMesh,i,e.updatable,e.size,e.opacity,t)}convertToNurbsCurve(e){return this.context.verb.geom.NurbsCurve.byPoints(e.polyline.points,1)}length(e){let t=0;for(let i=1;it.id===e.tagVariable.id));Object.keys(e.tag).forEach((i=>{t[i]=e.tag[i]})),t.needsUpdate=!0}else{const t=document.createElement("span"),i="_tag"+(new Date).getTime()+this.context.tagBag.length;e.tag.id=i,t.id=i,t.textContent=e.tag.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(t),e.tag.needsUpdate=!0,this.context.tagBag.push(e.tag)}return e.tag}drawTags(e){if(e.tagsVariable&&e.updatable){if(e.tagsVariable.length{const s=this.context.tagBag.find((e=>e.id===t.id)),r=e.tags[i];if(r)Object.keys(r).forEach((e=>{s[e]=r[e]})),s.needsUpdate=!0;else{this.context.tagBag=this.context.tagBag.filter((e=>e.id!==s.id));const e=document.getElementById(s.id);e.parentNode.removeChild(e)}}))}else{const t=[];e.tags.forEach(((i,s)=>{const r=document.createElement("span"),n="_tag"+(new Date).getTime()+this.context.tagBag.length;i.id=n,r.id=n,r.textContent=i.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(r),i.needsUpdate=!0,this.context.tagBag.push(i),t.push(i),e.tagsVariable=t}))}return e.tagsVariable}}class pG{constructor(e){this.context=e}angleBetween(e){return vr.FromRadians(this.context.verb.core.Vec.angleBetween(e.first,e.second)).degrees()}angleBetweenNormalized2d(e){return vr.FromRadians(this.context.verb.core.Vec.angleBetweenNormalized2d(e.first,e.second)).degrees()}positiveAngleBetween(e){return vr.FromRadians(this.context.verb.core.Vec.positiveAngleBetween(e.first,e.second,e.reference)).degrees()}addAll(e){return this.context.verb.core.Vec.addAll(e.vectors)}add(e){return this.context.verb.core.Vec.add(e.first,e.second)}all(e){return this.context.verb.core.Vec.all(e.vector)}cross(e){return this.context.verb.core.Vec.cross(e.first,e.second)}distSquared(e){return this.context.verb.core.Vec.distSquared(e.first,e.second)}dist(e){return this.context.verb.core.Vec.dist(e.first,e.second)}div(e){return this.context.verb.core.Vec.div(e.vector,e.scalar)}domain(e){return this.context.verb.core.Vec.domain(e.vector)}dot(e){return this.context.verb.core.Vec.dot(e.first,e.second)}finite(e){return this.context.verb.core.Vec.finite(e.vector)}isZero(e){return this.context.verb.core.Vec.isZero(e.vector)}lerp(e){return this.context.verb.core.Vec.lerp(e.fraction,e.first,e.second)}max(e){return this.context.verb.core.Vec.max(e.vector)}min(e){return this.context.verb.core.Vec.min(e.vector)}mul(e){return e.vector.map((t=>t*e.scalar))}neg(e){return this.context.verb.core.Vec.neg(e.vector)}normSquared(e){return this.context.verb.core.Vec.normSquared(e.vector)}norm(e){return this.context.verb.core.Vec.norm(e.vector)}normalized(e){return this.context.verb.core.Vec.normalized(e.vector)}onRay(e){return this.context.verb.core.Vec.onRay(e.point,e.vector,e.distance)}vectorXYZ(e){return[e.x,e.y,e.z]}vectorXY(e){return[e.x,e.y]}range(e){return this.context.verb.core.Vec.range(e.max)}signedAngleBetween(e){return vr.FromRadians(this.context.verb.core.Vec.signedAngleBetween(e.first,e.second,e.reference)).degrees()}span(e){return this.context.verb.core.Vec.span(e.min,e.max,e.step)}sub(e){return this.context.verb.core.Vec.sub(e.first,e.second)}sum(e){return this.context.verb.core.Vec.sum(e.vector)}}class fG{constructor(e){this.context=e,this.tolerance=1e-5,this.getArrayDepth=e=>Array.isArray(e)?1+Math.max(...e.map(this.getArrayDepth)):0}createOrUpdateSurfaceMesh(e,t,i,s,r,n){const o=()=>{const s=new cn;s.positions=e.positions,s.indices=e.indices,s.normals=e.normals,s.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;r&&(e=this.context.scene),t=new bo(`surface${Math.random()}`,e),o(),t.flipFaces(!1),s&&(t.material=s)}return s&&(t.material=s),n&&(t.isVisible=!1),t.isPickable=!1,t}createOrUpdateSurfacesMesh(e,t,i,s,r,n){const o=()=>{const s=e.pop(),r=new cn;r.positions=s.positions,r.indices=s.indices,r.normals=s.normals,r.uvs=s.uvs;const n=[];e.forEach((e=>{const t=new cn;t.positions=e.positions,t.indices=e.indices,t.normals=e.normals,t.uvs=e.uvs,n.push(t)})),r.merge(n),r.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;r&&(e=this.context.scene),t=new bo(`surface${Math.random()}`,e),o(),t.flipFaces(!1),s&&(t.material=s)}return s&&(t.material=s),n&&(t.isVisible=!1),t.isPickable=!1,t}transformControlPoints(e,t){return this.getFlatTransformations(e).forEach((e=>{t=this.transformPointsByMatrixArray(t,e)})),t}getFlatTransformations(e){let t=[];return 3===this.getArrayDepth(e)?e.forEach((e=>{t.push(...e)})):t=e,t}transformPointsByMatrixArray(e,t){const i=fe.FromArray(t);return this.transformPointsByMatrix(e,i)}transformPointsByMatrix(e,t){const i=[];for(const s of e){const e=new de(s[0],s[1],s[2]),r=de.TransformCoordinates(e,t);i.push([r.x,r.y,r.z])}return i}edgesRendering(e,t,i,s){e.enableEdgesRendering(),e.edgesWidth=t;const r=Array.isArray(s)?Ce.FromHexString(s[0]):Ce.FromHexString(s);e.color=r,e.edgesColor=new Ee(r.r,r.g,r.b,i)}drawPolyline(e,t,i,s,r,n){return this.drawPolylines(e,[t],i,s,r,n)}drawPolylines(e,t,i,s,r,n){const o=[];return t&&t.length>0?(t.forEach((e=>{o.push(e.map((e=>new de(e[0],e[1],e[2]))))})),e&&i?e.metadata.linesForRenderLengths.some(((e,t)=>e!==o[t].length))?(e.dispose(),(e=this.createLineSystem(i,o)).metadata={linesForRenderLengths:o.map((e=>e.length))}):e=Gd.CreateLineSystem("line-system"+Math.random(),{lines:o,instance:e,useVertexAlpha:!0,updatable:i},this.context.scene):(e=this.createLineSystem(i,o)).metadata={linesForRenderLengths:o.map((e=>e.length))},this.edgesRendering(e,s,r,n),e):void 0}createLineSystem(e,t){return Gd.CreateLineSystem(`lineSystem${Math.random()}`,{lines:t,useVertexAlpha:!0,updatable:e},this.context.scene)}removeConsecutiveDuplicates(e,t=!0){const i=[];if(e.length>1){for(let t=1;ti[0])))):i=e.points.map((()=>e.colours)),e.pointsMesh&&e.updatable?e.pointsMesh.getChildMeshes().length===t.length?this.updatePointsInstances(e.pointsMesh,t):(e.pointsMesh.dispose(),e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable)):e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable),e.pointsMesh}updatePointsInstances(e,t){const i=e.getChildMeshes(),s={};t.forEach(((e,t)=>{s[t]=new de(e[0],e[1],e[2])})),i.forEach((e=>{e.position=s[e.metadata.index]}))}setUpPositionsAndColours(e,t){const i=[],s=[];return t.length===e.length?e.forEach(((e,r)=>{i.push(...e),s.push(t[r].r,t[r].g,t[r].b,1)})):e.forEach(((e,r)=>{i.push(...e),s.push(t[0].r,t[0].g,t[0].b,1)})),{positions:i,colors:s}}createPointSpheresMesh(e,t,i,s,r,n){const o=t.map(((e,t)=>({position:e,color:i[t],index:t}))),a=Array.from(new Set(i)),l=a.map(((e,t)=>{const i=new yc(`mat${Math.random()}`,this.context.scene);i.disableLighting=!0,i.emissiveColor=Ce.FromHexString(e),i.alpha=s;const r=o.filter((t=>t.color===e));return{hex:a,material:i,positions:r}})),h=new bo(e,this.context.scene);return l.forEach((e=>{const t=Gd.CreateSphere(`sphere${Math.random()}`,{diameter:r,segments:6,updatable:n},this.context.scene);t.material=e.material,t.isVisible=!1,e.positions.forEach(((e,i)=>{const s=t.createInstance(`sphere-${i}-${Math.random()}`);s.position=new de(e.position[0],e.position[1],e.position[2]),s.metadata={index:e.index},s.parent=h,s.isVisible=!0}))})),h}}class mG{constructor(e,t,i){this.context=e,this.geometryHelper=t,this.line=i}drawPoint(e){return this.geometryHelper.drawPoint(e)}drawPoints(e){return this.geometryHelper.drawPoints(e)}drawPointsAsync(e){return Promise.resolve(this.drawPoints(e))}transformPoint(e){const t=e.transformation;let i=[e.point];return i=this.geometryHelper.transformControlPoints(t,i),i[0]}transformPoints(e){return this.geometryHelper.transformControlPoints(e.transformation,e.points)}transformsForPoints(e){if(e.points.length!==e.transformation.length)throw new Error("You must provide equal nr of points and transformations");return e.points.map(((t,i)=>this.geometryHelper.transformControlPoints(e.transformation[i],[t])[0]))}closestPointFromPointsDistance(e){return this.closestPointFromPointData(e).distance}closestPointFromPointsIndex(e){return this.closestPointFromPointData(e).index}closestPointFromPoints(e){return this.closestPointFromPointData(e).point}distance(e){const t=e.endPoint[0]-e.startPoint[0],i=e.endPoint[1]-e.startPoint[1],s=e.endPoint[2]-e.startPoint[2];return Math.sqrt(t*t+i*i+s*s)}distancesToPoints(e){return e.endPoints.map((t=>this.distance({startPoint:e.startPoint,endPoint:t})))}multiplyPoint(e){const t=[];for(let i=0;i{t.push(e[0]),i.push(e[1]),s.push(e[2])})),[t.reduce(((e,t)=>e+t),0)/e.points.length,i.reduce(((e,t)=>e+t),0)/e.points.length,s.reduce(((e,t)=>e+t),0)/e.points.length]}pointXYZ(e){return[e.x,e.y,e.z]}pointXY(e){return[e.x,e.y]}spiral(e){const t=e.phi,i=Math.log(t)/(Math.PI/e.widening),s=[],r=e.radius/e.numberPoints;for(let t=0;t{i[r]=[s[0]-e,s[1]-t,0]}))}return e.pointsOnGround&&i.forEach(((e,t)=>{i[t]=[e[0],0,e[1]]})),i}closestPointFromPointData(e){let t,i,s=Number.MAX_SAFE_INTEGER;for(let r=0;r{e(t)}))}}class vG{create(e){return e.text}split(e){return e.text.split(e.separator)}replaceAll(e){return e.text.split(e.search).join(e.replaceWith)}join(e){return e.list.join(e.separator)}toString(e){return e.item.toString()}toStringEach(e){return e.list.map((e=>e.toString()))}}class xG{constructor(){}}class bG{constructor(){this.assetManager=new xG}getFile(e){return this.assetManager.getAsset(e.fileName)}getLocalFile(e){return this.assetManager.getLocalAsset(e.fileName)}createObjectURL(e){return URL.createObjectURL(e.file)}createObjectURLs(e){return e.files.map((e=>URL.createObjectURL(e)))}}class TG{constructor(e){this.context=e}hexColor(e){return e.color}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.color);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:void 0}rgbToHex(e){const t=e.r,i=e.g,s=e.b;return`#${Number(16777216+65536*t+256*i+s).toString(16).substring(1,7)}`}hexToRgbMapped(e){const t=this.hexToRgb(e);return{r:this.context.remap(t.r,0,255,e.from,e.to),g:this.context.remap(t.g,0,255,e.from,e.to),b:this.context.remap(t.b,0,255,e.from,e.to)}}getRedParam(e){return this.hexToRgbMapped(e).r}getGreenParam(e){return this.hexToRgbMapped(e).g}getBlueParam(e){return this.hexToRgbMapped(e).b}rgbToRed(e){return e.rgb.r}rgbToGreen(e){return e.rgb.g}rgbToBlue(e){return e.rgb.b}}class yG{constructor(){this.canvasZoneClass="canvasZone",this.tolerance=1e-5,this.snapTolerance=1e-5,this.tagBag=[],this.timeoutBag=[],this.intervalBag=[],this.renderLoopBag=[],this.keyDownBag=[],this.keyUpBag=[],this.keyPressBag=[],this.currentlyPressedKeys=[]}getFile(e){return new Promise(((t,i)=>{if(e){const s=new FileReader;s.readAsText(e,"UTF-8"),s.onload=e=>{const i=e.target.result;t(i)},s.onerror=e=>{i()}}else i()}))}remap(e,t,i,s,r){return(e-t)/(i-t)*(r-s)+s}}!function(e){e[e.loading=0]="loading",e[e.loaded=1]="loaded",e[e.initialised=2]="initialised",e[e.computing=3]="computing"}(oG||(oG={}));class SG{constructor(){this.jscadWorkerState=new ak,this.promisesMade=[]}jscadWorkerAlreadyInitialised(){return!!this.jscadWorker}setJscadWorker(e){this.jscadWorker=e,this.jscadWorker.onmessage=({data:e})=>{if("jscad-initialised"===e)this.jscadWorkerState.next({state:oG.initialised});else if("busy"===e)this.jscadWorkerState.next({state:oG.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.jscadWorkerState.next({state:oG.loaded}):this.jscadWorkerState.next({state:oG.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,s={uid:i},r=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=r,this.promisesMade.push(s),this.jscadWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),r}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}var CG=i(258);class EG{constructor(e){this.context=e}stringify(e){return JSON.stringify(e.json)}parse(e){return JSON.parse(e.text)}query(e){return this.context.jsonpath.query(e.json,e.query)}setValue(e){const t=Object.assign({},structuredClone(e.json));return this.context.jsonpath.value(t,e.path,e.value),t}setValuesOnPaths(e){const t=Object.assign({},structuredClone(e.json));return e.paths.forEach(((i,s)=>{this.context.jsonpath.value(t,i,e.values[s])})),t}paths(e){return this.context.jsonpath.paths(e.json,e.query)}pathsAsStrings(e){return this.context.jsonpath.paths(e.json,e.query).map((e=>this.context.jsonpath.stringify(e)))}createEmpty(){return{}}previewAndSaveJson(e){e.json&&this.context.promptPrintSave({text:e.json,isJson:!0,hidden:!1})}previewJson(e){e.json&&this.context.promptPrint({text:e.json,isJson:!0,hidden:!1})}}var AG=i(615);class PG{boolean(e){return e.boolean}randomBooleans(e){const t=[];for(let i=0;i{if(ie.thresholdTotalFalse)t.push(!1);else{const s=i-e.thresholdTotalTrue,r=(e.thresholdTotalFalse-e.thresholdTotalTrue)/e.nrLevels,n=Math.ceil(s/r)/e.nrLevels;Math.random()>n?t.push(!0):t.push(!1)}})),t}thresholdBooleanList(e){const t=[];return e.numbers.forEach((i=>{i!e)):t}thresholdGapsBooleanList(e){const t=[];return e.numbers.forEach((i=>{let s=!1;e.gapThresholds.forEach((e=>{const r=e[0],n=e[1];i>=r&&i<=n&&(t.push(!0),s=!0)})),s||t.push(!1)})),e.inverse?t.map((e=>!e)):t}not(e){return!e.boolean}notList(e){return e.booleans.map((e=>!e))}compare(e){switch(e.operator){case"==":return e.first==e.second;case"!=":return e.first!=e.second;case"===":return e.first===e.second;case"!==":return e.first!==e.second;case"<":return e.first":return e.first>e.second;case">=":return e.first>=e.second;default:return!1}}valueGate(e){return e.boolean?e.value:void 0}firstDefinedValueGate(e){let t;return t=void 0!==e.value1?e.value1:void 0!==e.value2?e.value2:void 0,t}}class RG{constructor(){this.context=new yG,this.jscadWorkerManager=new SG,this.occtWorkerManager=new hk;const e=new fG(this.context);this.color=new TG(this.context),this.babylon=new XV(this.context,e,this.color),this.vector=new pG(this.context),this.line=new hG(this.context,e),this.point=new mG(this.context,e,this.line),this.polyline=new dG(this.context,e),this.verb=new PU(this.context,e),this.jscad=new cU(this.jscadWorkerManager,this.context,e),this.tag=new _G(this.context),this.time=new gG(this.context),this.occt=new fU(this.context,this.occtWorkerManager,e,this.jscad.text,this.vector),this.asset=new bG,this.math=new uG,this.logic=new PG,this.json=new EG(this.context),this.text=new vG,this.lists=new cG,this.draw=new lG(this.point,this.line,this.polyline,this.babylon.node,this.verb.curve,this.verb.surface,this.jscad,this.occt,this.tag,this.context)}init(e,t,i,s){this.context.scene=e,s&&(this.context.havokPlugin=s);const r={geom:CG.geom,core:CG.core};this.context.verb=r,this.context.jsonpath=AG,t&&this.occtWorkerManager.setOccWorker(t),i&&this.jscadWorkerManager.setJscadWorker(i)}}const IG="assets/textures";class MG{constructor(e){this.name="",this.scene=void 0,this.wAng=0,this.uScale=1,this.vScale=1,this.color=void 0,this.albedoTextureUrl=void 0,this.microSurfaceTextureUrl=void 0,this.bumpTextureUrl=void 0,this.metallic=.1,this.roughness=.9,this.zOffset=2,Object.keys(this).forEach((t=>this[t]=e[t]))}}class OG{static simpleBlackMaterial(e){const t=new Um("blackMaterial"+Math.random(),e);return t.albedoColor=new Ce(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2,t}static rock1Material(e,t,i){const s=new MG({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.rock1.default.albedo,bumpTextureUrl:OG.textures.rock1.microSurfaceTexture,microSurfaceTextureUrl:OG.textures.rock1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static wood1Material(e,t,i){const s=new MG({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.wood1.light.albedo,bumpTextureUrl:OG.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static wood2Material(e,t,i){const s=new MG({name:"wood2",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.wood2.light.albedo,microSurfaceTextureUrl:OG.textures.wood2.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static wood3Material(e,t,i){const s=new MG({name:"wood3",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.wood1.dark.albedo,microSurfaceTextureUrl:OG.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static brownPlanks(e,t,i){const s=new MG({name:"brownPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.brownPlanks.light.albedo,microSurfaceTextureUrl:OG.textures.brownPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static woodenPlanks(e,t,i){const s=new MG({name:"woodenPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.woodenPlanks.light.albedo,microSurfaceTextureUrl:OG.textures.woodenPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static glass(e,t){const i=new Um("faceGlassMaterial"+Math.random(),e);return i.albedoColor=Ce.FromHexString(t),i.ambientColor=Ce.FromHexString("#ffffff"),i.metallic=.8,i.roughness=.1,i.zOffset=1,i.alpha=.5,i}static brushedConcrete(e,t,i){const s=new MG({name:"brushedConcrete",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.brushedConcrete.grey.albedo,microSurfaceTextureUrl:OG.textures.brushedConcrete.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(s)}static metal1(e,t,i){const s=new MG({name:"metal1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:OG.textures.metal1.light.albedo,microSurfaceTextureUrl:OG.textures.metal1.microSurfaceTexture,bumpTextureUrl:OG.textures.metal1.light.roughness,metallic:.3,roughness:.6,zOffset:2});return OG.createMaterial(s)}static roughPlastic(e,t){const i=new MG({name:"roughPlastic-"+t,color:t,scene:e,metallic:.1,roughness:.9,zOffset:2});return OG.createMaterial(i)}static createMaterial(e){const t=new Um(e.name,e.scene);return e.color&&(t.albedoColor=Ce.FromHexString(e.color)),e.albedoTextureUrl&&(t.albedoTexture=OG.createTexture(e.albedoTextureUrl,e)),e.microSurfaceTextureUrl&&(t.microSurfaceTexture=OG.createTexture(e.microSurfaceTextureUrl,e)),e.bumpTextureUrl&&(t.bumpTexture=OG.createTexture(e.bumpTextureUrl,e)),t.metallic=e.metallic,t.roughness=e.roughness,t.zOffset=e.zOffset,t}static createTexture(e,t){const i=new Vo(e,t.scene);return i.uScale=t.uScale,i.vScale=t.vScale,i.wAng=t.wAng,i}}OG.textures={wood1:{microSurfaceTexture:`${IG}/Wood048_1K/Wood048_1K_NormalGL.jpg`,light:{albedo:`${IG}/Wood048_1K/Wood048_1K_Light.jpg`},dark:{albedo:`${IG}/Wood048_1K/Wood048_1K_Color_Dark.jpg`}},wood2:{microSurfaceTexture:`${IG}/Wood084_1K/Wood084A_1K_NormalGL.jpg`,light:{albedo:`${IG}/Wood084_1K/Wood084A_1K_Color.jpg`}},metal1:{microSurfaceTexture:`${IG}/metal_1/Metal029_1K_Displacement.jpg`,light:{albedo:`${IG}/metal_1/Metal029_1K_Color.jpg`,normalGL:`${IG}/metal_1/Metal029_1K_NormalGL.jpg`,roughness:`${IG}/metal_1/Metal029_1K_Roughness.jpg`,metalness:`${IG}/metal_1/Metal029_1K_Metalness.jpg`}},brownPlanks:{microSurfaceTexture:`${IG}/brown_planks/brown_planks_05_nor_gl_1k.jpg`,light:{albedo:`${IG}/brown_planks/brown_planks_05_diff_1k.jpg`}},woodenPlanks:{microSurfaceTexture:`${IG}/wooden_planks/wooden_planks_nor_gl_1k.jpg`,light:{albedo:`${IG}/wooden_planks/wooden_planks_diff_1k.jpg`}},brushedConcrete:{microSurfaceTexture:`${IG}/brushed_concrete/brushed_concrete_03_nor_gl_1k.jpg`,sand:{albedo:`${IG}/brushed_concrete/brushed_concrete_03_diff_1k.jpg`},grey:{albedo:`${IG}/brushed_concrete/brushed_concrete_03_diff_grey_1k.jpg`}},rock1:{microSurfaceTexture:`${IG}/Rock044_1K/Rock044_1K_NormalGL.jpg`,default:{albedo:`${IG}/Rock044_1K/Rock044_1K_Color.jpg`,roughness:`${IG}/Rock044_1K/Rock044_1K_Roughness.jpg`}}};var DG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class wG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return DG(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.wingtipVilla",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},chimney:{shape:t.shapes.find((e=>e.id===t.data.chimney.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return DG(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const s=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),r=s.getChildMeshes(),n=r[0],o=r[1],a=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),l=a.getChildMeshes(),h=l[0],c=l[1],u=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),d=u.getChildMeshes(),_=d[0],p=d[1],f=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),m=f.getChildMeshes(),g=m[0],v=m[1],x=yield this.draw.drawAnyAsync({entity:e.chimney.shape,options:i}),b=x.getChildMeshes(),T=b[0],y=b[1],S=new Vo("assets/textures/Wood048_1K/Wood048_1K_Red.jpg",this.context.scene),C=new Vo("assets/textures/Wood048_1K/Wood048_1K_Color_Dark.jpg",this.context.scene),E=new Vo("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);S.uScale=.3,S.vScale=.3,S.wAng=Math.PI/2,C.uScale=.3,C.vScale=.3,C.wAng=Math.PI/2,E.uScale=.3,E.vScale=.3,E.wAng=Math.PI/2;const A=new Um("wood-red",this.context.scene);A.albedoTexture=S,A.microSurfaceTexture=E,A.metallic=0,A.roughness=1,A.zOffset=2;const P=new Um("wood-dark",this.context.scene);return P.albedoTexture=C,P.microSurfaceTexture=E,P.metallic=0,P.roughness=1,P.zOffset=2,n.material=A,h.material=OG.wood1Material(this.context.scene,Math.PI/2,.3),_.material=A,g.material=A,T.material=P,n.parent=t,h.parent=t,_.parent=t,g.parent=t,T.parent=t,o.parent=t,c.parent=t,p.parent=t,v.parent=t,y.parent=t,s.dispose(),u.dispose(),a.dispose(),f.dispose(),x.dispose(),t}))}dispose(e){return DG(this,void 0,void 0,(function*(){const t=[e.compound,e.chimney.shape,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}}var NG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class FG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}dispose(e){return NG(this,void 0,void 0,(function*(){const t=[e.compound,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}create(e){return NG(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.chirpyChalet",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return NG(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const s=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),r=s.getChildMeshes()[0],n=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),o=n.getChildMeshes()[0],a=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),l=a.getChildMeshes()[0],h=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),c=h.getChildMeshes()[0],u=new Vo("assets/textures/Wood048_1K/Wood048_1K_Color.jpg",this.context.scene),d=new Vo("assets/textures/Wood048_1K/Wood048_1K_Light.jpg",this.context.scene),_=new Vo("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);d.uScale=.3,d.vScale=.3,d.wAng=Math.PI/2,u.uScale=.3,u.vScale=.3,u.wAng=Math.PI/2,_.uScale=.3,_.vScale=.3,_.wAng=Math.PI/2;const p=new Um("roof",this.context.scene);p.albedoTexture=u,p.microSurfaceTexture=_,p.metallic=0,p.roughness=1,p.zOffset=2;const f=new Um("walls",this.context.scene);return f.albedoTexture=d,f.microSurfaceTexture=_,f.metallic=0,f.roughness=1,f.zOffset=2,r.material=p,o.material=f,l.material=p,c.material=p,s.setParent(t),a.setParent(t),n.setParent(t),h.setParent(t),t}))}}class BG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.wingtipVilla=new wG(this.occWorkerManager,this.context,this.draw,this.occt),this.chirpyChalet=new FG(this.occWorkerManager,this.context,this.draw,this.occt)}}class LG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.birdhouses=new BG(this.occWorkerManager,this.context,this.draw,this.occt)}}var kG,VG,UG,GG,zG,WG,HG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class XG{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return HG(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.serenitySwirl",e);return t?{type:t.data.type,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return HG(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new Um("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ce(1,1,1),n.ambientColor=Ce.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}dispose(e){return HG(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}!function(e){e.low="low",e.middle="middle",e.high="high"}(kG||(kG={}));class YG{constructor(){this.lod=kG.low}}class QG{}class jG{constructor(e,t,i,s,r,n,o,a,l){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.addRadiusNarrow=i),void 0!==s&&(this.addRadiusWide=s),void 0!==r&&(this.addMiddleHeight=r),void 0!==n&&(this.addTopHeight=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l)}}class KG{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class $G{}class qG{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=kG.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==i&&(this.archCenterThickness=i),void 0!==s&&(this.edgesThickness=s),void 0!==r&&(this.thickness=r),void 0!==n&&(this.baseHeight=n),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.origin=h),void 0!==c&&(this.direction=c),void 0!==u&&(this.scale=u)}}class ZG{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class JG{}class ez{}class tz{}class iz{constructor(e,t,i,s,r,n,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==i&&(this.fullModel=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.decorationThickness=r),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class sz{constructor(){this.type="parametric-model",this.name="eternalLove"}}class rz{}class nz{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.fillet=r),void 0!==n&&(this.nrOfHandles=n),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.scale=h),void 0!==c&&(this.origin=c),void 0!==u&&(this.direction=u)}}class oz{constructor(){this.type="parametric-model",this.name="calmCup"}}class az{}class lz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==s&&(this.radiusMidOffset=s),void 0!==r&&(this.rotationTopAngle=r),void 0!==n&&(this.rotationMidAngle=n),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==l&&(this.nrSkinCellDivisionsTop=l),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==c&&(this.skinCellOuterHeight=c),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==_&&(this.skinCellTopHeight=_),void 0!==p&&(this.thickness=p),void 0!==f&&(this.bottomThickness=f),void 0!==m&&(this.precision=m),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==x&&(this.origin=x),void 0!==b&&(this.direction=b)}}class hz{constructor(){this.type="parametric-model",this.name="dragonCup"}}class cz{}class uz{}class dz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==i&&(this.widthBack=i),void 0!==s&&(this.widthFront=s),void 0!==r&&(this.length=r),void 0!==n&&(this.backOffset=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.phoneHeight=h),void 0!==c&&(this.phoneWidth=c),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdges=_),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class _z{constructor(){this.type="parametric-model",this.name="phoneNest"}}class pz extends QG{}class fz{}class mz extends QG{}class gz{}class vz{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class xz{}class bz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==i&&(this.nrSides=i),void 0!==s&&(this.nrOffsets=s),void 0!==r&&(this.height=r),void 0!==n&&(this.coverHeight=n),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==l&&(this.radiusOffset=l),void 0!==h&&(this.thickness=h),void 0!==c&&(this.ornamentalThickness=c),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==_&&(this.fillet=_),void 0!==p&&(this.precision=p),void 0!==f&&(this.rotation=f),void 0!==m&&(this.scale=m),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class Tz{constructor(){this.type="parametric-model",this.name="spicyBox"}}class yz{}class Sz{}class Cz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x,b,T,y,S,C,E,A,P,R,I){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=kG.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==i&&(this.terraceWidth=i),void 0!==s&&(this.widthSecondWing=s),void 0!==r&&(this.lengthSecondWing=r),void 0!==n&&(this.heightWalls=n),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==l&&(this.roofOffset=l),void 0!==h&&(this.roofInsideOverhang=h),void 0!==c&&(this.roofMaxDistAttachmentBeams=c),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==_&&(this.roofOutsideOverhang=_),void 0!==p&&(this.columnSize=p),void 0!==f&&(this.ceilingBeamHeight=f),void 0!==m&&(this.ceilingBeamWidth=m),void 0!==g&&(this.nrCeilingBeamsBetweenColumns=g),void 0!==v&&(this.distBetweenColumns=v),void 0!==x&&(this.floorHeight=x),void 0!==b&&(this.groundLevel=b),void 0!==T&&(this.facadePanelThickness=T),void 0!==y&&(this.windowWidthOffset=y),void 0!==S&&(this.windowHeightOffset=S),void 0!==C&&(this.windowFrameThickness=C),void 0!==E&&(this.windowGlassFrameThickness=E),void 0!==A&&(this.lod=A),void 0!==P&&(this.skinOpacity=P),void 0!==R&&(this.rotation=R),void 0!==I&&(this.origin=I)}}class Ez{constructor(){this.type="parametric-model",this.name="zenHideout"}}class Az{}class Pz{}class Rz{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class Iz{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class Mz extends Iz{}class Oz extends Rz{}class Dz{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class wz{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class Nz extends Dz{}class Fz extends wz{}class Bz{}class Lz{}class kz{}class Vz{}class Uz{}class Gz{}class zz{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class Wz extends zz{}class Hz{}class Xz{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=kG.high,this.center=[0,0,0],this.direction=[0,1,0]}}class Yz extends Xz{}class Qz{}class jz{}class Kz{constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class $z{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.holeDiameter=r),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.rotation=c),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class qz{constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class Zz{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.holeDiameter=r),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.roofAngle=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class Jz{constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class eW{}class tW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==i&&(this.backRestHeight=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r),void 0!==n&&(this.thickness=n),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.precision=h),void 0!==c&&(this.drawEdges=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==_&&(this.origin=_),void 0!==p&&(this.direction=p)}}class iW{constructor(){this.type="parametric-model",this.name="snakeChair"}}class sW extends QG{}class rW{}class nW extends QG{}class oW{}class aW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class lW{}class hW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.topThickness=s),void 0!==r&&(this.topOffset=r),void 0!==n&&(this.bottomThickness=n),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==l&&(this.radiusLegBottom=l),void 0!==h&&(this.nrLegPairs=h),void 0!==c&&(this.precision=c),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==_&&(this.scale=_),void 0!==p&&(this.origin=p),void 0!==f&&(this.direction=f)}}class cW{constructor(){this.type="parametric-model",this.name="elegantTable"}}class uW extends QG{}class dW{}class _W extends QG{}class pW extends QG{}class fW{constructor(){this.index=0}}class mW{}class gW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class vW{}class xW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.chamfer=s),void 0!==r&&(this.topThickness=r),void 0!==n&&(this.topGlassOffset=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==l&&(this.shelfTopOffset=l),void 0!==h&&(this.shelfThickness=h),void 0!==c&&(this.legWidth=c),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdges=_),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class bW{constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class TW extends QG{}class yW{}class SW extends QG{}class CW extends QG{}class EW extends QG{}class AW{constructor(){this.index=0}}class PW{}class RW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class IW{}class MW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.supportLength=s),void 0!==r&&(this.shelfHeight=r),void 0!==n&&(this.thickness=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==l&&(this.nrOrnamentPlanks=l),void 0!==h&&(this.ornamentDepth=h),void 0!==c&&(this.filletRadius=c),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==_&&(this.rotation=_),void 0!==p&&(this.scale=p),void 0!==f&&(this.origin=f),void 0!==m&&(this.direction=m)}}class OW{constructor(){this.type="parametric-model",this.name="snakeTable"}}class DW extends QG{}class wW{}class NW extends QG{}class FW{}class BW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(VG||(VG={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(UG||(UG={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(GG||(GG={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(zG||(zG={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(WG||(WG={}));const LW=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class kW{constructor(e,t,i,s,r,n,o,a,l){this.text="bitbybit.dev",this.fontType=VG.Roboto,this.fontVariant=UG.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=WG.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==i&&(this.fontVariant=i),void 0!==s&&(this.fontSize=s),void 0!==r&&(this.height=r),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==l&&(this.originAlignment=l)}}class VW{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.facePlanar=!1,this.faceTextVar=GG.separatedExtrusion,this.text="bitbybit.dev",this.fontType=VG.Roboto,this.fontVariant=UG.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=WG.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.faceTextVar=i),void 0!==s&&(this.text=s),void 0!==r&&(this.fontType=r),void 0!==n&&(this.fontVariant=n),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.originParamU=h),void 0!==c&&(this.originParamV=c),void 0!==u&&(this.originAlignment=u)}}class UW{constructor(){this.type="parametric-model",this.name="text3d"}}class GW{constructor(){this.index=0}}class zW{}class WW{}class HW{constructor(e,t,i,s,r,n,o,a,l,h){this.faceTextVar=GG.separatedExtrusion,this.text="bitbybit.dev",this.fontType=VG.Roboto,this.fontVariant=UG.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=WG.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==i&&(this.fontType=i),void 0!==s&&(this.fontVariant=s),void 0!==r&&(this.fontSize=r),void 0!==n&&(this.height=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==l&&(this.originParamV=l),void 0!==h&&(this.originAlignment=h)}}class XW{constructor(e,t,i){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.definitions=i)}}class YW{constructor(e,t,i,s){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==s&&(this.height=s)}}class QW{constructor(e,t,i,s,r,n,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==i&&(this.uNumber=i),void 0!==s&&(this.vNumber=s),void 0!==r&&(this.affectMinHeight=r),void 0!==n&&(this.affectMaxHeight=n),void 0!==o&&(this.precision=o)}}class jW{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class KW{constructor(){this.index=0}}class $W{}class qW{}class ZW{}class JW{}class eH{constructor(){this.faceIndex=0}}class tH{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class iH{constructor(){this.faceIndex=0,this.uIndex=0}}class sH{constructor(){this.faceIndex=0,this.vIndex=0}}class rH{}class nH{}var oH;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(oH||(oH={}));class aH{static parse(e,t){var i;const s=[e],r=new Set;for(;s.length>0;){const e=s.pop();if("object"==typeof e&&null!==e&&!r.has(e))if(r.add(e),Array.isArray(e))for(let t=0;tt.id===e.shapes[r])))||void 0===i?void 0:i.shape)}for(const t in e)s.push(e[t])}}return e}}var lH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class hH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return lH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.arabicArchway",e);if(t){const e=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},e),{type:t.data.type,name:t.data.name,compound:t.compound,shapes:t.shapes,originalInputs:t.data.originalInputs})}}))}drawModel(e,t=.003){return lH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;this.materials||(this.materials=this.createMaterials(e.originalInputs.lod)),s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?e.originalInputs.lod===kG.high&&"compound"===t?i(void 0):this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,t)=>{const s=o[t];if(s){if(s.parent=i,void 0!==this.materials[e]){const t=s.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}s.name=e,s.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=s}})),i}))}dispose(e){return lH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}disposeMaterials(){this.materials&&Object.keys(this.materials).forEach((e=>{const t=this.materials[e];t&&t.dispose()}))}createMaterials(e){const t=new ez;return e===kG.high?t.compound=this.createBaseMaterial():t.compound=this.createOpaqueMaterial(),t.vasePartsCompound=this.createBaseMaterial(),t.glassPartsCompound=this.createGlassMaterial(),t.vaseBaseCompound=this.createBaseMaterial(),t}createOpaqueMaterial(){const e=new Um("opaqueMat"+Math.random(),this.context.scene);return e.albedoColor=new Ce(1,1,1),e.ambientColor=Ce.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e.backFaceCulling=!1,e.alpha=.3,e}createBaseMaterial(){const e=new Um("faceMaterial"+Math.random(),this.context.scene);return e.albedoColor=new Ce(1,1,1),e.ambientColor=Ce.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e}createGlassMaterial(){const e=new Um("faceGlassMaterial"+Math.random(),this.context.scene);return e.albedoColor=new Ce(0,0,.05),e.ambientColor=Ce.FromHexString("#ffffff"),e.metallic=.8,e.roughness=.1,e.zOffset=1,e.alpha=.5,e}}class cH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.serenitySwirl=new XG(this.occWorkerManager,this.context,this.draw,this.occt),this.arabicArchway=new hH(this.occWorkerManager,this.context,this.draw,this.occt)}}var uH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class dH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return uH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.eternalLove",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return uH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new Um("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ce(1,.9,1),n.ambientColor=Ce.FromHexString("#ff00ff"),n.metallic=.8,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}dispose(e){return uH(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}class _H{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.eternalLove=new dH(this.occWorkerManager,this.context,this.draw,this.occt)}}var pH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class fH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return pH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.calmCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e){return pH(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new Um("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=new Ce(1,1,1),r.ambientColor=Ce.FromHexString("#ffffff"),r.metallic=.8,r.roughness=.7,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}dispose(e){return pH(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}var mH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class gH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return mH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.dragonCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}getCompoundShape(e){return e.model.compound}drawModel(e){return mH(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#617bff",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new Um("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=Ce.FromHexString("#2b00ff"),r.ambientColor=Ce.FromHexString("#ffffff"),r.metallic=.9,r.roughness=.3,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}}class vH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.calmCup=new fH(this.occWorkerManager,this.context,this.draw,this.occt),this.dragonCup=new gH(this.occWorkerManager,this.context,this.draw,this.occt)}}var xH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class bH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return xH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.phoneNest",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}drawOptions(e){return e}drawModel(e,t){return xH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#ffffff",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?("phone"===t&&(s.edgeColour="#000000"),this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)}))):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return xH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="phone-nest-",t=new fz,i=OG.wood3Material(this.context.scene,Math.PI/2,1);i.name=e+i.name,t.main=i;const s=OG.glass(this.context.scene,"#000000");return s.name=e+s.name,t.phone=s,t}}class TH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.phoneNest=new bH(this.occWorkerManager,this.context,this.draw,this.occt)}}class yH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.vases=new cH(this.occWorkerManager,this.context,this.draw,this.occt),this.cups=new vH(this.occWorkerManager,this.context,this.draw,this.occt),this.medals=new _H(this.occWorkerManager,this.context,this.draw,this.occt),this.desktop=new TH(this.occWorkerManager,this.context,this.draw,this.occt)}}var SH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class CH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return SH(this,void 0,void 0,(function*(){void 0===this.materials&&(this.materials=this.createMaterials()),void 0===this.skin&&(this.skin=this.createSkin());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.zenHideout",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e,t=.003){return SH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;if(s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.06,s.precision=t,e.originalInputs.lod===kG.high&&e.drawingPart){const t={},r=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((s=>{s.isVisible=!1,s.getChildMeshes().forEach((e=>e.isVisible=!1)),!0===this.skin[t]&&(s.visibility=e.originalInputs.skinOpacity,s.getChildMeshes().forEach((t=>t.visibility=e.originalInputs.skinOpacity))),i(s)}),(()=>{i(void 0)})):i(void 0)})))),n=yield Promise.all(r);Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const r=n[s];if(r){if(r.parent=i,void 0!==this.materials[e]){const t=r.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}r.name=e,r.isVisible=!0,r.getChildMeshes().forEach((e=>e.isVisible=!0)),t[e]=r}}))}else if(e.originalInputs.lod===kG.middle){const t=new Um("brepMaterial"+Math.random(),this.context.scene);t.albedoColor=new Ce(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s});r.getChildMeshes()[0].material=t,r.material=t,r.parent=i}else e.originalInputs.lod===kG.low&&(s.edgeColour="#e89668",s.edgeWidth=10,(yield this.draw.drawAnyAsync({entity:e.compound,options:s})).parent=i);return i}))}dispose(e){return SH(this,void 0,void 0,(function*(){const t=e.shapes.map((e=>e.shape));yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="zen-hideout-",t=new Pz,i=new zv(e+"windowGlassCompound",this.context.scene);i.alpha=.2,i.metallic=.9,i.roughness=.1,i.baseColor=new Ce(.9,.9,1),i.zOffset=2,t.windowGlassCompound=i;const s=new zv(e+"windowGlassCompound",this.context.scene);s.metallic=.1,s.roughness=.8,s.baseColor=new Ce(.05,.05,.05),s.zOffset=2,t.windowFrameCompound=s;const r=new zv(e+"glassFramesCompound",this.context.scene);r.metallic=.1,r.roughness=.8,r.baseColor=new Ce(0,0,0),r.zOffset=2,t.glassFramesCompound=r;const n=OG.metal1(this.context.scene,0,.3);t.roofCoverFirstCompound=n,t.roofCoverSecondCompound=n;const o=OG.wood1Material(this.context.scene,0,1);t.beamsCompound=o,t.columnsCompound=o;const a=OG.woodenPlanks(this.context.scene,0,1);t.firstFloorExteriorPanelsCompound=a;const l=new zv(e+"firstFloorInteriorPanelsCompound",this.context.scene);l.metallic=.1,l.roughness=.8,l.baseColor=new Ce(.1,.1,.1),l.zOffset=2,t.firstFloorInteriorPanelsCompound=l;const h=OG.wood3Material(this.context.scene,Math.PI/2,1);t.roofExteriorPanelsCompound=h;const c=new zv(e+"roofInteriorPanelsCompound",this.context.scene);c.metallic=.1,c.roughness=.8,c.baseColor=new Ce(.3,.3,.3),c.zOffset=2,t.roofInteriorPanelsCompound=c;const u=OG.wood2Material(this.context.scene,0,.5);t.floorCompound=u;const d=new zv(e+"ceilingCompound",this.context.scene);d.metallic=.3,d.roughness=.7,d.baseColor=new Ce(1,1,1),d.zOffset=2,t.ceilingCompound=d;const _=OG.brushedConcrete(this.context.scene,0,1);return t.stairsCompound=_,t}createSkin(){return{windowGlassCompound:!0,glassFramesCompound:!1,windowFrameCompound:!1,beamsCompound:!1,columnsCompound:!1,firstFloorExteriorPanelsCompound:!0,firstFloorInteriorPanelsCompound:!0,roofExteriorPanelsCompound:!0,roofInteriorPanelsCompound:!0,roofCoverFirstCompound:!0,roofCoverSecondCompound:!0,floorCompound:!0,ceilingCompound:!0,stairsCompound:!1}}}class EH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.zenHideout=new CH(this.occWorkerManager,this.context,this.draw,this.occt)}}class AH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.houses=new EH(this.occWorkerManager,this.context,this.draw,this.occt)}}class PH{lodEnum(e){return e.lod}}var RH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class IH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return RH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.elegantTable",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return RH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#bc7e5b",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return RH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="elegant-table-",t=new dW,i=OG.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i;const s=OG.wood1Material(this.context.scene,Math.PI/2,2);s.name=e+i.name,t.topBase=s;const r=OG.wood1Material(this.context.scene,0,1);return r.name=e+i.name,t.legs=r,t}}var MH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class OH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return MH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.goodCoffeeTable",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return MH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#bc7e5b",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return MH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="good-coffee-table-",t=new yW,i=OG.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i,t.legs=i,t.shelf=i;const s=OG.glass(this.context.scene,"#000000");return s.name=e+i.name,t.topGlass=s,t}}var DH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class wH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return DH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeTable",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getGlassShape(e){return e.model.mainPart.shapes.glass}getMainShape(e){return e.model.mainPart.shapes.main}getTopCenterPoint(e){return e.model.mainPart.topCenter}drawOptions(e){return e}drawModel(e,t){return DH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#000000",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return DH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="snake-table-",t=new wW,i=OG.roughPlastic(this.context.scene,"#ffffff");i.name=e+i.name,t.main=i;const s=OG.glass(this.context.scene,"#000000");return s.name=e+s.name,t.glass=s,t}}class NH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.elegantTable=new IH(this.occWorkerManager,this.context,this.draw,this.occt),this.goodCoffeeTable=new OH(this.occWorkerManager,this.context,this.draw,this.occt),this.snakeTable=new wH(this.occWorkerManager,this.context,this.draw,this.occt)}}var FH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class BH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return FH(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeChair",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getSittingWireShape(e){return e.model.mainPart.shapes.sittingWire}getSittingAreaCenterPoint(e){return e.model.mainPart.sittingCenter}drawOptions(e){return e}drawModel(e,t){return FH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#000000",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return FH(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e=new rW,t=OG.roughPlastic(this.context.scene,"#ffffff");return t.name="snake-chair-"+t.name,e.main=t,e}}class LH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.snakeChair=new BH(this.occWorkerManager,this.context,this.draw,this.occt)}}class kH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.chairs=new LH(this.occWorkerManager,this.context,this.draw,this.occt),this.tables=new NH(this.occWorkerManager,this.context,this.draw,this.occt)}}class VH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.kidsCorner=new LG(this.occWorkerManager,this.context,this.draw,this.occt),this.threeDPrinting=new yH(this.occWorkerManager,this.context,this.draw,this.occt),this.architecture=new AH(this.occWorkerManager,this.context,this.draw,this.occt),this.furniture=new kH(this.occWorkerManager,this.context,this.draw,this.occt),this.enums=new PH}}var UH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class GH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return UH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3d",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextOnFace(e){return UH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3dFace",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextsOnFace(e){return UH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.texts3dFace",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}definition3dTextOnFace(e){return e}drawModel(e,t=.003){return UH(this,void 0,void 0,(function*(){const i=new bo("brepMesh"+Math.random(),this.context.scene),s=new gV.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new Um("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ce(1,1,1),n.ambientColor=Ce.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}getCompoundShape(e){return e.model.compound}getCharacterShape(e){if(e.index<0||e.index>=e.model.characterParts.length)throw new Error("Index is out of bounds.");return e.model.characterParts[e.index].shapes.compound}getCharacterShapes(e){return e.model.characterParts.map((e=>e.shapes.compound))}getCharacterCenterCoordinates(e){return e.model.characterCenterCoordinates}getFaceCutout(e){if(e.model.faceParts){const t=e.model.faceParts.filter((e=>e.type===zG.cutout)).map((e=>e.shapes.face));if(t.length>0)return t[0];throw new Error("No cutout was found.")}throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAllFacesOfCutout(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===zG.cutout||e.type===zG.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getCutoutsInsideCharacters(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===zG.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAdvanceWidth(e){return e.model.advanceWidth}}var zH,WH=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class HH{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}createPyramidSimple(e){return WH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimple",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createPyramidSimpleAffectors(e){return WH(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimpleAffectors",e),i=aH.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e){return WH(this,void 0,void 0,(function*(){const t=new bo("brepMesh"+Math.random(),this.context.scene),i=new gV.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=1,i.precision=e.originalInputs.precision;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new Um("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=new Ce(1,1,1),r.ambientColor=Ce.FromHexString("#ffffff"),r.metallic=.3,r.roughness=.6,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}getCompoundShape(e){return e.model.compound}getCompoundShapeOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t.shapes.compound;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getAllPyramidCells(e){return e.model.faceParts.map((e=>e.cells)).flat()}getAllPyramidCellsOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex));throw new Error("Face index is out of range")}getAllPyramidUCellsOnFaceAtV(e){if(e.model.faceParts&&e.faceIndext.vIndex===e.vIndex));throw new Error("Face index is out of range")}getCellOnIndex(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getTopPointsOfCells(e){return e.cells.map((e=>e.topPoint))}getCenterPointsOfCells(e){return e.cells.map((e=>e.centerPoint))}getCornerPointsOfCells(e){return e.cells.map((e=>[e.cornerPoint1,e.cornerPoint2,e.cornerPoint3,e.cornerPoint4].filter((e=>void 0!==e))))}getCornerPointOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerPoint1:1===e.index?t.cornerPoint2:2===e.index?t.cornerPoint3:3===e.index?t.cornerPoint4:void 0));throw new Error("Corner index is out of range")}getCornerNormalOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerNormal1:1===e.index?t.cornerNormal2:2===e.index?t.cornerNormal3:3===e.index?t.cornerNormal4:void 0));throw new Error("Corner index is out of range")}getCornerNormalsOfCells(e){return e.cells.map((e=>[e.cornerNormal1,e.cornerNormal2,e.cornerNormal3,e.cornerNormal4].filter((e=>void 0!==e))))}getCompoundShapesOfCells(e){return e.cells.map((e=>e.shapes.compound))}getFaceShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.face1:1===e.index?t.shapes.face2:2===e.index?t.shapes.face3:3===e.index?t.shapes.face4:void 0));throw new Error("Face index is out of range")}getWireShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.wire1:1===e.index?t.shapes.wire2:2===e.index?t.shapes.wire3:3===e.index?t.shapes.wire4:void 0));throw new Error("Wire index is out of range")}getStartPolylineWireU(e){if(e.faceIndex>=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0&&"string"!=typeof t[e])for(var i=function(i){var s=t[e][i];"object"==typeof s&&null!==s&&s.then&&(s.then((function(s){return t[e][i]=s,s})),n.push(t[e][i]))},s=0;s0&&e.startedAsyncTask(i,s,"#eeeeff"),n.length>0?[2,Promise.all(n).then((function(t){return e.finishedAsyncTask(i,s),t}))]:[2,null]}))}))},e.finishedAsyncTask=function(e,t){},e.startedAsyncTask=function(e,t,i){},e.runtimeValidation=function(e,t){},e.validate=function(e,t,i){},e.handleBlockException=function(e,t){},e.errorHappened=function(e,t,i){},e.updateListInputs=function(e){Object.keys(e).forEach((function(t){if(Array.isArray(e[t])){var i=[];e[t].forEach((function(e){if(e&&e.result){var t=e.result;e.transformers&&e.transformers.length&&e.transformers.forEach((function(e){e.type===KH.flat&&(t=t.flat())})),t instanceof Array?i.push.apply(i,t):i.push(t)}})),e[t]=i}}))},e.executeBasedOnTypeAsync=function(e,t,i){return qH(this,void 0,void 0,(function(){var s,r,n,o,a,l,h,c,u;return ZH(this,(function(d){switch(d.label){case 0:if(t)return[3,5];l=this.performActionOnAllVariationsSimplified(e,i),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,Promise.all(l)];case 2:return s=d.sent(),[3,4];case 3:throw r=d.sent(),new Error(r);case 4:return[3,9];case 5:if(!t)return[3,9];for(n=Object.keys(e),o=n.map((function(t){return e[t]})),a=this.normalizeListsToEqualLength(o),l=[],h=function(e){var t={};n.forEach((function(i,s){t[i]=o[s][e]})),l.push(i(t))},c=0;ct&&(t=e.length)})),t},e.drawNodeMeshes=function(e,t){return qH(this,void 0,void 0,(function(){var i,s=this;return ZH(this,(function(r){switch(r.label){case 0:return i=e.map((function(e){return qH(s,void 0,void 0,(function(){var i,s,r;return ZH(this,(function(n){switch(n.label){case 0:return i=e.result,s=[],i instanceof Array&&i.length>0&&i[0]&&i[0].hash?i.forEach((function(e){var i=t.draw.drawAnyAsync({entity:e,options:void 0});s.push(i)})):(r=t.draw.drawAnyAsync({entity:i,options:void 0}),s.push(r)),[4,Promise.all(s)];case 1:return[2,n.sent()]}}))}))})),[4,Promise.all(i)];case 1:return r.sent(),[2]}}))}))},e}(),iX=function(){function e(e){this.context=e}return e.prototype.handleTags=function(e,t,i,s){var r=this;!t&&this.context.tagBag.length>0&&this.context.tagBag.find((function(e){return e.needsUpdate}))&&(t=!0),t&&this.context.tagBag.length>0&&this.context.tagBag.forEach((function(t){var n=document.querySelector("#"+t.id),o=new de(t.position[0],t.position[1],t.position[2]);n.textContent=t.text;var a=i.getRenderWidth()/2,l=i.getRenderHeight()/2,h=de.Project(o,fe.IdentityReadOnly,s.getTransformMatrix(),e.viewport.toGlobal(a,l)),c=de.Distance(e.position,o),u=t.adaptDepth?Math.ceil(r.context.remap(c,0,100,t.size,3)):t.size;h.x>0&&h.x0&&h.y0&&h.z<1&&u>3?n.style="".concat("position: absolute; transform: translate(-50%, -50%); font-weight: 400;"," font-size: ").concat(u,"px; color: ").concat(t.colour,"; left: ").concat(h.x,"px; top: ").concat(h.y,"px; display: inline;"):n.style="display: none;"}))},e.prototype.removeTagsIfNeeded=function(){this.tagsExist()&&this.context.tagBag.forEach((function(e){var t=document.getElementById(e.id);t.parentNode.removeChild(t)})),this.context.tagBag=[]},e.prototype.tagsExist=function(){return this.context.tagBag.length>0},e}(),sX=function(){return sX=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0?JSON.stringify(s):"{}",';\n let bitbybitRunnerResult = {};\n const runContext = "runner";\n const mockBitbybitRunnerInputs = (inputs) => {\n }\n const getBitbybitRunnerInputs = () => {\n return bitbybitRunnerInputs;\n }\n const setBitbybitRunnerResult = (result) => {\n bitbybitRunnerResult = result;\n }\n const setBitbybitRunnerResultValue = (prop, value) => {\n bitbybitRunnerResult[prop] = value;\n }\n\n const bitbybit = this.bitbybit;\n const Bit = this.Bit;\n Bit.mockBitbybitRunnerInputs = mockBitbybitRunnerInputs;\n Bit.getBitbybitRunnerInputs = getBitbybitRunnerInputs;\n Bit.setBitbybitRunnerResult = setBitbybitRunnerResult;\n Bit.setBitbybitRunnerResultValue = setBitbybitRunnerResultValue;\n\n const BitByBit = this.BitByBit;\n const errorHandle = this.errorHandle;\n const BABYLON = this.BABYLON;\n BABYLON.GUI = this.GUI;\n const resolve = this.resolve;\n\n await ').concat(r.script,"\n if(bitbybitRunnerResult !== undefined){\n resolve(bitbybitRunnerResult);\n } else {\n resolve(undefined);\n }\n }\n \n bitbybitRunnerStart();\n "),a={HS:tX,BitByBitContextHelperService:hX.context},l={bitbybit:hX,BABYLON:e,GUI:t,Bit:uX,BitByBit:a,errorHandle:n},[2,new Promise((function(e){return l.resolve=e,new Function(o).apply(l)}))]}))}))}function mX(){if(hX.context.scene.dispose(),oX.enablePhysics){var e=new zE(!0,aX);hX.context.havokPlugin=e}var t=document.getElementById(oX.canvasId);xX(hX.context.engine,t),cX.removeTagsIfNeeded(),hX.context.intervalBag.forEach((function(e){return clearInterval(e)})),hX.context.timeoutBag.forEach((function(e){return clearTimeout(e)})),hX.context.intervalBag.length=0,hX.context.timeoutBag.length=0,hX.context.renderLoopBag.length=0,hX.context.keyPressBag.length=0,hX.context.keyDownBag.length=0,hX.context.keyUpBag.length=0}function gX(){return rX(this,void 0,void 0,(function(){return nX(this,(function(e){return[2,hX.occtWorkerManager.cleanAllCache()]}))}))}function vX(){return rX(this,void 0,void 0,(function(){return nX(this,(function(e){return[2,hX.jscadWorkerManager.cleanAllCache()]}))}))}function xX(e,t){var i=new dr(e);i.clearColor=new Ee(26/255,28/255,31/255,1),new xn("root",i);var s=new Th("Camera",0,10,10,new de(0,0,0),i);s.setPosition(new de(0,10,-20)),s.attachControl(t,!0),s.lowerRadiusLimit=0,s.minZ=0;var r=new cu("HemiLight",new de(0,1,0),i);return r.intensityMode=yo.INTENSITYMODE_ILLUMINANCE,r.intensity=1,i.ambientColor=new Ce(.1,.1,.1),i.metadata={shadowGenerators:[]},hX.context.scene=i,hX.context.engine=e,dX=!1,s.onProjectionMatrixChangedObservable.add((function(){dX=!0})),s.onViewMatrixChangedObservable.add((function(){dX=!0})),i.registerBeforeRender(TX),i.registerAfterRender((function(){cX.handleTags(s,dX,hX.context.engine,i),dX=!1})),{scene:i,camera:s}}var bX=0;function TX(){var e=Date.now(),t=e-bX;bX=e,hX.context.renderLoopBag.forEach((function(e){return e(t)}))}})(),s})())); \ No newline at end of file diff --git a/workers/bitbybit-occt-webworker.js b/workers/bitbybit-occt-webworker.js index fafc791..bdf9493 100644 --- a/workers/bitbybit-occt-webworker.js +++ b/workers/bitbybit-occt-webworker.js @@ -1,2 +1,2 @@ /*! For license information please see bitbybit-occt-webworker.js.LICENSE.txt */ -(()=>{var e={725:()=>{},439:()=>{},699:()=>{},256:()=>{}},t={};function r(i){var n=t[i];if(void 0!==n)return n.exports;var s=t[i]={exports:{}};return e[i](s,s.exports,r),s.exports}r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";var e={};r.r(e),r.d(e,{Base:()=>W,OCCT:()=>U});var t={};r.r(t),r.d(t,{LodDto:()=>Ge,lodEnum:()=>Be});var i={};r.r(i),r.d(i,{Part:()=>He});var n={};r.r(n),r.d(n,{SerenitySwirlData:()=>ze,SerenitySwirlDto:()=>Ve});var s={};r.r(s),r.d(s,{ArabicArchwayData:()=>$e,ArabicArchwayDrawingPart:()=>Ye,ArabicArchwayDrawingPartShapes:()=>Xe,ArabicArchwayDto:()=>qe,ArabicArchwayDtoBase:()=>je});var o={};r.r(o),r.d(o,{ArabicArchway:()=>s,SerenitySwirl:()=>n});var a={};r.r(a),r.d(a,{EternalLoveData:()=>Qe,EternalLoveDto:()=>Je,EternalLoveDtoBase:()=>Ze});var c={};r.r(c),r.d(c,{EternalLove:()=>a});var h={};r.r(h),r.d(h,{CalmCupData:()=>tt,CalmCupDto:()=>et,CalmCupDtoBase:()=>Ke});var l={};r.r(l),r.d(l,{DragonCupData:()=>nt,DragonCupDto:()=>it,DragonCupDtoBase:()=>rt,DragonCupModelDto:()=>st});var u={};r.r(u),r.d(u,{CalmCup:()=>h,DragonCup:()=>l});var d={};r.r(d),r.d(d,{PhoneNestData:()=>ct,PhoneNestDrawDto:()=>pt,PhoneNestDrawingPart:()=>ht,PhoneNestDrawingPartShapes:()=>lt,PhoneNestDto:()=>at,PhoneNestDtoBase:()=>ot,PhoneNestMainPart:()=>ut,PhoneNestModelDto:()=>dt});var p={};r.r(p),r.d(p,{PhoneNest:()=>d});var f={};r.r(f),r.d(f,{SpicyBoxData:()=>vt,SpicyBoxDto:()=>gt,SpicyBoxDtoBase:()=>ft,SpicyBoxModelDto:()=>mt});var g={};r.r(g),r.d(g,{SpicyBox:()=>f});var v={};r.r(v),r.d(v,{Boxes:()=>g,Cups:()=>u,Desktop:()=>p,Medals:()=>c,Vases:()=>o});var m={};r.r(m),r.d(m,{ZenHideoutData:()=>bt,ZenHideoutDrawingPart:()=>wt,ZenHideoutDrawingPartShapes:()=>Et,ZenHideoutDto:()=>St,ZenHideoutDtoBase:()=>yt});var y={};r.r(y),r.d(y,{ZenHideout:()=>m});var S={};r.r(S),r.d(S,{BeamPart:()=>Ft,CeilingPart:()=>Ht,ColumnPart:()=>Rt,CornerEntranceDto:()=>zt,CornerEntrancePart:()=>Wt,CornerPart:()=>Dt,CornerStairDto:()=>It,CornerStairPart:()=>Ut,FloorPart:()=>Vt,Houses:()=>y,RoofBeamsPart:()=>Bt,RoofCoverOneSidedDto:()=>Nt,RoofCoverPart:()=>Gt,RoofPanelPart:()=>Mt,RoofPart:()=>Lt,SandwitchPanelDto:()=>Pt,SandwitchPanelFlexDto:()=>At,SandwitchPart:()=>_t,SandwitchPartFlex:()=>Ot,WindowCornerDto:()=>Tt,WindowCornerPart:()=>Ct,WindowRectangularDto:()=>xt,WindowRectangularPart:()=>kt});var b={};r.r(b),r.d(b,{WingtipVillaData:()=>qt,WingtipVillaDto:()=>jt});var w={};r.r(w),r.d(w,{ChirpyChaletData:()=>Yt,ChirpyChaletDto:()=>$t});var E={};r.r(E),r.d(E,{ChirpyChalet:()=>w,WingtipVilla:()=>b});var T={};r.r(T),r.d(T,{BirdHouses:()=>E});var x={};r.r(x),r.d(x,{SnakeChairData:()=>Jt,SnakeChairDrawDto:()=>rr,SnakeChairDrawingPart:()=>Qt,SnakeChairDrawingPartShapes:()=>Kt,SnakeChairDto:()=>Zt,SnakeChairDtoBase:()=>Xt,SnakeChairMainPart:()=>er,SnakeChairModelDto:()=>tr});var k={};r.r(k),r.d(k,{SnakeChair:()=>x});var C={};r.r(C),r.d(C,{ElegantTableData:()=>sr,ElegantTableDrawDto:()=>dr,ElegantTableDrawingPart:()=>or,ElegantTableDrawingPartShapes:()=>ar,ElegantTableDto:()=>nr,ElegantTableDtoBase:()=>ir,ElegantTableLegByIndexDto:()=>lr,ElegantTableLegPart:()=>cr,ElegantTableModelDto:()=>ur,ElegantTableTopPart:()=>hr});var P={};r.r(P),r.d(P,{GoodCoffeeTableData:()=>gr,GoodCoffeeTableDrawDto:()=>Tr,GoodCoffeeTableDrawingPart:()=>vr,GoodCoffeeTableDrawingPartShapes:()=>mr,GoodCoffeeTableDto:()=>fr,GoodCoffeeTableDtoBase:()=>pr,GoodCoffeeTableLegByIndexDto:()=>wr,GoodCoffeeTableLegPart:()=>yr,GoodCoffeeTableModelDto:()=>Er,GoodCoffeeTableShelfPart:()=>Sr,GoodCoffeeTableTopPart:()=>br});var A={};r.r(A),r.d(A,{SnakeTableData:()=>Cr,SnakeTableDrawDto:()=>Dr,SnakeTableDrawingPart:()=>Pr,SnakeTableDrawingPartShapes:()=>Ar,SnakeTableDto:()=>kr,SnakeTableDtoBase:()=>xr,SnakeTableMainPart:()=>_r,SnakeTableModelDto:()=>Or});var _={};r.r(_),r.d(_,{ElegantTable:()=>C,GoodCoffeeTable:()=>P,SnakeTable:()=>A});var O={};r.r(O),r.d(O,{Chairs:()=>k,Tables:()=>_});var D={};r.r(D),r.d(D,{Architecture:()=>S,Enums:()=>t,Furniture:()=>O,KidsCorner:()=>T,Shared:()=>i,ThreeDPrinting:()=>v});var R={};r.r(R),r.d(R,{FontDefinition:()=>Ir,Text3DData:()=>Br,Text3DDto:()=>Fr,Text3DFaceDefinitionDto:()=>Wr,Text3DFaceDto:()=>Lr,Text3DLetterByIndexDto:()=>Mr,Text3DModelDto:()=>Ur,Texts3DFaceDto:()=>Nr,faceTextVarEnum:()=>Ue,faceTypeEnum:()=>We,fontVariantsEnum:()=>Ie,fontsEnum:()=>Me,fontsModel:()=>Rr,recAlignmentEnum:()=>Ne});var F={};r.r(F),r.d(F,{PyramidSimpeByIndexDto:()=>zr,PyramidSimpleAffectorsDto:()=>Hr,PyramidSimpleCellPart:()=>Kr,PyramidSimpleData:()=>Vr,PyramidSimpleDto:()=>Gr,PyramidSimpleFacePart:()=>ei,PyramidSimpleModelCellDto:()=>Yr,PyramidSimpleModelCellsDto:()=>qr,PyramidSimpleModelCellsIndexDto:()=>$r,PyramidSimpleModelDto:()=>jr,PyramidSimpleModelFaceCellIndexDto:()=>Zr,PyramidSimpleModelFaceCellsUIndexDto:()=>Jr,PyramidSimpleModelFaceCellsVIndexDto:()=>Qr,PyramidSimpleModelFaceIndexDto:()=>Xr});var L={};r.r(L),r.d(L,{PyramidSimple:()=>F});var B={};r.r(B),r.d(B,{FacePatterns:()=>L});var M={};r.r(M),r.d(M,{outputShapeEnum:()=>ti});var I,U,W,N,G={};r.r(G),r.d(G,{Enums:()=>M,Patterns:()=>B,Text3D:()=>R}),(N=I||(I={})).loading="loading",N.loaded="loaded",N.initialised="initialised",N.computing="computing";class H{starLines(e,t,r,i,n){let s=[];const o=2*Math.PI/r;for(let i=0;i=i&&(e=i-1e-6,console.warn("width first is bigger than length second, to make it work, width second is set to length first - 1e-6")),r>=t&&(r=t-1e-6,console.warn("width second is bigger than length first, to make it work, width second is set to length first - 1e-6")),[[0,0,0],[t,0,0],[t,0,e],[r,0,e],[r,0,i],[0,0,i]]}polygonLMiddle(e,t,r,i){return e>=i&&(e=i-1e-6,console.warn("width first is bigger than length second, to make it work, width second is set to length first - 1e-6")),r>=t&&(r=t-1e-6,console.warn("width second is bigger than length first, to make it work, width second is set to length first - 1e-6")),[[r/2,0,e/2],[r/2,0,i],[-r/2,0,i],[-r/2,0,-e/2],[t,0,-e/2],[t,0,e/2]]}}class V{constructor(){this.tolerance=1e-5}degToRad(e){return e*(Math.PI/180)}remap(e,t,r,i,n){return(e-t)/(r-t)*(n-i)+i}removeAllDuplicateVectors(e,t=1e-7){const r=[];return e.forEach((e=>{r.some((r=>this.vectorsTheSame(e,r,t)))||r.push(e)})),r}removeConsecutiveDuplicates(e,t=!0){const r=[];if(e.length>1){for(let t=1;te.map(((e,r)=>e+t[r]))),[0,0,0]).map((t=>t/e.length))}magnitude(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}normalize(e){const t=this.magnitude(e);return e.map((e=>e/t))}translatePoint(e,t,r){return[e[0]+t[0]*r,e[1]+t[1]*r,e[2]+t[2]*r]}distanceBetweenPoints(e,t){const r=t[0]-e[0],i=t[1]-e[1],n=t[2]-e[2];return Math.sqrt(r*r+i*i+n*n)}}!function(e){let t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(r=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(i=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(n=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(s=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(c=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(l=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(p=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(f=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(g=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(v=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,r,i,n){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.positionResult=i),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,r,i,n,s){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==r&&(this.point1=r),void 0!==i&&(this.tolerance=i),void 0!==n&&(this.positionResult=n),void 0!==s&&(this.circleRemainder=s)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,r,i,n){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.positionResult=i),void 0!==n&&(this.circleRemainders=n)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,r,i){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.radius=i)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,r,i){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.radius=i)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,r,i,n,s){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==r&&(this.planeOrigin=r),void 0!==i&&(this.planeDirection=i),void 0!==n&&(this.radius=n),void 0!==s&&(this.solution=s)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,r){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==r&&(this.inside=r)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==r&&(this.edgeOpacity=r),void 0!==i&&(this.edgeColour=i),void 0!==n&&(this.faceMaterial=n),void 0!==s&&(this.faceColour=s),void 0!==l&&(this.vertexColour=l),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==c&&(this.drawFaces=c),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==g&&(this.edgeIndexColour=g),void 0!==v&&(this.drawFaceIndexes=v),void 0!==m&&(this.faceIndexHeight=m),void 0!==y&&(this.faceIndexColour=y)}},e.DrawShapesDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==r&&(this.edgeOpacity=r),void 0!==i&&(this.edgeColour=i),void 0!==n&&(this.faceMaterial=n),void 0!==s&&(this.faceColour=s),void 0!==l&&(this.vertexColour=l),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==c&&(this.drawFaces=c),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==g&&(this.edgeIndexColour=g),void 0!==v&&(this.drawFaceIndexes=v),void 0!==m&&(this.faceIndexHeight=m),void 0!==y&&(this.faceIndexColour=y)}},e.FaceSubdivisionDto=class{constructor(e,t,r,i,n,s,o,a,c){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==r&&(this.nrDivisionsV=r),void 0!==i&&(this.shiftHalfStepU=i),void 0!==n&&(this.removeStartEdgeU=n),void 0!==s&&(this.removeEndEdgeU=s),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==c&&(this.removeEndEdgeV=c)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==r&&(this.nrDivisionsV=r),void 0!==i&&(this.shiftHalfStepNthU=i),void 0!==n&&(this.shiftHalfStepUOffsetN=n),void 0!==s&&(this.removeStartEdgeNthU=s),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==c&&(this.removeEndEdgeUOffsetN=c),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==l&&(this.shiftHalfStepVOffsetN=l),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==p&&(this.removeEndEdgeNthV=p),void 0!==f&&(this.removeEndEdgeVOffsetN=f)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,r,i,n,s,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==r&&(this.param=r),void 0!==i&&(this.nrPoints=i),void 0!==n&&(this.shiftHalfStep=n),void 0!==s&&(this.removeStartPoint=s),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,r){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==r&&(this.paramV=r)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,r){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.RectangleDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.center=r),void 0!==i&&(this.direction=i)}},e.LPolygonDto=class{constructor(e,t,r,i,s,o,a,c){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=n.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==r&&(this.widthSecond=r),void 0!==i&&(this.lengthSecond=i),void 0!==s&&(this.align=s),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==c&&(this.direction=c)}},e.BoxDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.height=r),void 0!==i&&(this.center=i)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.height=r),void 0!==i&&(this.corner=i)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,r,i,n,s){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==r&&(this.height=r),void 0!==i&&(this.angle=i),void 0!==n&&(this.center=n),void 0!==s&&(this.direction=s)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,r){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==r&&(this.end=r)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,r,i){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==r&&(this.end=r),void 0!==i&&(this.sense=i)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,r,i){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==r&&(this.alphaAngle2=r),void 0!==i&&(this.sense=i)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,r,i){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==i&&(this.sense=i)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,r){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==r&&(this.end=r)}},e.CylinderDto=class{constructor(e,t,r,i){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==r&&(this.center=r),void 0!==i&&(this.direction=i)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,r,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.indexes=i)}},e.FilletEdgesListDto=class{constructor(e,t,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusList=r)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,r){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radius=r)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.paramsU=i)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusLists=r),void 0!==i&&(this.paramsULists=i)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.paramsU=i)}},e.Fillet3DWireDto=class{constructor(e,t,r,i,n){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.direction=r),void 0!==i&&(this.radiusList=i),void 0!==n&&(this.indexes=n)}},e.ChamferDto=class{constructor(e,t,r,i){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==r&&(this.distanceList=r),void 0!==i&&(this.indexes=i)}},e.ChamferEdgesListDto=class{constructor(e,t,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.distanceList=r)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,r,i,n){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.face=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.angle=n)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,r,i,n){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.face=r),void 0!==i&&(this.distance1=i),void 0!==n&&(this.distance2=n)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,r,i,n){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distances1=i),void 0!==n&&(this.distances2=n)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,r,i,n){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distance1=i),void 0!==n&&(this.distance2=n)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,r,i,n){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distances=i),void 0!==n&&(this.angles=n)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,r,i,n){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.angle=n)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,r,i,n){this.keepLines=f.outside,this.circleRemainders=p.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.keepLines=r),void 0!==i&&(this.circleRemainders=i),void 0!==n&&(this.tolerance=n)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,r,i){this.combination=g.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==r&&(this.unify=r),void 0!==i&&(this.tolerance=i)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,r,i){this.combination=g.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==r&&(this.unify=r),void 0!==i&&(this.tolerance=i)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,r,i){this.nrZigZags=20,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==r&&(this.nrZigZags=r),void 0!==i&&(this.inverse=i)}},e.InterpolationDto=class{constructor(e,t,r){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==r&&(this.tolerance=r)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,r,i){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.removeStartPoint=r),void 0!==i&&(this.removeEndPoint=i)}},e.ProjectWireDto=class{constructor(e,t,r){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==r&&(this.direction=r)}},e.WiresToPointsDto=class{constructor(e,t,r,i,n,s){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==r&&(this.curvatureDeflection=r),void 0!==i&&(this.minimumOfPoints=i),void 0!==n&&(this.uTolerance=n),void 0!==s&&(this.minimumLength=s)}},e.EdgesToPointsDto=class{constructor(e,t,r,i,n,s){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==r&&(this.curvatureDeflection=r),void 0!==i&&(this.minimumOfPoints=i),void 0!==n&&(this.uTolerance=n),void 0!==s&&(this.minimumLength=s)}},e.ProjectWiresDto=class{constructor(e,t,r){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==r&&(this.direction=r)}},e.DivideShapesDto=class{constructor(e,t,r,i){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.removeStartPoint=r),void 0!==i&&(this.removeEndPoint=i)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,r,i){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.tEdgeParam=r),void 0!==i&&(this.distance2DParam=i)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,r){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,r,n,s,o,a,c,h,l,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=i.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==r&&(this.closed=r),void 0!==n&&(this.periodic=n),void 0!==s&&(this.straight=s),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==c&&(this.maxUDegree=c),void 0!==h&&(this.tolerance=h),void 0!==l&&(this.parType=l),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,r,i){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==r&&(this.distance=r),void 0!==i&&(this.tolerance=i)}},e.OffsetAdvancedDto=class{constructor(e,r,i,n,s,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==r&&(this.face=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.tolerance=n),void 0!==s&&(this.joinType=s),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,r,i){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==r&&(this.direction=r),void 0!==i&&(this.copy=i)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,r){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.nrCorners=r)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,r){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==r&&(this.keepEdges=r)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,r){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==r&&(this.precsmall=r)}},e.BasicShapeRepairDto=class{constructor(e,t,r,i){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.maxTolerance=r),void 0!==i&&(this.minTolerance=i)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,r){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==r&&(this.angle=r)}},e.ThickSolidByJoinDto=class{constructor(e,r,i,n,s,o,a,c){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==r&&(this.shapes=r),void 0!==i&&(this.offset=i),void 0!==n&&(this.tolerance=n),void 0!==s&&(this.intersection=s),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==c&&(this.removeIntEdges=c)}},e.TransformDto=class{constructor(e,t,r,i,n){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==r&&(this.rotationAxis=r),void 0!==i&&(this.rotationAngle=i),void 0!==n&&(this.scaleFactor=n)}},e.TransformShapesDto=class{constructor(e,t,r,i,n){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==r&&(this.rotationAxes=r),void 0!==i&&(this.rotationAngles=i),void 0!==n&&(this.scaleFactors=n)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,r,i,n){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==r&&(this.fromDirection=r),void 0!==i&&(this.toOrigin=i),void 0!==n&&(this.toDirection=n)}},e.AlignShapesDto=class{constructor(e,t,r,i,n){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==r&&(this.fromDirections=r),void 0!==i&&(this.toOrigins=i),void 0!==n&&(this.toDirections=n)}},e.MirrorDto=class{constructor(e,t,r){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==r&&(this.direction=r)}},e.MirrorShapesDto=class{constructor(e,t,r){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==r&&(this.directions=r)}},e.MirrorAlongNormalDto=class{constructor(e,t,r){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==r&&(this.normal=r)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,r){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==r&&(this.normals=r)}},e.AlignAndTranslateDto=class{constructor(e,t,r){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.center=r)}},e.UnifySameDomainDto=class{constructor(e,t,r,i){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==r&&(this.unifyFaces=r),void 0!==i&&(this.concatBSplines=i)}},e.FilterFacePointsDto=class{constructor(e,t,r,i,n,s,o,a,c){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.useBndBox=i),void 0!==n&&(this.gapTolerance=n),void 0!==s&&(this.keepIn=s),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==c&&(this.keepUnknown=c)}},e.FilterSolidPointsDto=class{constructor(e,t,r,i,n,s,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.keepIn=i),void 0!==n&&(this.keepOn=n),void 0!==s&&(this.keepOut=s),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,r){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==r&&(this.centers=r)}},e.RotateDto=class{constructor(e,t,r){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==r&&(this.angle=r)}},e.RotateAroundCenterDto=class{constructor(e,t,r,i){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==r&&(this.center=r),void 0!==i&&(this.axis=i)}},e.RotateShapesDto=class{constructor(e,t,r){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==r&&(this.angles=r)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,r,i){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==r&&(this.centers=r),void 0!==i&&(this.axes=i)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,r){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==r&&(this.center=r)}},e.Scale3DShapesDto=class{constructor(e,t,r){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==r&&(this.centers=r)}},e.ShapeToMeshDto=class{constructor(e,t,r){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.adjustYtoZ=r)}},e.ShapesToMeshesDto=class{constructor(e,t,r){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.adjustYtoZ=r)}},e.SaveStepDto=class{constructor(e,t,r,i){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.adjustYtoZ=r),void 0!==i&&(this.tryDownload=i)}},e.SaveStlDto=class{constructor(e,t,r,i,n,s){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.precision=r),void 0!==i&&(this.adjustYtoZ=i),void 0!==n&&(this.tryDownload=n),void 0!==s&&(this.binary=s)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,r){this.fileType=s.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==r&&(this.adjustZtoY=r)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,r){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.adjustZtoY=r)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,r){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==r&&(this.direction=r)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,r){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==r&&(this.dir=r)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,r,i){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==r&&(this.nrOfPointsV=r),void 0!==i&&(this.flat=i)}},e.Geom2dEllipseDto=class{constructor(e,t,r,i,n){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radiusMinor=r),void 0!==i&&(this.radiusMajor=i),void 0!==n&&(this.sense=n)}},e.Geom2dCircleDto=class{constructor(e,t,r,i){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radius=r),void 0!==i&&(this.sense=i)}},e.ChristmasTreeDto=class{constructor(e,t,r,i,n,s,o,a,c,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==r&&(this.outerDist=r),void 0!==i&&(this.nrSkirts=i),void 0!==n&&(this.trunkHeight=n),void 0!==s&&(this.trunkWidth=s),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==c&&(this.origin=c),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,r,i,n,s,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==r&&(this.numRays=r),void 0!==i&&(this.center=i),void 0!==n&&(this.direction=n),void 0!==s&&(this.offsetOuterEdges=s),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,r,i,n,s){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.aroundCenter=r),void 0!==i&&(this.width=i),void 0!==n&&(this.height=n),void 0!==s&&(this.angle=s)}},e.Heart2DDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.rotation=r),void 0!==i&&(this.sizeApprox=i)}},e.NGonWireDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.nrCorners=r),void 0!==i&&(this.radius=i)}},e.EllipseDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radiusMinor=r),void 0!==i&&(this.radiusMajor=i)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,r){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,r,i,n){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==r&&(this.u2=r),void 0!==i&&(this.sense=i),void 0!==n&&(this.adjustPeriodic=n)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,r){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==r&&(this.direction=r)}},e.SliceInStepPatternDto=class{constructor(e,t,r){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==r&&(this.direction=r)}}}(U||(U={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(W||(W={}));class z{constructor(e,t){this.occ=e,this.och=t}geom2dEllipse(e){const t=this.och.entitiesService.gpAx2d(e.center,e.direction),r=new this.occ.Geom2d_Ellipse_2(t,e.radiusMajor,e.radiusMinor,e.sense);return t.delete(),r}geom2dCircle(e){const t=this.och.entitiesService.gpAx2d(e.center,e.direction),r=new this.occ.Geom2d_Circle_2(t,e.radius,e.sense);return t.delete(),r}geom2dTrimmedCurve(e){const t=new this.occ.Handle_Geom2d_Curve_2(e.shape);return new this.occ.Geom2d_TrimmedCurve(t,e.u1,e.u2,e.sense,e.adjustPeriodic)}geom2dSegment(e){const t=this.och.entitiesService.gpPnt2d(e.start),r=this.och.entitiesService.gpPnt2d(e.end),i=new this.occ.GCE2d_MakeSegment_1(t,r),n=i.Value().get();return t.delete(),r.delete(),i.delete(),n}get2dPointFrom2dCurveOnParam(e){const t=e.shape.Value(e.param),r=[t.X(),t.Y()];return t.delete(),r}geomCircleCurve(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.curve)}geomEllipseCurve(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.curve)}}class j{constructor(e,t){this.occ=e,this.och=t}cylindricalSurface(e){const t=this.och.entitiesService.gpAx3(e.center,e.direction),r=new this.occ.Geom_CylindricalSurface_1(t,e.radius);return t.delete(),r}surfaceFromFace(e){return this.och.surfaceFromFace(e)}}class q{constructor(e,t){this.curves=new z(e,t),this.surfaces=new j(e,t)}}class ${constructor(e,t){this.occ=e,this.och=t}makeEdgeFromGeom2dCurveAndSurface(e){return this.och.edgesService.makeEdgeFromGeom2dCurveAndSurface(e)}line(e){return this.och.edgesService.lineEdge(e)}arcThroughThreePoints(e){return this.och.edgesService.arcThroughThreePoints(e)}arcThroughTwoPointsAndTangent(e){return this.och.edgesService.arcThroughTwoPointsAndTangent(e)}arcFromCircleAndTwoPoints(e){return this.och.edgesService.arcFromCircleAndTwoPoints(e)}arcFromCircleAndTwoAngles(e){return this.och.edgesService.arcFromCircleAndTwoAngles(e)}arcFromCirclePointAndAngle(e){return this.och.edgesService.arcFromCirclePointAndAngle(e)}createCircleEdge(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.edge)}createEllipseEdge(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.edge)}removeInternalEdges(e){const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e.shape,!0,!0,!1);t.Build();const r=t.Shape();return t.delete(),r}getEdge(e){return this.och.shapeGettersService.getEdge(e)}edgesToPoints(e){return this.och.edgesService.edgesToPoints(e)}reversedEdge(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}pointOnEdgeAtParam(e){return this.och.edgesService.pointOnEdgeAtParam(e)}tangentOnEdgeAtParam(e){return this.och.edgesService.tangentOnEdgeAtParam(e)}startPointOnEdge(e){return this.och.edgesService.startPointOnEdge(e)}endPointOnEdge(e){return this.och.edgesService.endPointOnEdge(e)}pointOnEdgeAtLength(e){return this.och.edgesService.pointOnEdgeAtLength(e)}tangentOnEdgeAtLength(e){return this.och.edgesService.tangentOnEdgeAtLength(e)}divideEdgeByParamsToPoints(e){return this.och.edgesService.divideEdgeByParamsToPoints(e)}divideEdgeByEqualDistanceToPoints(e){return this.och.edgesService.divideEdgeByEqualDistanceToPoints(e)}getEdges(e){return this.och.shapeGettersService.getEdges(e)}getEdgesAlongWire(e){return this.och.edgesService.getEdgesAlongWire(e)}getCircularEdgesAlongWire(e){return this.och.edgesService.getCircularEdgesAlongWire(e)}getLinearEdgesAlongWire(e){return this.och.edgesService.getLinearEdgesAlongWire(e)}getEdgeLength(e){return this.och.edgesService.getEdgeLength(e)}getEdgesLengths(e){return this.och.edgesService.getEdgesLengths(e)}getEdgeCenterOfMass(e){return this.och.geomService.getLinearCenterOfMass(e)}getEdgesCentersOfMass(e){return this.och.edgesService.getEdgesCentersOfMass(e)}getCornerPointsOfEdgesForShape(e){return this.och.edgesService.getCornerPointsOfEdgesForShape(e)}getCircularEdgeCenterPoint(e){return this.och.edgesService.getCircularEdgeCenterPoint(e)}getCircularEdgeRadius(e){return this.och.edgesService.getCircularEdgeRadius(e)}getCircularEdgePlaneDirection(e){return this.och.edgesService.getCircularEdgePlaneDirection(e)}constraintTanLinesFromTwoPtsToCircle(e){return this.och.edgesService.constraintTanLinesFromTwoPtsToCircle(e)}constraintTanLinesFromPtToCircle(e){return this.och.edgesService.constraintTanLinesFromPtToCircle(e)}constraintTanLinesOnTwoCircles(e){return this.och.edgesService.constraintTanLinesOnTwoCircles(e)}constraintTanCirclesOnTwoCircles(e){return this.och.edgesService.constraintTanCirclesOnTwoCircles(e)}constraintTanCirclesOnCircleAndPnt(e){return this.och.edgesService.constraintTanCirclesOnCircleAndPnt(e)}}class Y{constructor(e,t){this.occ=e,this.och=t}createFaceFromWire(e){return this.och.facesService.createFaceFromWire(e)}createFaceFromWires(e){return this.och.facesService.createFaceFromWires(e)}createFacesFromWires(e){return this.och.facesService.createFacesFromWires(e)}faceFromSurface(e){return this.och.facesService.faceFromSurface(e)}faceFromSurfaceAndWire(e){return this.och.facesService.faceFromSurfaceAndWire(e)}getUMinBound(e){return this.och.facesService.getUMinBound(e)}getUMaxBound(e){return this.och.facesService.getUMaxBound(e)}getVMinBound(e){return this.och.facesService.getVMinBound(e)}getVMaxBound(e){return this.och.facesService.getVMaxBound(e)}subdivideToPointsControlled(e){return this.och.facesService.subdivideToPointsControlled(e)}subdivideToPoints(e){return this.och.facesService.subdivideToPoints(e)}subdivideToNormals(e){return this.och.facesService.subdivideToNormals(e)}subdivideToPointsOnParam(e){return this.och.facesService.subdivideToPointsOnParam(e)}subdivideToUVOnParam(e){return this.och.facesService.subdivideToUVOnParam(e)}subdivideToUV(e){return this.och.facesService.subdivideToUV(e)}uvOnFace(e){return this.och.facesService.uvOnFace(e)}pointsOnUVs(e){return this.och.facesService.pointsOnUVs(e)}normalsOnUVs(e){return this.och.facesService.normalsOnUVs(e)}pointOnUV(e){return this.och.facesService.pointOnUV(e)}normalOnUV(e){return this.och.facesService.faceNormalOnUV(e)}createPolygonFace(e){return this.och.facesService.createPolygonFace(e)}createCircleFace(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.face)}createEllipseFace(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.face)}createSquareFace(e){return this.och.facesService.createSquareFace(e)}createRectangleFace(e){return this.och.facesService.createRectangleFace(e)}createFaceFromMultipleCircleTanWireCollections(e){return this.och.facesService.createFaceFromMultipleCircleTanWireCollections(e)}createFaceFromMultipleCircleTanWires(e){return this.och.facesService.createFaceFromMultipleCircleTanWires(e)}getFace(e){return this.och.shapeGettersService.getFace(e)}getFaces(e){return this.och.shapeGettersService.getFaces(e)}reversedFace(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}getFaceArea(e){return this.och.facesService.getFaceArea(e)}getFacesAreas(e){return this.och.facesService.getFacesAreas(e)}getFaceCenterOfMass(e){return this.och.facesService.getFaceCenterOfMass(e)}getFacesCentersOfMass(e){return this.och.facesService.getFacesCentersOfMass(e)}filterFacePoints(e){return this.och.facesService.filterFacePoints(e)}}class X{constructor(e,t){this.occ=e,this.och=t}makeCompound(e){return this.och.converterService.makeCompound(e)}}class Z{constructor(e,t){this.occ=e,this.och=t}vertexFromPoint(e){return this.och.entitiesService.makeVertex(e.point)}verticesFromPoints(e){return e.points.map((e=>this.vertexFromPoint({point:e})))}verticesCompoundFromPoints(e){const t=this.verticesFromPoints(e);return this.och.converterService.makeCompound({shapes:t})}getVertices(e){return this.och.shapeGettersService.getVertices(e)}getVerticesAsPoints(e){return this.och.verticesService.getVerticesAsPoints(e)}verticesToPoints(e){return this.och.verticesService.verticesToPoints(e)}vertexToPoint(e){return this.och.converterService.vertexToPoint(e)}}class J{constructor(e,t){this.occ=e,this.och=t}purgeInternalEdges(e){const t=new this.occ.TopOpeBRepTool_PurgeInternalEdges(e.shape,!0);if(t.Perform(),t.IsDone())return t.Shape();throw new Error("Could not purge internal edges for the shape")}unifySameDomain(e){const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e.shape,e.unifyEdges,e.unifyFaces,e.concatBSplines);return t.Build(),t.Shape()}isClosed(e){return e.shape.Closed_1()}isConvex(e){return e.shape.Convex_1()}isChecked(e){return e.shape.Checked_1()}isFree(e){return e.shape.Free_1()}isInfinite(e){return e.shape.Infinite_1()}isModified(e){return e.shape.Modified_1()}isLocked(e){return e.shape.Locked_1()}isNull(e){return e.shape.IsNull()}isEqual(e){return e.shape.IsEqual(e.otherShape)}isNotEqual(e){return e.shape.IsNotEqual(e.otherShape)}isPartner(e){return e.shape.IsPartner(e.otherShape)}isSame(e){return e.shape.IsSame(e.otherShape)}getOrientation(e){const t=e.shape.Orientation_1();let r;return t===this.occ.TopAbs_Orientation.TopAbs_FORWARD?r=U.topAbsOrientationEnum.forward:t===this.occ.TopAbs_Orientation.TopAbs_REVERSED?r=U.topAbsOrientationEnum.reversed:t===this.occ.TopAbs_Orientation.TopAbs_INTERNAL?r=U.topAbsOrientationEnum.internal:t===this.occ.TopAbs_Orientation.TopAbs_EXTERNAL&&(r=U.topAbsOrientationEnum.external),r}getShapeType(e){return this.och.enumService.getShapeTypeEnum(e.shape)}}class Q{constructor(e,t){this.occ=e,this.och=t}sewFaces(e){return this.och.shellsService.sewFaces(e)}isClosed(e){return this.occ.BRep_Tool.IsClosed_1(e.shape)}getShellSurfaceArea(e){return this.och.shellsService.getShellSurfaceArea(e)}}class K{constructor(e,t){this.occ=e,this.och=t}fromClosedShell(e){return this.och.solidsService.fromClosedShell(e)}createBox(e){return this.och.solidsService.createBox(e)}createCube(e){return this.och.solidsService.createCube(e)}createBoxFromCorner(e){return this.och.solidsService.createBoxFromCorner(e)}createCylinder(e){return this.och.solidsService.createCylinder(e)}createCylindersOnLines(e){return this.och.solidsService.createCylindersOnLines(e)}createSphere(e){return this.och.solidsService.createSphere(e)}createCone(e){return this.och.solidsService.createCone(e)}getSolidSurfaceArea(e){return this.och.solidsService.getSolidSurfaceArea(e)}getSolidVolume(e){return this.och.solidsService.getSolidVolume(e)}getSolidsVolumes(e){return this.och.solidsService.getSolidsVolumes(e)}getSolidCenterOfMass(e){return this.och.solidsService.getSolidCenterOfMass(e)}getSolidsCentersOfMass(e){return this.och.solidsService.getSolidsCentersOfMass(e)}getSolids(e){return this.och.solidsService.getSolids(e)}filterSolidPoints(e){return this.och.solidsService.filterSolidPoints(e)}}class ee{constructor(e,t){this.occ=e,this.och=t}createPolygonWire(e){return this.och.wiresService.createPolygonWire(e)}createPolygons(e){const t=e.polygons.map((e=>this.createPolygonWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createPolylineWire(e){return this.och.wiresService.createPolylineWire(e)}createPolylines(e){const t=e.polylines.map((e=>this.createPolylineWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createLineWire(e){return this.och.wiresService.createLineWire(e)}createLines(e){const t=e.lines.map((e=>this.createLineWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createBezier(e){return this.och.wiresService.createBezier(e)}createBezierWires(e){const t=e.bezierWires.map((e=>this.createBezier(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}interpolatePoints(e){return this.och.wiresService.interpolatePoints(e)}interpolateWires(e){const t=e.interpolations.map((e=>this.interpolatePoints(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}splitOnPoints(e){return this.och.wiresService.splitOnPoints(e)}combineEdgesAndWiresIntoAWire(e){return this.och.converterService.combineEdgesAndWiresIntoAWire(e)}createWireFromEdge(e){return this.och.wiresService.createWireFromEdges(e)}addEdgesAndWiresToWire(e){return this.och.wiresService.addEdgesAndWiresToWire(e)}createBSpline(e){return this.och.wiresService.createBSpline(e)}createBSplines(e){const t=e.bSplines.map((e=>this.createBSpline(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createZigZagBetweenTwoWires(e){return this.och.wiresService.createZigZagBetweenTwoWires(e)}divideWireByParamsToPoints(e){return this.och.wiresService.divideWireByParamsToPoints(e)}divideWiresByParamsToPoints(e){return e.shapes.map((t=>this.divideWireByParamsToPoints(Object.assign(Object.assign({},e),{shape:t}))))}divideWireByEqualDistanceToPoints(e){return this.och.wiresService.divideWireByEqualDistanceToPoints(e)}divideWiresByEqualDistanceToPoints(e){return e.shapes.map((t=>this.divideWireByEqualDistanceToPoints(Object.assign(Object.assign({},e),{shape:t}))))}pointOnWireAtParam(e){return this.och.wiresService.pointOnWireAtParam(e)}pointOnWireAtLength(e){return this.och.wiresService.pointOnWireAtLength(e)}tangentOnWireAtParam(e){return this.och.wiresService.tangentOnWireAtParam(e)}tangentOnWireAtLength(e){return this.och.wiresService.tangentOnWireAtLength(e)}derivativesOnWireAtLength(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1),i=new this.occ.GCPnts_AbscissaPoint_2(r,e.length,r.FirstParameter()),n=i.Parameter(),s=this.och.entitiesService.gpPnt([0,0,0]),o=this.och.entitiesService.gpVec([0,0,0]),a=this.och.entitiesService.gpVec([0,0,0]),c=this.och.entitiesService.gpVec([0,0,0]);r.D3(n,s,o,a,c);const h=[[o.X(),o.Y(),o.Z()],[a.X(),a.Y(),a.Z()],[c.X(),c.Y(),c.Z()]];return o.delete(),a.delete(),c.delete(),r.delete(),i.delete(),s.delete(),h}derivativesOnWireAtParam(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1),i=this.och.entitiesService.gpPnt([0,0,0]),n=this.och.entitiesService.gpVec([0,0,0]),s=this.och.entitiesService.gpVec([0,0,0]),o=this.och.entitiesService.gpVec([0,0,0]),a=this.och.vecHelper.remap(e.param,0,1,r.FirstParameter(),r.LastParameter());r.D3(a,i,n,s,o);const c=[[n.X(),n.Y(),n.Z()],[s.X(),s.Y(),s.Z()],[o.X(),o.Y(),o.Z()]];return n.delete(),s.delete(),o.delete(),r.delete(),i.delete(),c}startPointOnWire(e){return this.och.wiresService.startPointOnWire(e)}endPointOnWire(e){return this.och.wiresService.endPointOnWire(e)}createCircleWire(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.wire)}createEllipseWire(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.wire)}createSquareWire(e){return this.och.wiresService.createSquareWire(e)}createStarWire(e){return this.och.wiresService.createStarWire(e)}createChristmasTreeWire(e){return this.och.wiresService.createChristmasTreeWire(e)}createParallelogramWire(e){return this.och.wiresService.createParallelogramWire(e)}createHeartWire(e){return this.och.wiresService.createHeartWire(e)}createNGonWire(e){return this.och.wiresService.createNGonWire(e)}createRectangleWire(e){return this.och.wiresService.createRectangleWire(e)}createLPolygonWire(e){return this.och.wiresService.createLPolygonWire(e)}getWire(e){return this.och.shapeGettersService.getWire(e)}getWires(e){return this.och.shapeGettersService.getWires(e)}getWireLength(e){return this.och.wiresService.getWireLength(e)}getWiresLengths(e){return this.och.wiresService.getWiresLengths(e)}getWireCenterOfMass(e){return this.och.wiresService.getWireCenterOfMass(e)}getWiresCentersOfMass(e){return e.shapes.map((e=>this.och.wiresService.getWireCenterOfMass({shape:e})))}reversedWire(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}reversedWireFromReversedEdges(e){const t=e.shape,r=this.och.edgesService.getEdgesAlongWire({shape:t}).map((e=>this.och.converterService.getActualTypeOfShape(e.Reversed()))),i=this.och.converterService.combineEdgesAndWiresIntoAWire({shapes:r.reverse()}),n=this.och.converterService.getActualTypeOfShape(i);return i.delete(),r.forEach((e=>e.delete())),n}placeWireOnFace(e){const t=e.wire,r=e.face,i=this.och.surfaceFromFace({shape:r});return this.och.wiresService.placeWire(t,i)}placeWiresOnFace(e){const t=e.wires,r=e.face,i=this.och.surfaceFromFace({shape:r});return t.map((e=>this.och.wiresService.placeWire(e,i)))}closeOpenWire(e){const t=e.shape,r=this.och.wiresService.startPointOnWire({shape:t}),i=this.och.wiresService.endPointOnWire({shape:t});if(this.och.vecHelper.vectorsTheSame(r,i,1e-7))return t;const n=this.createLineWire({start:i,end:r}),s=this.addEdgesAndWiresToWire({shape:t,shapes:[n]});return n.delete(),s}project(e){const t=e.wire,r=this.och.entitiesService.gpDir(e.direction),i=new this.occ.BRepProj_Projection_1(t,e.shape,r),n=i.Shape();return r.delete(),i.delete(),n}wiresToPoints(e){const t=this.getWires({shape:e.shape}),r=[];return t.forEach((t=>{const i=this.och.edgesService.edgesToPoints(Object.assign(Object.assign({},e),{shape:t})).flat(),n=this.och.vecHelper.removeConsecutiveDuplicates(i,!1);r.push(n)})),r}projectWires(e){const t=[];return e.wires.forEach((r=>{const i=this.och.entitiesService.gpDir(e.direction),n=new this.occ.BRepProj_Projection_1(r,e.shape,i),s=n.Shape();t.push(s),i.delete(),n.delete()})),t}createWireFromTwoCirclesTan(e){return this.och.wiresService.createWireFromTwoCirclesTan(e)}}class te{constructor(e,t){this.vertex=new Z(e,t),this.edge=new $(e,t),this.wire=new ee(e,t),this.face=new Y(e,t),this.shell=new Q(e,t),this.solid=new K(e,t),this.compound=new X(e,t),this.shape=new J(e,t)}}class re{constructor(e){this.occ=e}BRep_Tool_Range_1(e,t,r){return this.occ.BRep_Tool.Range_1(e,t,r)}BRep_Tool_Curve_2(e,t,r){return this.occ.BRep_Tool.Curve_2(e,t,r)}BRepTools_UVBounds_1(e,t,r,i,n){return this.occ.BRepTools.UVBounds_1(e,t,r,i,n)}}class ie{constructor(e){this.occ=e}forEachWire(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_WIRE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_WIRE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Wire_2(i.Current()));i.delete()}forEachEdge(e,t){const r={};let i=0;const n=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(n.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);n.More();n.Next()){const e=this.occ.TopoDS.Edge_1(n.Current()),s=e.HashCode(1e8);Object.prototype.hasOwnProperty.call(r,s)||(r[s]=i,i++,t(i,e))}return n.delete(),r}forEachEdgeAlongWire(e,t){const r={};let i=0;const n=new this.occ.BRepTools_WireExplorer_1;for(n.Init_1(e);n.More();n.Next()){const e=this.occ.TopoDS.Edge_1(n.Current()),s=e.HashCode(1e8);Object.prototype.hasOwnProperty.call(r,s)||(r[s]=i,i++,t(i,e))}return n.delete(),r}forEachFace(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_FACE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_FACE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Face_1(i.Current()));i.delete()}forEachShell(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_SHELL,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_SHELL,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Shell_1(i.Current()));i.delete()}forEachVertex(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Vertex_1(i.Current()));i.delete()}forEachSolid(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_SOLID,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_SOLID,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Solid_2(i.Current()));i.delete()}}class ne{constructor(e){this.occ=e}getShapeTypeEnum(e){let t=U.shapeTypeEnum.unknown;const r=e.ShapeType();return t=r===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?U.shapeTypeEnum.edge:r===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?U.shapeTypeEnum.wire:r===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?U.shapeTypeEnum.vertex:r===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?U.shapeTypeEnum.solid:r===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?U.shapeTypeEnum.shell:r===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?U.shapeTypeEnum.face:r===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?U.shapeTypeEnum.compSolid:r===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?U.shapeTypeEnum.compound:U.shapeTypeEnum.shape,t}getGccEntPositionFromEnum(e){let t=this.occ.GccEnt_Position.GccEnt_noqualifier;return t=e===U.gccEntPositionEnum.unqualified?this.occ.GccEnt_Position.GccEnt_unqualified:e===U.gccEntPositionEnum.enclosed?this.occ.GccEnt_Position.GccEnt_enclosed:e===U.gccEntPositionEnum.enclosing?this.occ.GccEnt_Position.GccEnt_enclosing:e===U.gccEntPositionEnum.outside?this.occ.GccEnt_Position.GccEnt_outside:(U.gccEntPositionEnum.noqualifier,this.occ.GccEnt_Position.GccEnt_noqualifier),t}getTopAbsStateEnum(e){let t=U.topAbsStateEnum.unknown;return t=e===this.occ.TopAbs_State.TopAbs_IN?U.topAbsStateEnum.in:e===this.occ.TopAbs_State.TopAbs_OUT?U.topAbsStateEnum.out:e===this.occ.TopAbs_State.TopAbs_ON?U.topAbsStateEnum.on:U.topAbsStateEnum.unknown,t}convertFourSidesStrictEnumToTwoCircleInclusionEnum(e){return e===U.fourSidesStrictEnum.inside?U.twoCircleInclusionEnum.inside:e===U.fourSidesStrictEnum.outside?U.twoCircleInclusionEnum.outside:e===U.fourSidesStrictEnum.insideOutside?U.twoCircleInclusionEnum.insideOutside:e===U.fourSidesStrictEnum.outsideInside?U.twoCircleInclusionEnum.outsideInside:U.twoCircleInclusionEnum.none}}class se{constructor(e){this.occ=e}getActualTypeOfShape(e){let t=e;return t=e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?this.occ.TopoDS.Edge_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?this.occ.TopoDS.Wire_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?this.occ.TopoDS.Vertex_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?this.occ.TopoDS.Solid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?this.occ.TopoDS.Shell_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?this.occ.TopoDS.Face_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.occ.TopoDS.CompSolid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.occ.TopoDS.Compound_1(e):e,t}combineEdgesAndWiresIntoAWire(e){if(void 0===e.shapes)throw Error("Shapes are not defined");const t=new this.occ.BRepBuilderAPI_MakeWire_1;if(e.shapes.forEach((e=>{e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?t.Add_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE&&t.Add_2(e)})),t.IsDone()){this.occ.BRepLib.BuildCurves3d_1(t.Wire(),1e-7,this.occ.GeomAbs_Shape.GeomAbs_C1,14,0);const e=t.Wire();return t.delete(),e}{let e;const r=t.Error();throw t.delete(),r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_DisconnectedWire?e="Wire is disconnected and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_EmptyWire?e="Wire is empty and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_NonManifoldWire?e="Wire is non manifold and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_WireDone&&(e="Wire is done"),new Error(e)}}vertexToPoint(e){const t=this.occ.BRep_Tool.Pnt(e.shape),r=[t.X(),t.Y(),t.Z()];return t.delete(),r}getGeomCurveFromEdge(e,t,r){const i=e.Location_1();return this.occ.BRep_Tool.Curve_1(e,i,t,r).get()}makeCompound(e){const t=new this.occ.TopoDS_Compound,r=new this.occ.BRep_Builder;return r.MakeCompound(t),e.shapes.forEach((e=>{const i=new this.occ.BRepBuilderAPI_Copy_2(e,!0,!1),n=i.Shape();r.Add(t,n),i.delete(),n.delete()})),r.delete(),t}makeCompoundIfNeeded(e,t){if(t){const t=this.makeCompound({shapes:e});return e.forEach((e=>e.delete())),t}return e}}class oe{constructor(e){this.occ=e}createCircle(e,t,r,i){const n=this.gcMakeCircle(t,r,e);if(i===U.typeSpecificityEnum.curve)return n;{const e=this.bRepBuilderAPIMakeEdge(n);if(i===U.typeSpecificityEnum.edge)return e;{const t=this.bRepBuilderAPIMakeWire(e);if(i===U.typeSpecificityEnum.wire)return e.delete(),t;if(i===U.typeSpecificityEnum.face)return this.bRepBuilderAPIMakeFaceFromWire(t,!0)}}return n}createEllipse(e,t,r,i,n){const s=this.gcMakeEllipse(r,i,e,t);if(n===U.typeSpecificityEnum.curve)return s;{const e=this.bRepBuilderAPIMakeEdge(s);if(n===U.typeSpecificityEnum.edge)return e;{const t=this.bRepBuilderAPIMakeWire(e);if(n===U.typeSpecificityEnum.wire)return e.delete(),t;if(n===U.typeSpecificityEnum.face)return this.bRepBuilderAPIMakeFaceFromWire(t,!0)}}return s}makeVertex(e){const t=this.gpPnt(e),r=new this.occ.BRepBuilderAPI_MakeVertex(t),i=r.Vertex();return t.delete(),r.delete(),i}gpPnt2d(e){return new this.occ.gp_Pnt2d_3(e[0],e[1])}gpPnt(e){return new this.occ.gp_Pnt_3(e[0],e[1],e[2])}gpVec(e){return new this.occ.gp_Vec_4(e[0],e[1],e[2])}gpXYZ(e){return new this.occ.gp_XYZ_2(e[0],e[1],e[2])}gpVec2d(e){return new this.occ.gp_Vec2d_4(e[0],e[1])}gpDir(e){return new this.occ.gp_Dir_4(e[0],e[1],e[2])}gpDir2d(e){return new this.occ.gp_Dir2d_4(e[0],e[1])}gcMakeCircle(e,t,r){const i=new this.occ.GC_MakeCircle_2(this.gpAx2(e,t),r),n=i.Value().get();return i.delete(),n}gcMakeEllipse(e,t,r,i){const n=this.gpAx2(e,t),s=new this.occ.GC_MakeEllipse_2(n,i,r);if(s.IsDone()){const e=s.Value().get();return s.delete(),n.delete(),e}throw new Error("Ellipse could not be created.")}bRepBuilderAPIMakeEdge(e){const t=this.castToHandleGeomCurve(e),r=new this.occ.BRepBuilderAPI_MakeEdge_24(t),i=r.Edge();return r.delete(),t.delete(),i}bRepBuilderAPIMakeWire(e){const t=new this.occ.BRepBuilderAPI_MakeWire_2(e),r=t.Wire();return t.delete(),r}bRepBuilderAPIMakeShell(e){const t=this.occ.BRep_Tool.Surface_2(e),r=new this.occ.BRepBuilderAPI_MakeShell_2(t,!1),i=r.Shell();return r.delete(),t.delete(),i}bRepBuilderAPIMakeFaceFromWires(e,t){let r;const i=[];return e.forEach((e=>{if(i.length>0){const t=new this.occ.BRepBuilderAPI_MakeFace_22(i[i.length-1],e);i.push(t.Face()),t.delete()}else{const r=new this.occ.BRepBuilderAPI_MakeFace_15(e,t);i.push(r.Face()),r.delete()}})),i.length>0&&(r=i.pop(),i.forEach((e=>e.delete()))),r}bRepBuilderAPIMakeFaceFromWire(e,t){const r=new this.occ.BRepBuilderAPI_MakeFace_15(e,t),i=r.Face();return r.delete(),i}bRepBuilderAPIMakeFaceFromSurface(e,t){const r=new this.occ.Handle_Geom_Surface_2(e),i=new this.occ.BRepBuilderAPI_MakeFace_8(r,t),n=i.Face();return i.delete(),r.delete(),n}bRepBuilderAPIMakeFaceFromSurfaceAndWire(e,t,r){const i=new this.occ.Handle_Geom_Surface_2(e),n=new this.occ.BRepBuilderAPI_MakeFace_21(i,t,r),s=n.Face();return n.delete(),i.delete(),s}bRepPrimAPIMakeSphere(e,t,r){const i=this.gpAx2(e,t),n=new this.occ.BRepPrimAPI_MakeSphere_9(i,r),s=n.Shape();return n.delete(),i.delete(),s}gpAx3(e,t){return new this.occ.gp_Ax3_4(this.gpPnt(e),this.gpDir(t))}gpAx2(e,t){return new this.occ.gp_Ax2_3(this.gpPnt(e),this.gpDir(t))}gpAx2FromTwoVectors(e,t,r){return new this.occ.gp_Ax2_2(this.gpPnt(e),this.gpDir(t),this.gpDir(r))}gpAx1(e,t){return new this.occ.gp_Ax1_2(this.gpPnt(e),this.gpDir(t))}gpAx2d(e,t){const r=this.gpPnt2d(e),i=this.gpDir2d(t);return new this.occ.gp_Ax2d_2(r,i)}gpAx22d(e,t,r){const i=this.gpPnt2d(e),n=this.gpDir2d(t),s=this.gpDir2d(r),o=new this.occ.gp_Ax22d_2(i,n,s);return n.delete(),s.delete(),i.delete(),o}gpPln(e,t){const r=this.gpPnt(e),i=this.gpDir(t),n=new this.occ.gp_Pln_3(r,i);return r.delete(),i.delete(),n}bRepPrimAPIMakeCylinder(e,t,r,i){const n=this.gpAx2(e,t),s=new this.occ.BRepPrimAPI_MakeCylinder_3(n,r,i),o=s.Shape();return s.delete(),n.delete(),o}bRepPrimAPIMakeCylinderBetweenPoints(e,t,r){const i=this.gpPnt(e),n=this.gpPnt(t),s=new this.occ.gp_Vec_5(i,n),o=s.Magnitude(),a=this.gpAx2(e,[s.X(),s.Y(),s.Z()]),c=new this.occ.BRepPrimAPI_MakeCylinder_3(a,r,o),h=c.Shape();return c.delete(),a.delete(),i.delete(),n.delete(),s.delete(),h}bRepPrimAPIMakeBox(e,t,r,i){const n=this.gpPnt([-e/2+i[0],-r/2+i[1],-t/2+i[2]]),s=new this.occ.BRepPrimAPI_MakeBox_3(n,e,r,t),o=s.Shape();return s.delete(),n.delete(),o}castToHandleGeomCurve(e){return new this.occ.Handle_Geom_Curve_2(e)}}class ae{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.occ=e,this.enumService=t,this.entitiesService=r,this.converterService=i,this.booleansService=n,this.shapeGettersService=s,this.edgesService=o,this.transformsService=a,this.vecHelper=c,this.wiresService=h,this.facesService=l,this.shellsService=u}loftAdvanced(e){if(e.periodic&&!e.closed)throw new Error("Cant construct periodic non closed loft.");const t=new this.occ.BRepOffsetAPI_ThruSections(e.makeSolid,e.straight,e.tolerance),r=[],i=[];if(e.startVertex){const r=this.entitiesService.makeVertex(e.startVertex);t.AddVertex(r),i.push(r)}if(e.closed&&!e.periodic)e.shapes.push(e.shapes[0]);else if(e.closed&&e.periodic){const i=[];e.shapes.forEach((t=>{this.enumService.getShapeTypeEnum(t)===U.shapeTypeEnum.edge&&(t=this.entitiesService.bRepBuilderAPIMakeWire(t));const r=this.wiresService.divideWireByParamsToPoints({shape:t,nrOfDivisions:e.nrPeriodicSections,removeStartPoint:!1,removeEndPoint:!1});i.push(r)}));for(let n=0;n<=e.nrPeriodicSections;n++){const s=i.map((e=>e[n])),o=this.wiresService.interpolatePoints({points:s,tolerance:e.tolerance,periodic:!0});t.AddWire(o),r.push(o)}}e.periodic||e.shapes.forEach((e=>{t.AddWire(e)}));const n=[];if(e.endVertex){const r=this.entitiesService.makeVertex(e.endVertex);t.AddVertex(r),n.push(r)}let s;e.useSmoothing&&t.SetSmoothing(e.useSmoothing),e.maxUDegree&&t.SetMaxDegree(e.maxUDegree),e.parType===U.approxParametrizationTypeEnum.approxChordLength?s=this.occ.Approx_ParametrizationType.Approx_ChordLength:e.parType===U.approxParametrizationTypeEnum.approxCentripetal?s=this.occ.Approx_ParametrizationType.Approx_Centripetal:e.parType===U.approxParametrizationTypeEnum.approxIsoParametric&&(s=this.occ.Approx_ParametrizationType.Approx_IsoParametric),s&&t.SetParType(s),t.CheckCompatibility(!1);const o=t.Shape(),a=this.converterService.getActualTypeOfShape(o);return o.delete(),t.delete(),r.forEach((e=>e.delete())),i.forEach((e=>e.delete())),n.forEach((e=>e.delete())),a}closestPointsBetweenTwoShapes(e,t){const r=new this.occ.Message_ProgressRange_1,i=new this.occ.BRepExtrema_DistShapeShape_2(e,t,this.occ.Extrema_ExtFlag.Extrema_ExtFlag_MIN,this.occ.Extrema_ExtAlgo.Extrema_ExtAlgo_Grad,r),n=new this.occ.Message_ProgressRange_1;if(i.Perform(n),i.IsDone()&&i.NbSolution()>0){const e=i.PointOnShape1(1),t=i.PointOnShape2(1);return[[e.X(),e.Y(),e.Z()],[t.X(),t.Y(),t.Z()]]}throw new Error("Closest points could not be found.")}closestPointsOnShapeFromPoints(e){return e.points.map((e=>this.entitiesService.makeVertex(e))).map((t=>this.closestPointsBetweenTwoShapes(t,e.shape))).map((e=>e[1]))}closestPointsOnShapesFromPoints(e){const t=e.points.map((e=>this.entitiesService.makeVertex(e))),r=[];return e.shapes.forEach((e=>{const i=t.map((t=>this.closestPointsBetweenTwoShapes(t,e)));r.push(...i.map((e=>e[1])))})),r}distancesToShapeFromPoints(e){return e.points.map((e=>this.entitiesService.makeVertex(e))).map((t=>this.closestPointsBetweenTwoShapes(t,e.shape))).map((e=>this.vecHelper.distanceBetweenPoints(e[0],e[1])))}loft(e){const t=new this.occ.BRepOffsetAPI_ThruSections(e.makeSolid,!1,1e-6);e.shapes.forEach((e=>{this.enumService.getShapeTypeEnum(e)===U.shapeTypeEnum.edge&&(e=this.entitiesService.bRepBuilderAPIMakeWire(e)),t.AddWire(e)})),t.CheckCompatibility(!1);const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);return r.delete(),t.delete(),i}offset(e){return this.offsetAdv({shape:e.shape,face:e.face,distance:e.distance,tolerance:e.tolerance,joinType:U.joinTypeEnum.arc,removeIntEdges:!1})}offsetAdv(e){if(e.tolerance||(e.tolerance=.1),0===e.distance)return e.shape;let t;const r=this.getJoinType(e.joinType),i=this.occ.BRepOffset_Mode.BRepOffset_Skin,n=[];if(this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.wire||this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge){let s;this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge?(s=this.entitiesService.bRepBuilderAPIMakeWire(e.shape),n.push(s)):s=e.shape;try{t=new this.occ.BRepOffsetAPI_MakeOffset_1,e.face?t.Init_1(e.face,r,!1):t.Init_2(r,!1),t.AddWire(s);const i=new this.occ.Message_ProgressRange_1;t.Build(i),t.Perform(e.distance,0)}catch(n){t=new this.occ.BRepOffsetAPI_MakeOffsetShape,t.PerformByJoin(s,e.distance,e.tolerance,i,!1,!1,r,e.removeIntEdges,new this.occ.Message_ProgressRange_1)}}else{const n=e.shape;t=new this.occ.BRepOffsetAPI_MakeOffsetShape,t.PerformByJoin(n,e.distance,e.tolerance,i,!1,!1,r,e.removeIntEdges,new this.occ.Message_ProgressRange_1)}const s=t.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),t&&t.delete(),n.forEach((e=>e.delete())),o}offset3DWire(e){const t=this.extrude({shape:e.shape,direction:e.direction}),r=this.makeThickSolidSimple({shape:t,offset:e.offset}),i=this.shapeGettersService.getEdges({shape:e.shape}).length,n=(4*i+2)/2-1,s=n-i+1,o=[];let a;this.shapeGettersService.getFaces({shape:r}).forEach(((e,t)=>{if(t>=s&&t<=n){const t=this.shapeGettersService.getEdges({shape:e})[2];o.push(t)}}));try{a=this.converterService.combineEdgesAndWiresIntoAWire({shapes:o}),a=a.Reversed(),a=this.converterService.getActualTypeOfShape(a)}catch(e){return a=o,a}return a}extrudeShapes(e){return e.shapes.map((t=>{const r=this.extrude({shape:t,direction:e.direction}),i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}))}extrude(e){const t=new this.occ.gp_Vec_4(e.direction[0],e.direction[1],e.direction[2]),r=new this.occ.BRepPrimAPI_MakePrism_1(e.shape,t,!1,!0),i=r.Shape();return r.delete(),t.delete(),i}splitShapeWithShapes(e){const t=new this.occ.TopTools_ListOfShape_1;return e.shapes.forEach((e=>{t.Append_1(e)})),this.occ.BitByBitDev.BitSplit(e.shape,t)}revolve(e){let t;if(e.angle||(e.angle=360),e.direction||(e.direction=[0,0,1]),e.angle>=360){const r=new this.occ.gp_Pnt_3(0,0,0),i=new this.occ.gp_Dir_4(e.direction[0],e.direction[1],e.direction[2]),n=new this.occ.gp_Ax1_2(r,i),s=new this.occ.BRepPrimAPI_MakeRevol_2(e.shape,n,e.copy);t=s.Shape(),s.delete(),r.delete(),i.delete(),n.delete()}else{const r=new this.occ.gp_Pnt_3(0,0,0),i=new this.occ.gp_Dir_4(e.direction[0],e.direction[1],e.direction[2]),n=new this.occ.gp_Ax1_2(r,i),s=new this.occ.BRepPrimAPI_MakeRevol_1(e.shape,n,.0174533*e.angle,e.copy);t=s.Shape(),s.delete(),r.delete(),i.delete(),n.delete()}const r=this.converterService.getActualTypeOfShape(t);return t.delete(),r}rotatedExtrude(e){const t=this.transformsService.translate({translation:[0,e.height,0],shape:e.shape}),r=this.transformsService.rotate({axis:[0,1,0],angle:e.angle,shape:t}),i=this.wiresService.createBSpline({points:[[0,0,0],[0,e.height,0]],closed:!1}),n=[];for(let t=0;t<=30;t++){const r=t/30;n.push([20*Math.sin(r*e.angle*.0174533),e.height*r,20*Math.cos(r*e.angle*.0174533)])}const s=this.wiresService.createBSpline({points:n,closed:!1}),o=new this.occ.BRepOffsetAPI_MakePipeShell(i);o.SetMode_5(s,!0,this.occ.BRepFill_TypeOfContact.BRepFill_NoContact),o.Add_1(e.shape,!1,!1),o.Add_1(r,!1,!1),o.Build(new this.occ.Message_ProgressRange_1),o.MakeSolid();const a=o.Shape(),c=this.converterService.getActualTypeOfShape(a);return a.delete(),o.delete(),s.delete(),i.delete(),r.delete(),t.delete(),c}pipe(e){const t=new this.occ.BRepOffsetAPI_MakePipeShell(e.shape);e.shapes.forEach((e=>{t.Add_1(e,!1,!1)})),t.Build(new this.occ.Message_ProgressRange_1),t.MakeSolid();const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);return r.delete(),t.delete(),i}pipePolylineWireNGon(e){const t=e.shape,r=[],i=this.shapeGettersService.getEdges({shape:t});i.forEach(((t,n)=>{const s=this.edgesService.startPointOnEdge({shape:t}),o=this.edgesService.tangentOnEdgeAtParam({shape:t,param:0});let a,c=o;if(n>0&&n{n.Add_1(e,!1,!1)})),n.Build(new this.occ.Message_ProgressRange_1),n.MakeSolid();const s=n.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),n.delete(),o}pipeWireCylindrical(e){const t=e.shape,r=[],i=this.shapeGettersService.getEdges({shape:t});i.forEach(((t,n)=>{const s=this.edgesService.startPointOnEdge({shape:t}),o=this.edgesService.tangentOnEdgeAtParam({shape:t,param:0});let a,c=o;if(n>0&&n{n.Add_1(e,!1,!1)})),n.Build(new this.occ.Message_ProgressRange_1),n.MakeSolid();const s=n.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),n.delete(),o}pipeWiresCylindrical(e){return e.shapes.map((t=>this.pipeWireCylindrical({shape:t,radius:e.radius})))}makeThickSolidSimple(e){const t=new this.occ.BRepOffsetAPI_MakeThickSolid;t.MakeThickSolidBySimple(e.shape,e.offset),t.Build(new this.occ.Message_ProgressRange_1);const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);let n=i;if(e.offset>0){const e=this.shapeGettersService.getFaces({shape:i}).map((e=>e.Reversed()));n=this.shellsService.sewFaces({shapes:e,tolerance:1e-7}),i.delete()}return t.delete(),r.delete(),n}makeThickSolidByJoin(e){const t=new this.occ.TopTools_ListOfShape_1;e.shapes.forEach((e=>{t.Append_1(e)}));const r=new this.occ.BRepOffsetAPI_MakeThickSolid,i=this.getJoinType(e.joinType);r.MakeThickSolidByJoin(e.shape,t,e.offset,e.tolerance,this.occ.BRepOffset_Mode.BRepOffset_Skin,e.intersection,e.selfIntersection,i,e.removeIntEdges,new this.occ.Message_ProgressRange_1);const n=r.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),r.delete(),t.delete(),s}getJoinType(e){let t;switch(e){case U.joinTypeEnum.arc:t=this.occ.GeomAbs_JoinType.GeomAbs_Arc;break;case U.joinTypeEnum.intersection:t=this.occ.GeomAbs_JoinType.GeomAbs_Intersection;break;case U.joinTypeEnum.tangent:t=this.occ.GeomAbs_JoinType.GeomAbs_Tangent}return t}getBRepOffsetMode(e){let t;switch(e){case U.bRepOffsetModeEnum.skin:t=this.occ.BRepOffset_Mode.BRepOffset_Skin;break;case U.bRepOffsetModeEnum.pipe:t=this.occ.BRepOffset_Mode.BRepOffset_Pipe;break;case U.bRepOffsetModeEnum.rectoVerso:t=this.occ.BRepOffset_Mode.BRepOffset_RectoVerso}return t}slice(e){if(e.step<=0)throw new Error("Step needs to be positive.");const{bbox:t,transformedShape:r}=this.createBBoxAndTransformShape(e.shape,e.direction),i=[];if(!t.IsThin(1e-4)){const{minY:n,maxY:s,maxDist:o}=this.computeBounds(t),a=[];for(let t=n;t=h?c:h;return l*=1.2,{minY:i,maxY:n,maxDist:l}}applySlices(e,t,r,i){const n=[];if(this.enumService.getShapeTypeEnum(e)===U.shapeTypeEnum.solid)n.push(e);else{const t=this.shapeGettersService.getSolids({shape:e});n.push(...t)}if(0===n.length)throw new Error("No solids found to slice.");n.forEach((e=>{const n=new U.IntersectionDto;n.keepEdges=!0,n.shapes=[e];const s=this.converterService.makeCompound({shapes:t});n.shapes.push(s),this.booleansService.intersection(n).forEach((e=>{if(e&&!e.IsNull()){const t=this.transformsService.align({shape:e,fromOrigin:[0,0,0],fromDirection:[0,1,0],toOrigin:[0,0,0],toDirection:r});i.push(t)}}))}))}}class ce{constructor(e,t,r,i){this.occ=e,this.converterService=t,this.entitiesService=r,this.vecHelper=i}alignAndTranslate(e){const t=this.align({shape:e.shape,fromOrigin:[0,0,0],fromDirection:[0,1,0],toOrigin:[0,0,0],toDirection:e.direction}),r=this.translate({shape:t,translation:e.center});return t.delete(),r}translate(e){const t=new this.occ.gp_Trsf_1,r=new this.occ.gp_Vec_4(e.translation[0],e.translation[1],e.translation[2]);t.SetTranslation_1(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),t.delete(),i.delete(),r.delete(),s}mirror(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx1(e.origin,e.direction);t.SetMirror_2(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),i.delete(),t.delete(),r.delete(),s}mirrorAlongNormal(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx2(e.origin,e.normal);t.SetMirror_3(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return r.delete(),n.delete(),i.delete(),t.delete(),s}rotate(e){let t;if(0!==e.angle){const t=new this.occ.gp_Trsf_1,r=new this.occ.gp_Vec_4(e.axis[0],e.axis[1],e.axis[2]),i=new this.occ.gp_Dir_4(e.axis[0],e.axis[1],e.axis[2]),n=new this.occ.gp_Pnt_3(0,0,0),s=new this.occ.gp_Ax1_2(n,i);t.SetRotation_1(s,this.vecHelper.degToRad(e.angle));const o=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),a=o.Shape(),c=this.converterService.getActualTypeOfShape(a);return a.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),t.delete(),c}t=e.shape;const r=this.converterService.getActualTypeOfShape(t);return 0!==e.angle&&t.delete(),r}align(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx3(e.fromOrigin,e.fromDirection),i=this.entitiesService.gpAx3(e.toOrigin,e.toDirection);t.SetDisplacement(r,i);const n=new this.occ.TopLoc_Location_2(t),s=e.shape.Moved(n,!1);t.delete(),r.delete(),i.delete();const o=this.converterService.getActualTypeOfShape(s);return s.delete(),o}}class he{constructor(e,t){this.occ=e,this.shapeGettersService=t}intersection(e){if(e.shapes.length<2)throw new Error("Intersection requires 2 or more shapes to be given");const t=e.shapes[0];let r=[];for(let i=1;i0&&(r=r.map((e=>{const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e,!0,!0,!1);t.Build();const r=t.Shape();return t.delete(),r}))),r}difference(e){let t=e.shape;const r=e.shapes;for(let e=0;e{t++})),t}getSolidFromCompound(e,t){if(!e||e.ShapeType()>this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID||e.IsNull())return console.error("Not a compound shape!"),e;t||(t=0);let r=e,i=0;return this.iteratorService.forEachSolid(e,((e,n)=>{e===t&&(r=this.occ.TopoDS.Solid_1(n)),i++})),0===i&&console.error("NO SOLIDS FOUND IN SHAPE!"),r.hash=e.hash+1,r}getEdges(e){if(e.shape&&this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge)return[e.shape];if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is of incorrect type");const t=[];return this.iteratorService.forEachEdge(e.shape,((e,r)=>{t.push(r)})),t}getEdge(e){if(!e.shape||e.shape.ShapeType&&e.shape.ShapeType()>this.occ.TopAbs_ShapeEnum.TopAbs_WIRE||e.shape.IsNull())throw new Error("Edge can not be found for shape that is not provided or is of incorrect type");e.index||(e.index=0);let t={},r=!1;if(this.iteratorService.forEachEdge(e.shape,((i,n)=>{i===e.index&&(t=n,r=!0)})),r)return t;throw new Error(`Edge can not be found for shape on index ${e.index}`)}getWires(e){const t=[];return this.iteratorService.forEachWire(e.shape,((e,r)=>{t.push(r)})),t}getWire(e){if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is null");const t=this.enumService.getShapeTypeEnum(e.shape);if(t===U.shapeTypeEnum.wire||t===U.shapeTypeEnum.edge||t===U.shapeTypeEnum.vertex)throw new Error("Shape is of incorrect type");let r;if(e.index||(e.index=0),this.iteratorService.forEachWire(e.shape,((t,i)=>{t===e.index&&(r=this.occ.TopoDS.Wire_1(i))})),!r)throw Error("Wire not found");return r}getFaces(e){const t=[];return this.iteratorService.forEachFace(e.shape,((e,r)=>{t.push(r)})),t}getSolids(e){const t=[];return this.iteratorService.forEachSolid(e.shape,((e,r)=>{t.push(r)})),t}getFace(e){if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is null");const t=this.enumService.getShapeTypeEnum(e.shape);if(t===U.shapeTypeEnum.wire||t===U.shapeTypeEnum.edge||t===U.shapeTypeEnum.vertex)throw new Error("Shape is of incorrect type");e.index||(e.index=0);let r={},i=0;if(this.iteratorService.forEachFace(e.shape,((t,n)=>{t===e.index&&(r=this.occ.TopoDS.Face_1(n)),i++})),i{t.push(r)})),t}}class ue{constructor(e,t,r,i,n,s,o,a,c,h){this.occ=e,this.occRefReturns=t,this.shapeGettersService=r,this.entitiesService=i,this.iteratorService=n,this.converterService=s,this.enumService=o,this.geomService=a,this.transformsService=c,this.vecHelper=h}getCornerPointsOfEdgesForShape(e){const t=this.shapeGettersService.getEdges(e);let r=[];return t.forEach((e=>{const t={current:0},i={current:0},n=this.occRefReturns.BRep_Tool_Curve_2(e,t,i);try{const e=n.get();if(e){const n=e.Value(t.current),s=e.Value(i.current),o=[n.X(),n.Y(),n.Z()],a=[s.X(),s.Y(),s.Z()];n.delete(),s.delete(),r.push(o),r.push(a)}}catch(e){console.log(e)}})),r.length>0&&(r=this.vecHelper.removeAllDuplicateVectors(r)),r}getCircularEdgesAlongWire(e){return this.getEdgesAlongWire(e).filter((e=>this.isEdgeCircular({shape:e})))}getLinearEdgesAlongWire(e){return this.getEdgesAlongWire(e).filter((e=>this.isEdgeLinear({shape:e})))}getEdgesAlongWire(e){if(e.shape&&this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge)return[e.shape];if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is of incorrect type");const t=[],r=this.fixEdgeOrientationsAlongWire(e);return this.iteratorService.forEachEdgeAlongWire(r,((e,r)=>{t.push(r)})),t}fixEdgeOrientationsAlongWire(e){const t=[];return this.iteratorService.forEachEdgeAlongWire(e.shape,((e,r)=>{t.push(r)})),this.converterService.combineEdgesAndWiresIntoAWire({shapes:t})}arcThroughThreePoints(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpPnt(e.middle),i=this.entitiesService.gpPnt(e.end),n=new this.occ.GC_MakeArcOfCircle_4(t,r,i),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),a}arcThroughTwoPointsAndTangent(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpVec(e.tangentVec),i=this.entitiesService.gpPnt(e.end),n=new this.occ.GC_MakeArcOfCircle_5(t,r,i),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),a}arcFromCircleAndTwoAngles(e){const t=this.getGpCircleFromEdge({shape:e.circle}),r=this.vecHelper.degToRad(e.alphaAngle1),i=this.vecHelper.degToRad(e.alphaAngle2),n=new this.occ.GC_MakeArcOfCircle_1(t,r,i,e.sense),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),n.delete(),s.delete(),o.delete(),a}arcFromCirclePointAndAngle(e){const t=this.getGpCircleFromEdge({shape:e.circle}),r=this.vecHelper.degToRad(e.alphaAngle),i=this.entitiesService.gpPnt(e.point),n=new this.occ.GC_MakeArcOfCircle_2(t,i,r,e.sense),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),n.delete(),i.delete(),s.delete(),o.delete(),a}lineEdge(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpPnt(e.end),i=new this.occ.GC_MakeSegment_1(t,r).Value(),n=i.get(),s=new this.occ.Handle_Geom_Curve_2(n),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return o.delete(),s.delete(),t.delete(),r.delete(),i.delete(),n.delete(),a}getEdgeLength(e){const t=e.shape,r=new this.occ.GProp_GProps_1;this.occ.BRepGProp.LinearProperties(t,r,!1,!1);const i=r.Mass();return r.delete(),i}getEdgesLengths(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getEdgeLength({shape:e})))}getEdgesCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.geomService.getLinearCenterOfMass({shape:e})))}edgesToPoints(e){const t=this.enumService.getShapeTypeEnum(e.shape);let r=[];r=t===U.shapeTypeEnum.edge?[e.shape]:t===U.shapeTypeEnum.wire?this.getEdgesAlongWire({shape:e.shape}):this.shapeGettersService.getEdges({shape:e.shape});const i=[],n=r.map((e=>this.startPointOnEdge({shape:e})));return r.forEach((t=>{const r=[],n=new this.occ.TopLoc_Location_1,s=new this.occ.BRepAdaptor_Curve_2(t),o=new this.occ.GCPnts_TangentialDeflection_2(s,e.angularDeflection,e.curvatureDeflection,e.minimumOfPoints,e.uTolerance,e.minimumLength),a=o.NbPoints(),c=[];for(let e=0;ee.delete())),n.delete(),s.delete(),o.delete()})),i.forEach(((e,t)=>{const r=this.vecHelper.distanceBetweenPoints(e[0],n[t]);this.vecHelper.distanceBetweenPoints(n[t],e[e.length-1]){const r=new this.occ.GCPnts_AbscissaPoint_2(t,e,t.FirstParameter()),i=r.Parameter();return r.delete(),i})).map((e=>{const r=this.entitiesService.gpPnt([0,0,0]);t.D0(e,r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}))}divideCurveToNrSegments(e,t,r){const i=e.shape,n=[];for(let i=0;i<=e.nrOfDivisions;i++){const s=i/e.nrOfDivisions,o=this.vecHelper.remap(s,0,1,t,r);n.push(o)}return e.removeStartPoint&&n.shift(),e.removeEndPoint&&n.pop(),n.map((e=>{const t=this.entitiesService.gpPnt([0,0,0]);i.D0(e,t);const r=[t.X(),t.Y(),t.Z()];return t.delete(),r}))}startPointOnCurve(e){const t=e.shape,r=this.entitiesService.gpPnt([0,0,0]);t.D0(t.FirstParameter(),r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}endPointOnCurve(e){const t=e.shape,r=this.entitiesService.gpPnt([0,0,0]);t.D0(t.LastParameter(),r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}getLinearCenterOfMass(e){const t=e.shape,r=new this.occ.GProp_GProps_1;this.occ.BRepGProp.LinearProperties(t,r,!1,!1);const i=r.CentreOfMass(),n=[i.X(),i.Y(),i.Z()];return r.delete(),n}}class pe{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.occ=e,this.occRefReturns=t,this.vecHelper=r,this.shapesHelperService=i,this.shapeGettersService=n,this.transformsService=s,this.enumService=o,this.entitiesService=a,this.converterService=c,this.geomService=h,this.edgesService=l,this.booleansService=u}getWireLength(e){return this.shapeGettersService.getEdges(e).map((e=>this.edgesService.getEdgeLength({shape:e}))).reduce(((e,t)=>e+t),0)}getWiresLengths(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getWireLength({shape:e})))}createRectangleWire(e){const t=e.width/2,r=e.length/2,i=[[t,0,r],[-t,0,r],[-t,0,-r],[t,0,-r]].reverse(),n=this.createPolygonWire({points:i}),s=this.transformsService.alignAndTranslate({shape:n,direction:e.direction,center:e.center});return n.delete(),s}createSquareWire(e){return this.createRectangleWire({width:e.size,length:e.size,center:e.center,direction:e.direction})}createChristmasTreeWire(e){const t=this.createLineWire({start:[e.innerDist,0,0],end:[0,e.height,0]}),r=this.createLineWire({start:[e.outerDist,0,0],end:[0,e.height,0]}),i=this.divideWireByEqualDistanceToPoints({shape:t,nrOfDivisions:e.nrSkirts,removeEndPoint:!1,removeStartPoint:!1}),n=this.divideWireByEqualDistanceToPoints({shape:r,nrOfDivisions:e.nrSkirts,removeEndPoint:!1,removeStartPoint:!1}),s=[];if(e.trunkWidth>0&&e.trunkHeight>0?(s.push([0,-e.trunkHeight,0]),s.push([e.trunkWidth/2,-e.trunkHeight,0]),s.push([e.trunkWidth/2,0,0])):s.push([0,0,0]),i.forEach(((t,r)=>{const i=n[r];0===r?s.push(i):0!==r&&r[-e[0],e[1],e[2]]));e.pop(),s.push(...e.reverse())}let o;if(e.trunkHeight>0&&e.trunkWidth>0){const t=s.map((t=>[t[0],t[1]+e.trunkHeight,t[2]]));o=this.createPolylineWire({points:t})}else o=this.createPolylineWire({points:s});const a=this.transformsService.rotate({shape:o,angle:e.rotation,axis:[0,1,0]});return this.transformsService.alignAndTranslate({shape:a,direction:e.direction,center:e.origin})}createStarWire(e){const t=this.shapesHelperService.starLines(e.innerRadius,e.outerRadius,e.numRays,e.half,e.offsetOuterEdges),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createParallelogramWire(e){const t=this.shapesHelperService.parallelogram(e.width,e.height,e.angle,e.aroundCenter),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createHeartWire(e){const t=e.sizeApprox/2,r=[[0,0,.7*t],[t/6,0,.9*t],[t/2,0,t],[.75*t,0,.9*t],[t,0,t/4],[t/2,0,-t/2],[0,0,-t]],i=r.map((e=>[-e[0],e[1],e[2]])),n=1e-5,s=this.interpolatePoints({points:r,periodic:!1,tolerance:n}),o=this.interpolatePoints({points:i.reverse(),periodic:!1,tolerance:n}),a=this.converterService.combineEdgesAndWiresIntoAWire({shapes:[s,o]}),c=this.transformsService.rotate({shape:a,angle:e.rotation,axis:[0,1,0]}),h=this.transformsService.alignAndTranslate({shape:c,direction:e.direction,center:e.center});return a.delete(),c.delete(),s.delete(),o.delete(),h}createNGonWire(e){const t=this.shapesHelperService.ngon(e.nrCorners,e.radius,[0,0]),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createLPolygonWire(e){let t;switch(e.align){case U.directionEnum.outside:t=this.shapesHelperService.polygonL(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;case U.directionEnum.inside:t=this.shapesHelperService.polygonLInverted(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;case U.directionEnum.middle:t=this.shapesHelperService.polygonLMiddle(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;default:t=this.shapesHelperService.polygonL(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond)}const r=this.createPolygonWire({points:t}),i=this.transformsService.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return r.delete(),i.delete(),n}createPolygonWire(e){const t=[];for(let r=0;re.delete())),void t.delete();{const e=i.get(),n=new this.occ.Handle_Geom_Curve_2(e),s=new this.occ.BRepBuilderAPI_MakeEdge_24(n),o=s.Edge(),a=new this.occ.BRepBuilderAPI_MakeWire_2(o),c=a.Wire();return i.Nullify(),i.delete(),n.Nullify(),n.delete(),s.delete(),o.delete(),a.delete(),r.forEach((e=>e.delete())),t.delete(),c}}splitOnPoints(e){const t=1e-7,r=this.startPointOnWire({shape:e.shape}),i=this.endPointOnWire({shape:e.shape}),n=this.vecHelper.vectorsTheSame(i,r,t);n||(e.points.some((e=>this.vecHelper.vectorsTheSame(e,r,t)))||e.points.push(r),e.points.some((e=>this.vecHelper.vectorsTheSame(e,i,t)))||e.points.push(i));const s=this.createLines({lines:e.points.map((e=>({start:e,end:[e[0],e[1]+t,e[2]]}))),returnCompound:!1}),o=this.booleansService.difference({shape:e.shape,shapes:s,keepEdges:!0}),a=this.shapeGettersService.getEdges({shape:o}),c=[];a.forEach((r=>{const i=c[c.length-1],n=this.edgesService.endPointOnEdge({shape:r}),s=this.edgesService.startPointOnEdge({shape:r}),o=e.points.some((e=>this.vecHelper.vectorsTheSame(n,e,t))),a=e.points.some((e=>this.vecHelper.vectorsTheSame(s,e,t)));o&&!a?c.push([r]):!o&&a?i?i.push(r):c.push([r]):o&&a?c.push([r]):o||a||(i?i.push(r):c.push([r]))}));const h=[];if(c.forEach((e=>{const t=this.converterService.combineEdgesAndWiresIntoAWire({shapes:e});h.push(t)})),n&&h.length>1){const r=this.endPointOnWire({shape:h[0]}),i=this.startPointOnWire({shape:h[h.length-1]});if(this.vecHelper.vectorsTheSame(r,i,t)&&!e.points.find((e=>this.vecHelper.vectorsTheSame(e,r,t)))){const e=this.addEdgesAndWiresToWire({shape:h[h.length-1],shapes:[h[0]]});h[0]=e,h.pop()}}return h}createLines(e){const t=e.lines.map((e=>this.createLineWire(e))).filter((e=>void 0!==e));return this.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createWireFromTwoCirclesTan(e){const t=this.shapeGettersService.getEdges({shape:e.circle1}),r=this.shapeGettersService.getEdges({shape:e.circle2});if(1===t.length&&1===r.length){const i=t[0],n=r[0],s=this.edgesService.constraintTanLinesOnTwoCircles({circle1:i,circle2:n,positionResult:e.keepLines===U.twoSidesStrictEnum.outside?U.positionResultEnum.keepSide2:U.positionResultEnum.keepSide1,circleRemainders:this.enumService.convertFourSidesStrictEnumToTwoCircleInclusionEnum(e.circleRemainders),tolerance:e.tolerance}),o=this.converterService.combineEdgesAndWiresIntoAWire({shapes:s});return s.forEach((e=>e.delete())),i.delete(),n.delete(),o}throw new Error("Could not find the edges of the provided circle wires.")}createZigZagBetweenTwoWires(e){const t=e.wire1,r=e.wire2,i=this.edgesService.getEdgesAlongWire({shape:t}),n=this.edgesService.getEdgesAlongWire({shape:r}),s=i.map((t=>this.edgesService.divideEdgeByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))),o=n.map((t=>this.edgesService.divideEdgeByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))),a=s.map(((t,r)=>{const i=o[r],n=[];for(let r=0;re.delete())),t.delete(),i.delete(),n.Nullify(),n.delete(),o.Nullify(),o.delete(),a.delete(),c.delete(),h.delete(),l}createBezier(e){const t=new this.occ.TColgp_Array1OfPnt_2(1,e.points.length+(e.closed?1:0));for(let r=1;r<=e.points.length;r++)t.SetValue(r,this.entitiesService.gpPnt(e.points[r-1]));e.closed&&t.SetValue(e.points.length+1,t.Value(1));const r=new this.occ.Geom_BezierCurve_1(t),i=new this.occ.Handle_Geom_Curve_2(r),n=new this.occ.BRepBuilderAPI_MakeEdge_24(i),s=n.Edge(),o=new this.occ.BRepBuilderAPI_MakeWire_2(s),a=o.Wire();return o.delete(),n.delete(),s.delete(),i.delete(),t.delete(),a}addEdgesAndWiresToWire(e){const t=new this.occ.BRepBuilderAPI_MakeWire_1;let r;if(t.Add_2(e.shape),e.shapes.forEach((e=>{e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?t.Add_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE&&t.Add_2(e)})),!t.IsDone())throw new Error("Wire could not be constructed. Check if edges and wires do not have disconnected elements.");return r=t.Wire(),t.delete(),r}startPointOnWire(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1);return this.geomService.startPointOnCurve(Object.assign(Object.assign({},e),{shape:r}))}endPointOnWire(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1);return this.geomService.endPointOnCurve(Object.assign(Object.assign({},e),{shape:r}))}placeWire(e,t){const r=this.shapeGettersService.getEdges({shape:e}),i=[];r.forEach((e=>{const r={current:0},n={current:0};this.occRefReturns.BRep_Tool_Range_1(e,r,n);const s=this.occRefReturns.BRep_Tool_Curve_2(e,r,n);if(!s.IsNull()){const e=this.entitiesService.gpPln([0,0,0],[0,1,0]),o=this.occ.GeomAPI.To2d(s,e),a=o.get(),c=this.edgesService.makeEdgeFromGeom2dCurveAndSurfaceBounded({curve:a,surface:t},r.current,n.current);c&&i.push(c),e.delete(),o.delete()}s.delete()})),r.forEach((e=>e.delete()));const n=this.converterService.combineEdgesAndWiresIntoAWire({shapes:i});return i.forEach((e=>e.delete())),n}}class fe{constructor(e,t,r,i,n,s,o,a){this.occ=e,this.occRefReturns=t,this.entitiesService=r,this.enumService=i,this.shapeGettersService=n,this.converterService=s,this.booleansService=o,this.wiresService=a}createFaceFromWire(e){let t;if(this.enumService.getShapeTypeEnum(e.shape)!==U.shapeTypeEnum.wire)throw new Error("Provided input shape is not a wire");if(e.planar){const r=this.occ.TopoDS.Wire_1(e.shape);t=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(r,e.planar),r.delete()}else{const r=3,i=15,n=2,s=!1,o=1e-5,a=1e-4,c=.01,h=.1,l=8,u=9,d=new this.occ.BRepFill_Filling(r,i,n,s,o,a,c,h,l,u),p=this.shapeGettersService.getEdges(e);if(p.forEach((e=>{d.Add_1(e,this.occ.GeomAbs_Shape.GeomAbs_C0,!0)})),d.Build(),!d.IsDone())throw new Error("Could not create non planar face");t=d.Face(),d.delete(),p.forEach((e=>e.delete()))}return t}getFaceArea(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.SurfaceProperties_1(e.shape,t,!1,!1);const r=t.Mass();return t.delete(),r}getFacesAreas(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getFaceArea({shape:e})))}getFaceCenterOfMass(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.SurfaceProperties_1(e.shape,t,!1,!1);const r=t.CentreOfMass(),i=[r.X(),r.Y(),r.Z()];return t.delete(),r.delete(),i}getFacesCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getFaceCenterOfMass({shape:e})))}filterFacePoints(e){const t=[];if(e.points.length>0){const r=new this.occ.BRepClass_FaceClassifier_1;return e.points.forEach((i=>{const n=this.entitiesService.gpPnt(i);r.Perform_2(e.shape,n,e.tolerance,e.useBndBox,e.gapTolerance);const s=r.State(),o=this.enumService.getTopAbsStateEnum(s);e.keepOn&&o===U.topAbsStateEnum.on&&t.push(i),e.keepIn&&o===U.topAbsStateEnum.in&&t.push(i),e.keepOut&&o===U.topAbsStateEnum.out&&t.push(i),e.keepUnknown&&o===U.topAbsStateEnum.unknown&&t.push(i),n.delete()})),r.delete(),t}return[]}createSquareFace(e){const t=this.wiresService.createSquareWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!0);return t.delete(),r}createRectangleFace(e){const t=this.wiresService.createRectangleWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!0);return t.delete(),r}createFaceFromMultipleCircleTanWires(e){const t=e.circles,r=[];if(e.combination===U.combinationCirclesForFaceEnum.allWithAll)for(let i=0;ithis.createFaceFromWire({shape:t,planar:e.planar})))}faceFromSurface(e){const t=this.entitiesService.bRepBuilderAPIMakeFaceFromSurface(e.shape,e.tolerance);if(t.IsNull())throw t.delete(),new Error("Could not construct a face from the surface. Check if surface is not infinite.");return t}faceFromSurfaceAndWire(e){const t=this.entitiesService.bRepBuilderAPIMakeFaceFromSurfaceAndWire(e.surface,e.wire,e.inside);if(t.IsNull())throw t.delete(),new Error("Could not construct a face from the surface. Check if surface is not infinite.");return t}getUMinBound(e){const t=e.shape,{uMin:r}=this.getUVBounds(t);return r}getUMaxBound(e){const t=e.shape,{uMax:r}=this.getUVBounds(t);return r}getVMinBound(e){const t=e.shape,{vMin:r}=this.getUVBounds(t);return r}getVMaxBound(e){const t=e.shape,{vMax:r}=this.getUVBounds(t);return r}subdivideToPointsControlled(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),i=r.get(),{uMin:n,uMax:s,vMin:o,vMax:a}=this.getUVBounds(t),c=[];for(let t=0;t{const t=i+(n-i)*e[0],a=s+(o-s)*e[1],c=this.entitiesService.gpPnt([0,0,0]);r.D0(t,a,c);const h=[c.X(),c.Y(),c.Z()];return c.delete(),h}));return r.delete(),a}normalsOnUVs(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),{uMin:i,uMax:n,vMin:s,vMax:o}=this.getUVBounds(t),a=e.paramsUV.map((e=>{const t=i+(n-i)*e[0],a=s+(o-s)*e[1],c=this.entitiesService.gpDir([0,1,0]);this.occ.GeomLib.NormEstim(r,this.entitiesService.gpPnt2d([t,a]),1e-7,c);const h=[c.X(),c.Y(),c.Z()];return c.delete(),h}));return r.delete(),a}pointOnUV(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),i=r.get(),{uMin:n,uMax:s,vMin:o,vMax:a}=this.getUVBounds(t),c=n+(s-n)*e.paramU,h=o+(a-o)*e.paramV,l=this.entitiesService.gpPnt([0,0,0]);i.D0(c,h,l);const u=[l.X(),l.Y(),l.Z()];return l.delete(),r.delete(),u}normalOnUV(e){return this.faceNormalOnUV(e)}createPolygonFace(e){const t=this.wiresService.createPolygonWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!1);return t.delete(),r}}class ge{constructor(e,t){this.occ=e,this.shapeGettersService=t}getVerticesAsPoints(e){const t=this.shapeGettersService.getVertices(e);return this.verticesToPoints({shapes:t})}verticesToPoints(e){return e.shapes.map((e=>{const t=this.occ.BRep_Tool.Pnt(e),r=[t.X(),t.Y(),t.Z()];return t.delete(),r}))}}class ve{constructor(e,t,r,i){this.occ=e,this.shapeGettersService=t,this.converterService=r,this.facesService=i}getShellSurfaceArea(e){const t=this.shapeGettersService.getFaces(e);return this.facesService.getFacesAreas({shapes:t}).reduce(((e,t)=>e+t),0)}sewFaces(e){const t=new this.occ.BRepBuilderAPI_Sewing(e.tolerance,!0,!0,!0,!1);e.shapes.forEach((e=>{t.Add(e)}));const r=new this.occ.Message_ProgressRange_1;t.Perform(r);const i=t.SewedShape(),n=this.converterService.getActualTypeOfShape(i);return t.delete(),r.delete(),i.delete(),n}}class me{constructor(e,t,r,i,n,s,o,a,c){this.occ=e,this.vecHelper=t,this.iteratorService=r,this.converterService=i,this.entitiesService=n,this.transformsService=s,this.shapeGettersService=o,this.edgesService=a,this.operationsService=c}filletEdges(e){if(!e.indexes||e.indexes.length&&0===e.indexes.length){if(void 0===e.radius)throw Error("Radius not defined");const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational),r=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE),i=[];for(;r.More();){const n=this.occ.TopoDS.Edge_1(r.Current());i.push(n),t.Add_2(e.radius,n),r.Next()}const n=t.Shape();return t.delete(),r.delete(),i.forEach((e=>e.delete())),n}if(e.indexes&&e.indexes.length>0){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);let r,i=0,n=0;const s=e.indexes;if(this.iteratorService.forEachEdge(e.shape,((r,o)=>{if(s.includes(r)){let r=e.radius;if(e.radiusList&&(r=e.radiusList[n],n++),void 0===r)throw Error("Radius not defined, or radiusList not correct length");t.Add_2(r,o),i++}})),0===i)throw new Error("Fillet Edges Not Found! Make sure you are looking at the object _before_ the Fillet is applied!");r=t.Shape(),t.delete();const o=this.converterService.getActualTypeOfShape(r);return r.delete(),o}}filletEdgesListOneRadius(e){if(e.edges&&e.edges.length>0){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach((r=>{t.Add_2(e.radius,r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesList(e){if(e.edges&&e.edges.length>0&&e.radiusList&&e.radiusList.length>0&&e.edges.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach(((r,i)=>{t.Add_2(e.radiusList[i],r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgeVariableRadius(e){if(e.paramsU&&e.paramsU.length>0&&e.radiusList&&e.radiusList.length>0&&e.paramsU.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);this.assignVariableFilletToEdge(e,t);const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesSameVariableRadius(e){if(e.edges&&e.edges.length>0&&e.radiusList&&e.radiusList.length>0&&e.paramsU.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach((r=>{this.assignVariableFilletToEdge({edge:r,paramsU:e.paramsU,radiusList:e.radiusList,shape:e.shape},t)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesVariableRadius(e){if(e.edges&&e.edges.length>0&&e.radiusLists&&e.radiusLists.length>0&&e.paramsULists.length===e.radiusLists.length&&e.paramsULists.length===e.edges.length&&e.radiusLists.length===e.edges.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach(((r,i)=>{this.assignVariableFilletToEdge({edge:r,paramsU:e.paramsULists[i],radiusList:e.radiusLists[i],shape:e.shape},t)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}assignVariableFilletToEdge(e,t){const r=new this.occ.TColgp_Array1OfPnt2d_2(1,e.paramsU.length);e.paramsU.forEach(((t,i)=>{r.SetValue(i+1,this.entitiesService.gpPnt2d([t,e.radiusList[i]]))})),t.Add_5(r,e.edge)}chamferEdges(e){if(!e.indexes||e.indexes.length&&0===e.indexes.length){if(void 0===e.distance)throw Error("Distance is undefined");const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE),i=[];for(;r.More();){const n=this.occ.TopoDS.Edge_1(r.Current());i.push(n),t.Add_2(e.distance,n),r.Next()}const n=t.Shape();return t.delete(),r.delete(),i.forEach((e=>e.delete())),n}if(e.indexes&&e.indexes.length>0){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);let r,i=0,n=0;const s=e.indexes;this.iteratorService.forEachEdge(e.shape,((r,o)=>{if(s.includes(r)){let r=e.distance;if(e.distanceList&&(r=e.distanceList[n],n++),void 0===r)throw Error("Distance not defined and/or distance list incorrect length");t.Add_2(r,o),i++}})),0===i?(console.error("Chamfer Edges Not Found! Make sure you are looking at the object _before_ the Fillet is applied!"),r=e.shape):r=t.Shape(),t.delete();const o=this.converterService.getActualTypeOfShape(r);return r.delete(),o}}chamferEdgesList(e){if(e.edges&&e.edges.length>0&&e.distanceList&&e.distanceList.length>0&&e.edges.length===e.distanceList.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{const n=e.distanceList[i];if(void 0===n)throw Error("Distance is not defined");t.Add_2(n,r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgeTwoDistances(e){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);t.Add_3(e.distance1,e.distance2,e.edge,e.face);const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}chamferEdgesTwoDistances(e){if(e.edges&&e.edges.length>0&&e.edges.length===e.faces.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{t.Add_3(e.distance1,e.distance2,r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgesTwoDistancesLists(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.distances1&&e.distances1.length>0&&e.distances2&&e.distances2.length>0&&e.edges.length===e.faces.length&&e.edges.length===e.distances1.length&&e.edges.length===e.distances2.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{t.Add_3(e.distances1[i],e.distances2[i],r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgeDistAngle(e){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=this.vecHelper.degToRad(e.angle);t.AddDA(e.distance,r,e.edge,e.face);const i=t.Shape();t.delete();const n=this.converterService.getActualTypeOfShape(i);return i.delete(),n}chamferEdgesDistsAngles(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.distances&&e.distances.length>0&&e.angles&&e.angles.length>0&&e.edges.length===e.distances.length&&e.edges.length===e.faces.length&&e.edges.length===e.angles.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{const n=this.vecHelper.degToRad(e.angles[i]);t.AddDA(e.distances[i],n,r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgesDistAngle(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.edges.length===e.faces.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=this.vecHelper.degToRad(e.angle);e.edges.forEach(((i,n)=>{t.AddDA(e.distance,r,i,e.faces[n])}));const i=t.Shape();t.delete();const n=this.converterService.getActualTypeOfShape(i);return i.delete(),n}}fillet3DWire(e){let t=!1;if(e.radiusList&&e.radiusList.length>0&&e.indexes&&e.indexes.length>0){if(e.radiusList.length!==e.indexes.length)throw new Error("Radius list and indexes are not the same length");t=!0}let r=this.edgesService.fixEdgeOrientationsAlongWire({shape:e.shape});if(t&&e.shape.Closed_1()){const t=this.edgesService.getEdgesAlongWire({shape:e.shape}),i=t.shift(),n=[...t,i];r=this.converterService.combineEdgesAndWiresIntoAWire({shapes:n})}else r=this.converterService.getActualTypeOfShape(e.shape.Reversed());const i=this.operationsService.extrude({shape:r,direction:e.direction});let n=e.indexes;if(t){const t=e.indexes.filter((e=>e>2)),r=Math.max(...t),i=[5];let s=5;for(let e=0;ee.shape.Closed_1()?t<=2?t:i[t-3]:1===t?2:i[t-2]))}const s=this.filletEdges({shape:i,radius:e.radius,indexes:n,radiusList:e.radiusList}),o=[],a=this.shapeGettersService.getFaces({shape:s});a.forEach(((e,t)=>{const r=this.shapeGettersService.getEdges({shape:e})[3];o.push(r)}));const c=this.converterService.combineEdgesAndWiresIntoAWire({shapes:o}),h=this.transformsService.translate({shape:c,translation:e.direction.map((e=>-e))});return i.delete(),s.delete(),a.forEach((e=>e.delete())),o.forEach((e=>e.delete())),h}}class ye{constructor(e,t,r,i,n,s,o){this.occ=e,this.shapeGettersService=t,this.facesService=r,this.enumService=i,this.entitiesService=n,this.converterService=s,this.transformsService=o}fromClosedShell(e){const t=this.converterService.getActualTypeOfShape(e.shape),r=new this.occ.BRepBuilderAPI_MakeSolid_3(t),i=r.Solid();return r.delete(),t.delete(),i}createBox(e){return this.entitiesService.bRepPrimAPIMakeBox(e.width,e.length,e.height,e.center)}createCube(e){return this.entitiesService.bRepPrimAPIMakeBox(e.size,e.size,e.size,e.center)}createBoxFromCorner(e){const t=this.entitiesService.bRepPrimAPIMakeBox(e.width,e.length,e.height,e.corner),r=this.transformsService.translate({shape:t,translation:[e.width/2,e.height/2,e.length/2]});return t.delete(),r}createCylinder(e){return this.entitiesService.bRepPrimAPIMakeCylinder(e.center,e.direction?e.direction:[0,1,0],e.radius,e.height)}createCylindersOnLines(e){return e.lines.map((t=>this.entitiesService.bRepPrimAPIMakeCylinderBetweenPoints(t.start,t.end,e.radius)))}createSphere(e){return this.entitiesService.bRepPrimAPIMakeSphere(e.center,[0,0,1],e.radius)}createCone(e){const t=this.entitiesService.gpAx2(e.center,e.direction),r=new this.occ.BRepPrimAPI_MakeCone_4(t,e.radius1,e.radius2,e.height,e.angle),i=r.Shape();return r.delete(),t.delete(),i}filterSolidPoints(e){const t=[];if(e.points.length>0){const r=new this.occ.BRepClass3d_SolidClassifier_1;return r.Load(e.shape),e.points.forEach((i=>{const n=this.entitiesService.gpPnt(i);r.Perform(n,e.tolerance);const s=r.State(),o=this.enumService.getTopAbsStateEnum(s);e.keepOn&&o===U.topAbsStateEnum.on&&t.push(i),e.keepIn&&o===U.topAbsStateEnum.in&&t.push(i),e.keepOut&&o===U.topAbsStateEnum.out&&t.push(i),e.keepUnknown&&o===U.topAbsStateEnum.unknown&&t.push(i),n.delete()})),r.delete(),t}return[]}getSolidVolume(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.VolumeProperties_1(e.shape,t,!0,!1,!1);const r=t.Mass();return t.delete(),r}getSolidSurfaceArea(e){const t=this.shapeGettersService.getFaces(e);return this.facesService.getFacesAreas({shapes:t}).reduce(((e,t)=>e+t),0)}getSolidsVolumes(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getSolidVolume({shape:e})))}getSolidCenterOfMass(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.VolumeProperties_1(e.shape,t,!0,!1,!1);const r=t.CentreOfMass(),i=[r.X(),r.Y(),r.Z()];return t.delete(),r.delete(),i}getSolidsCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getSolidCenterOfMass({shape:e})))}getSolids(e){return this.shapeGettersService.getSolids(e)}}class Se{constructor(e,t,r){this.vecHelper=e,this.shapesHelperService=t,this.occ=r,this.occRefReturns=new re(r),this.iteratorService=new ie(r),this.enumService=new ne(r),this.converterService=new se(r),this.entitiesService=new oe(r),this.shapeGettersService=new le(r,this.enumService,this.iteratorService),this.geomService=new de(r,this.vecHelper,this.entitiesService),this.booleansService=new he(r,this.shapeGettersService),this.transformsService=new ce(r,this.converterService,this.entitiesService,this.vecHelper),this.verticesService=new ge(r,this.shapeGettersService),this.edgesService=new ue(r,this.occRefReturns,this.shapeGettersService,this.entitiesService,this.iteratorService,this.converterService,this.enumService,this.geomService,this.transformsService,this.vecHelper),this.wiresService=new pe(r,this.occRefReturns,this.vecHelper,this.shapesHelperService,this.shapeGettersService,this.transformsService,this.enumService,this.entitiesService,this.converterService,this.geomService,this.edgesService,this.booleansService),this.facesService=new fe(r,this.occRefReturns,this.entitiesService,this.enumService,this.shapeGettersService,this.converterService,this.booleansService,this.wiresService),this.shellsService=new ve(r,this.shapeGettersService,this.converterService,this.facesService),this.solidsService=new ye(r,this.shapeGettersService,this.facesService,this.enumService,this.entitiesService,this.converterService,this.transformsService),this.operationsService=new ae(r,this.enumService,this.entitiesService,this.converterService,this.booleansService,this.shapeGettersService,this.edgesService,this.transformsService,this.vecHelper,this.wiresService,this.facesService,this.shellsService),this.filletsService=new me(r,this.vecHelper,this.iteratorService,this.converterService,this.entitiesService,this.transformsService,this.shapeGettersService,this.edgesService,this.operationsService)}surfaceFromFace(e){const t=e.shape;return this.occ.BRep_Tool.Surface_2(t).get()}}class be{constructor(e,t){this.occ=e,this.och=t}union(e){return this.och.booleansService.union(e)}difference(e){return this.och.booleansService.difference(e)}intersection(e){const t=this.och.booleansService.intersection(e);return this.och.converterService.makeCompound({shapes:t})}}class we{constructor(e,t){this.occ=e,this.och=t}saveShapeSTEP(e){const t=e.shape;let r;if(e.adjustYtoZ){const t=this.och.transformsService.rotate({shape:e.shape,axis:[1,0,0],angle:-90});r=this.och.transformsService.mirrorAlongNormal({shape:t,origin:[0,0,0],normal:[0,0,1]}),t.delete()}const i=new this.occ.STEPControl_Writer_1;let n;n=r||t;const s=new this.occ.Message_ProgressRange_1;let o,a;try{o=i.Transfer(n,this.occ.STEPControl_StepModelType.STEPControl_AsIs,!0,s)}catch(e){throw new Error("Failed when calling writer.Transfer.")}if(o!==this.occ.IFSelect_ReturnStatus.IFSelect_RetDone)throw new Error("Failed when transfering to step writer.");if(i.Write("x")!==this.occ.IFSelect_ReturnStatus.IFSelect_RetDone)throw new Error("Failed when writing step file.");{const e=this.occ.FS.readFile("/x",{encoding:"utf8"});this.occ.FS.unlink("/x"),a=e}return r&&r.delete(),s.delete(),a}loadSTEPorIGES(e){const t=e.fileName,r=e.filetext,i=(()=>{switch(t.toLowerCase().split(".").pop()){case"step":case"stp":return"step";case"iges":case"igs":return"iges";default:return}})();let n;if(this.occ.FS.createDataFile("/",`file.${i}`,r,!0,!0,!0),"step"===i)n=new this.occ.STEPControl_Reader_1;else{if("iges"!==i)return void console.error("opencascade can't parse this extension! (yet)");n=new this.occ.IGESControl_Reader_1}if(n.ReadFile(`file.${i}`)===this.occ.IFSelect_ReturnStatus.IFSelect_RetDone){const t=new this.occ.Message_ProgressRange_1;n.TransferRoots(t),t.delete();let r,s=n.OneShape();if(e.adjustZtoY){const e=this.och.transformsService.mirrorAlongNormal({shape:s,origin:[0,0,0],normal:[0,0,1]});r=this.och.transformsService.rotate({shape:e,axis:[1,0,0],angle:90}),e.delete()}return this.occ.FS.unlink(`/file.${i}`),r&&(s.delete(),s=r),s}console.error("Something in OCCT went wrong trying to read "+t)}}class Ee{constructor(e,t){this.occ=e,this.och=t}closestPointsBetweenTwoShapes(e){return this.och.operationsService.closestPointsBetweenTwoShapes(e.shape1,e.shape2)}closestPointsOnShapeFromPoints(e){return this.och.operationsService.closestPointsOnShapeFromPoints(e)}closestPointsOnShapesFromPoints(e){return this.och.operationsService.closestPointsOnShapesFromPoints(e)}distancesToShapeFromPoints(e){return this.och.operationsService.distancesToShapeFromPoints(e)}loft(e){return this.och.operationsService.loft(e)}loftAdvanced(e){return this.och.operationsService.loftAdvanced(e)}offset(e){return this.och.operationsService.offset(e)}offsetAdv(e){return this.och.operationsService.offsetAdv(e)}offset3DWire(e){return this.och.operationsService.offset3DWire(e)}extrudeShapes(e){return this.och.operationsService.extrudeShapes(e)}extrude(e){return this.och.operationsService.extrude(e)}splitShapeWithShapes(e){return this.och.operationsService.splitShapeWithShapes(e)}revolve(e){return this.och.operationsService.revolve(e)}rotatedExtrude(e){return this.och.operationsService.rotatedExtrude(e)}pipe(e){return this.och.operationsService.pipe(e)}pipePolylineWireNGon(e){return this.och.operationsService.pipePolylineWireNGon(e)}pipeWireCylindrical(e){return this.och.operationsService.pipeWireCylindrical(e)}pipeWiresCylindrical(e){return this.och.operationsService.pipeWiresCylindrical(e)}makeThickSolidSimple(e){return this.och.operationsService.makeThickSolidSimple(e)}makeThickSolidByJoin(e){return this.och.operationsService.makeThickSolidByJoin(e)}slice(e){return this.och.operationsService.slice(e)}sliceInStepPattern(e){return this.och.operationsService.sliceInStepPattern(e)}}class Te{constructor(e,t){this.occ=e,this.och=t}transform(e){const t=this.scale({shape:e.shape,factor:e.scaleFactor}),r=this.rotate({shape:t,axis:e.rotationAxis,angle:e.rotationAngle}),i=this.translate({shape:r,translation:e.translation});return t.delete(),r.delete(),i}rotate(e){return this.och.transformsService.rotate(e)}rotateAroundCenter(e){const t=this.translate({shape:e.shape,translation:e.center.map((e=>-e))}),r=e.angle,i=this.rotate({shape:t,axis:e.axis,angle:r}),n=this.translate({shape:i,translation:e.center});return i.delete(),t.delete(),n}align(e){return this.och.transformsService.align(e)}alignAndTranslate(e){return this.och.transformsService.alignAndTranslate(e)}translate(e){return this.och.transformsService.translate(e)}scale(e){const t=new this.occ.gp_Trsf_1,r=this.och.entitiesService.gpPnt([0,0,0]);t.SetScale(r,e.factor);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.och.converterService.getActualTypeOfShape(n);return r.delete(),t.delete(),i.delete(),n.delete(),s}scale3d(e){const t=this.translate({shape:e.shape,translation:e.center.map((e=>-e))}),r=new this.occ.gp_GTrsf_1,i=e.scale,n=new this.occ.gp_Mat_2(i[0],0,0,0,i[1],0,0,0,i[2]);let s;r.SetVectorialPart(n);try{const i=new this.occ.BRepBuilderAPI_GTransform_2(t,r,!1),n=new this.occ.Message_ProgressRange_1;i.Build(n);const o=i.Shape();s=this.translate({shape:o,translation:e.center}),i.delete(),o.delete(),n.delete()}catch(e){throw new Error("Could not scale the shape")}return t.delete(),r.delete(),n.delete(),s}mirror(e){return this.och.transformsService.mirror(e)}mirrorAlongNormal(e){return this.och.transformsService.mirrorAlongNormal(e)}transformShapes(e){return this.checkIfListsEqualLength([e.shapes,e.translations,e.rotationAxes,e.rotationAngles,e.scaleFactors]),e.shapes.map(((t,r)=>this.transform({shape:t,translation:e.translations[r],rotationAxis:e.rotationAxes[r],rotationAngle:e.rotationAngles[r],scaleFactor:e.scaleFactors[r]})))}rotateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.axes,e.angles]),e.shapes.map(((t,r)=>this.rotate({shape:t,axis:e.axes[r],angle:e.angles[r]})))}rotateAroundCenterShapes(e){return this.checkIfListsEqualLength([e.shapes,e.axes,e.angles]),e.shapes.map(((t,r)=>this.rotateAroundCenter({shape:t,axis:e.axes[r],angle:e.angles[r],center:e.centers[r]})))}alignShapes(e){return this.checkIfListsEqualLength([e.shapes,e.fromOrigins,e.fromDirections,e.toOrigins,e.toDirections]),e.shapes.map(((t,r)=>this.align({shape:t,fromOrigin:e.fromOrigins[r],fromDirection:e.fromDirections[r],toOrigin:e.toOrigins[r],toDirection:e.toDirections[r]})))}alignAndTranslateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.centers,e.directions]),e.shapes.map(((t,r)=>this.alignAndTranslate({shape:t,center:e.centers[r],direction:e.directions[r]})))}translateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.translations]),e.shapes.map(((t,r)=>this.translate({shape:t,translation:e.translations[r]})))}scaleShapes(e){return this.checkIfListsEqualLength([e.shapes,e.factors]),e.shapes.map(((t,r)=>this.scale({shape:t,factor:e.factors[r]})))}scale3dShapes(e){return this.checkIfListsEqualLength([e.shapes,e.scales,e.centers]),e.shapes.map(((t,r)=>this.scale3d({shape:t,scale:e.scales[r],center:e.centers[r]})))}mirrorShapes(e){return this.checkIfListsEqualLength([e.shapes,e.directions,e.origins]),e.shapes.map(((t,r)=>this.mirror({shape:t,origin:e.origins[r],direction:e.directions[r]})))}mirrorAlongNormalShapes(e){return this.checkIfListsEqualLength([e.shapes,e.normals,e.origins]),e.shapes.map(((t,r)=>this.mirrorAlongNormal({shape:t,normal:e.normals[r],origin:e.origins[r]})))}checkIfListsEqualLength(e){const t=e[0].length;if(e.some((e=>e.length!==t)))throw new Error("Some of the list lengths are not the same. For this operation to work all lists need to be of equal length")}}class xe{constructor(e,t){this.occ=e,this.och=t}filletEdges(e){return this.och.filletsService.filletEdges(e)}filletEdgesList(e){return this.och.filletsService.filletEdgesList(e)}filletEdgesListOneRadius(e){return this.och.filletsService.filletEdgesListOneRadius(e)}filletEdgeVariableRadius(e){return this.och.filletsService.filletEdgeVariableRadius(e)}filletEdgesVariableRadius(e){return this.och.filletsService.filletEdgesVariableRadius(e)}filletEdgesSameVariableRadius(e){return this.och.filletsService.filletEdgesSameVariableRadius(e)}chamferEdges(e){return this.och.filletsService.chamferEdges(e)}chamferEdgesList(e){return this.och.filletsService.chamferEdgesList(e)}chamferEdgeDistAngle(e){return this.och.filletsService.chamferEdgeDistAngle(e)}chamferEdgesDistAngle(e){return this.och.filletsService.chamferEdgesDistAngle(e)}chamferEdgesDistsAngles(e){return this.och.filletsService.chamferEdgesDistsAngles(e)}chamferEdgeTwoDistances(e){return this.och.filletsService.chamferEdgeTwoDistances(e)}chamferEdgesTwoDistances(e){return this.och.filletsService.chamferEdgesTwoDistances(e)}chamferEdgesTwoDistancesLists(e){return this.och.filletsService.chamferEdgesTwoDistancesLists(e)}filletTwoEdgesInPlaneIntoAWire(e){const t=this.och.entitiesService.gpPln(e.planeOrigin,e.planeDirection),r=new this.occ.ChFi2d_FilletAlgo_3(e.edge1,e.edge2,t);r.Perform(e.radius);const i=this.och.entitiesService.gpPnt(e.planeOrigin),n=new this.occ.TopoDS_Edge,s=new this.occ.TopoDS_Edge;let o=-1;void 0!==e.solution&&(o=e.solution);const a=r.Result(i,n,s,o),c=this.och.converterService.combineEdgesAndWiresIntoAWire({shapes:[n,a,s]});return r.delete(),i.delete(),t.delete(),n.delete(),s.delete(),a.delete(),c}fillet3DWire(e){return this.och.filletsService.fillet3DWire(e)}fillet2d(e){if(e.indexes&&e.radiusList&&e.radiusList.length!==e.indexes.length)throw new Error("When using radius list, length of the list must match index list of corners that you want to fillet.");let t,r=!1;if(e.shape.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE)t=this.och.converterService.getActualTypeOfShape(e.shape),r=!0;else{if(e.shape.ShapeType()!==this.occ.TopAbs_ShapeEnum.TopAbs_WIRE)throw new Error("You can only fillet a 2d wire or a 2d face.");{const r=new this.occ.BRepBuilderAPI_MakeFace_15(e.shape,!0),i=new this.occ.Message_ProgressRange_1;r.Build(i);const n=r.Shape();t=this.och.converterService.getActualTypeOfShape(n),n.delete(),i.delete(),r.delete()}}const i=new this.occ.BRepFilletAPI_MakeFillet2d_2(t),n=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);let s=1;const o=[];for(;n.More();n.Next()){const e=this.occ.TopoDS.Vertex_1(n.Current());s%2==0&&o.push(e),s++}r||e.shape.Closed_1()||o.pop();let a=0;o.forEach(((t,r)=>{e.indexes?e.indexes.includes(r+1)&&(this.applyRadiusToVertex(e,i,t,a),a++):this.applyRadiusToVertex(e,i,t,r)}));const c=new this.occ.Message_ProgressRange_1;let h;if(i.Build(c),r)h=i.Shape();else if(i.IsDone()){const e=i.Shape(),t=this.och.shapeGettersService.getWires({shape:e});1===t.length&&(h=t[0])}else{const r=this.och.facesService.faceNormalOnUV({shape:t,paramU:.5,paramV:.5});h=this.fillet3DWire({shape:e.shape,radius:e.radius,radiusList:e.radiusList,indexes:e.indexes,direction:r})}return n.delete(),i.delete(),c.delete(),o.forEach((e=>e.delete())),h}applyRadiusToVertex(e,t,r,i){if(e.radiusList){const n=e.radiusList;t.AddFillet(r,n[i])}else e.radius&&t.AddFillet(r,e.radius)}}class ke{constructor(e,t){this.occ=e,this.och=t}fixEdgeOrientationsAlongWire(e){return this.och.edgesService.fixEdgeOrientationsAlongWire(e)}basicShapeRepair(e){const t=new this.occ.ShapeFix_Shape_1;t.Init(e.shape),t.SetPrecision(e.precision),t.SetMaxTolerance(e.maxTolerance),t.SetMinTolerance(e.minTolerance);const r=new this.occ.Message_ProgressRange_1;t.Perform(r),r.delete();const i=t.Shape();return t.delete(),i}fixSmallEdgeOnWire(e){const t=new this.occ.ShapeFix_Wire_1;return t.Load_1(e.shape),t.FixSmall_1(e.lockvtx,e.precsmall),t.Perform(),t.Wire()}}class Ce{constructor(e,t){this.occ=e,this.och=t,this.shapes=new te(e,t),this.geom=new q(e,t),this.transforms=new Te(e,t),this.operations=new Ee(e,t),this.booleans=new be(e,t),this.fillets=new xe(e,t),this.shapeFix=new ke(e,t),this.io=new we(e,t)}shapesToMeshes(e){return e.shapes.map((t=>this.shapeToMesh({shape:t,precision:e.precision,adjustYtoZ:e.adjustYtoZ})))}shapeToMesh(e){const t=[],r=[],i=[];let n=e.shape;if(n.IsNull())return{faceList:t,edgeList:r,pointsList:[]};if(this.occ.BRepTools.Clean(n,!0),e.adjustYtoZ){const t=this.och.transformsService.rotate({shape:e.shape,axis:[1,0,0],angle:-90}),r=this.och.transformsService.mirrorAlongNormal({shape:t,origin:[0,0,0],normal:[0,0,1]});t.delete(),n.delete(),n=r}const s=[],o=this.och.shapeGettersService.getFaces({shape:n});let a;o&&o.length&&(a=new this.occ.BRepMesh_IncrementalMesh_2(n,e.precision,!1,.5,!1),o.forEach(((e,r)=>{const i=new this.occ.TopLoc_Location_1,n=this.occ.BRep_Tool.Triangulation(e,i,0);if(n.IsNull())return void console.error("Encountered Null Face!");const o={vertex_coord:[],normal_coord:[],uvs:[],tri_indexes:[],vertex_coord_vec:[],number_of_triangles:0,face_index:r},a=new this.occ.Poly_Connect_2(n),c=n.get();o.vertex_coord=new Array(3*c.NbNodes()),o.vertex_coord_vec=[];for(let e=0;e{const n={vertex_coord:[],edge_index:-1},s=new this.occ.TopLoc_Location_1,o=new this.occ.BRepAdaptor_Curve_2(t),a=new this.occ.GCPnts_TangentialDeflection_2(o,e.precision,.1,2,1e-9,1e-7);n.vertex_coord=[];const c=a.NbPoints(),h=[];for(let e=0;ee.delete())),s.delete(),o.delete(),a.delete(),this.occ.BRepTools.Clean(t,!0)}));const c=this.och.shapeGettersService.getVertices({shape:n});return c.length>0&&c.forEach((e=>{const t=this.occ.BRep_Tool.Pnt(e);i.push([t.X(),t.Y(),t.Z()]),t.delete()})),a&&a.Delete(),this.occ.BRepTools.Clean(n,!0),{faceList:t,edgeList:r,pointsList:i}}}var Pe,Ae=(Pe=(Pe="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,i;(e=void 0!==(e=e||{})?e:{}).ready=new Promise((function(e,r){t=e,i=r}));var n,s,o,a,c,h,l=Object.assign({},e),u=[],d="./this.program",p=(e,t)=>{throw t},f="object"==typeof window,g="function"==typeof importScripts,v="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";v?(m=g?r(699).dirname(m)+"/":"//",h=()=>{c||(a=r(439),c=r(699))},n=function(e,t){return h(),e=c.normalize(e),a.readFileSync(e,t?void 0:"utf8")},o=e=>{var t=n(e,!0);return t.buffer||(t=new Uint8Array(t)),t},s=(e,t,r)=>{h(),e=c.normalize(e),a.readFile(e,(function(e,i){e?r(e):t(i.buffer)}))},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof yr))throw e})),process.on("unhandledRejection",(function(e){throw e})),p=(e,t)=>{if(te())throw process.exitCode=e,t;var r;(r=t)instanceof yr||S("exiting due to exception: "+r),process.exit(e)},e.inspect=function(){return"[Emscripten Module object]"}):(f||g)&&(g?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),Pe&&(m=Pe),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",n=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),s=(e,t,r)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)});var y=e.print||console.log.bind(console),S=e.printErr||console.warn.bind(console);Object.assign(e,l),l=null,e.arguments&&(u=e.arguments),e.thisProgram&&(d=e.thisProgram),e.quit&&(p=e.quit);var b;function w(e){w.shown||(w.shown={}),w.shown[e]||(w.shown[e]=1,S(e))}e.wasmBinary&&(b=e.wasmBinary);var E,T=e.noExitRuntime||!0;"object"!=typeof WebAssembly&&ae("no native wasm support detected");var x,k=!1;function C(e,t){e||ae(t)}var P="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function A(e,t,r){for(var i=(t>>>=0)+r,n=t;e[n]&&!(n>=i);)++n;if(n-t>16&&e.buffer&&P)return P.decode(e.subarray(t,n));for(var s="";t>10,56320|1023&h)}}else s+=String.fromCharCode((31&o)<<6|a)}else s+=String.fromCharCode(o)}return s}function _(e,t){return(e>>>=0)?A(B,e,t):""}function O(e,t,r,i){if(!(i>0))return 0;for(var n=r>>>=0,s=r+i-1,o=0;o=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++o)),a<=127){if(r>=s)break;t[r++>>>0]=a}else if(a<=2047){if(r+1>=s)break;t[r++>>>0]=192|a>>6,t[r++>>>0]=128|63&a}else if(a<=65535){if(r+2>=s)break;t[r++>>>0]=224|a>>12,t[r++>>>0]=128|a>>6&63,t[r++>>>0]=128|63&a}else{if(r+3>=s)break;t[r++>>>0]=240|a>>18,t[r++>>>0]=128|a>>12&63,t[r++>>>0]=128|a>>6&63,t[r++>>>0]=128|63&a}}return t[r>>>0]=0,r-n}function D(e,t,r){return O(e,B,t,r)}function R(e){for(var t=0,r=0;r=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++r)),i<=127?++t:t+=i<=2047?2:i<=65535?3:4}return t}var F,L,B,M,I,U,W,N,G,H="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0;function V(e,t){for(var r=e,i=r>>1,n=i+t/2;!(i>=n)&&I[i>>>0];)++i;if((r=i<<1)-e>32&&H)return H.decode(B.subarray(e>>>0,r>>>0));for(var s="",o=0;!(o>=t/2);++o){var a=M[e+2*o>>>1];if(0==a)break;s+=String.fromCharCode(a)}return s}function z(e,t,r){if(void 0===r&&(r=2147483647),r<2)return 0;for(var i=t,n=(r-=2)<2*e.length?r/2:e.length,s=0;s>>1]=o,t+=2}return M[t>>>1]=0,t-i}function j(e){return 2*e.length}function q(e,t){for(var r=0,i="";!(r>=t/4);){var n=U[e+4*r>>>2];if(0==n)break;if(++r,n>=65536){var s=n-65536;i+=String.fromCharCode(55296|s>>10,56320|1023&s)}else i+=String.fromCharCode(n)}return i}function $(e,t,r){if(void 0===r&&(r=2147483647),r<4)return 0;for(var i=t>>>=0,n=i+r-4,s=0;s=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),U[t>>>2]=o,(t+=4)+4>n)break}return U[t>>>2]=0,t-i}function Y(e){for(var t=0,r=0;r=55296&&i<=57343&&++r,t+=4}return t}function X(e){var t=R(e)+1,r=ur(t);return r&&O(e,L,r,t),r}function Z(t){F=t,e.HEAP8=L=new Int8Array(t),e.HEAP16=M=new Int16Array(t),e.HEAP32=U=new Int32Array(t),e.HEAPU8=B=new Uint8Array(t),e.HEAPU16=I=new Uint16Array(t),e.HEAPU32=W=new Uint32Array(t),e.HEAPF32=N=new Float32Array(t),e.HEAPF64=G=new Float64Array(t)}e.INITIAL_MEMORY;var J,Q=[],K=[],ee=[];function te(){return T}var re=0,ie=null,ne=null;function se(t){re++,e.monitorRunDependencies&&e.monitorRunDependencies(re)}function oe(t){if(re--,e.monitorRunDependencies&&e.monitorRunDependencies(re),0==re&&(null!==ie&&(clearInterval(ie),ie=null),ne)){var r=ne;ne=null,r()}}function ae(t){e.onAbort&&e.onAbort(t),S(t="Aborted("+t+")"),k=!0,x=1,t+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(t);throw i(r),r}var ce,he,le,ue;function de(e){return e.startsWith("data:application/octet-stream;base64,")}function pe(e){return e.startsWith("file://")}function fe(e){try{if(e==ce&&b)return new Uint8Array(b);if(o)return o(e);throw"both async and sync fetching of the wasm failed"}catch(e){ae(e)}}function ge(t){for(;t.length>0;){var r=t.shift();if("function"!=typeof r){var i=r.func;"number"==typeof i?void 0===r.arg?me(i)():me(i)(r.arg):i(void 0===r.arg?null:r.arg)}else r(e)}}de(ce="bitbybit-dev-occt.wasm")||(he=ce,ce=e.locateFile?e.locateFile(he,m):m+he);var ve=[];function me(e){var t=ve[e];return t||(e>=ve.length&&(ve.length=e+1),ve[e]=t=J.get(e)),t}function ye(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){W[this.ptr+4>>>2]=e},this.get_type=function(){return W[this.ptr+4>>>2]},this.set_destructor=function(e){W[this.ptr+8>>>2]=e},this.get_destructor=function(){return W[this.ptr+8>>>2]},this.set_refcount=function(e){U[this.ptr>>>2]=e},this.set_caught=function(e){e=e?1:0,L[this.ptr+12>>>0]=e},this.get_caught=function(){return 0!=L[this.ptr+12>>>0]},this.set_rethrown=function(e){e=e?1:0,L[this.ptr+13>>>0]=e},this.get_rethrown=function(){return 0!=L[this.ptr+13>>>0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var e=U[this.ptr>>>2];U[this.ptr>>>2]=e+1},this.release_ref=function(){var e=U[this.ptr>>>2];return U[this.ptr>>>2]=e-1,1===e},this.set_adjusted_ptr=function(e){W[this.ptr+16>>>2]=e},this.get_adjusted_ptr=function(){return W[this.ptr+16>>>2]},this.get_exception_ptr=function(){if(mr(this.get_type()))return W[this.excPtr>>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var Se={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,i=e.length-1;i>=0;i--){var n=e[i];"."===n?e.splice(i,1):".."===n?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=Se.isAbs(e),r="/"===e.substr(-1);return(e=Se.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=Se.splitPath(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=Se.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments,0);return Se.normalize(e.join("/"))},join2:(e,t)=>Se.normalize(e+"/"+t)},be={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:xe.cwd();if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";e=i+"/"+e,t=Se.isAbs(i)}return(t?"/":"")+(e=Se.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=be.resolve(e).substr(1),t=be.resolve(t).substr(1);for(var i=r(e.split("/")),n=r(t.split("/")),s=Math.min(i.length,n.length),o=s,a=0;a0?r.slice(0,i).toString("utf-8"):null}else"undefined"!=typeof window&&"function"==typeof window.prompt?null!==(t=window.prompt("Input: "))&&(t+="\n"):"function"==typeof readline&&null!==(t=readline())&&(t+="\n");if(!t)return null;e.input=cr(t,!0)}return e.input.shift()},put_char:function(e,t){null===t||10===t?(y(A(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(y(A(e.output,0)),e.output=[])}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(S(A(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(S(A(e.output,0)),e.output=[])}}};function Ee(e){e=function(e,t){return 65536*Math.ceil(e/65536)}(e);var t=vr(65536,e);return t?(function(e,t){B.fill(0,e,e+t)}(t,e),t):0}var Te={ops_table:null,mount:function(e){return Te.createNode(null,"/",16895,0)},createNode:function(e,t,r,i){if(xe.isBlkdev(r)||xe.isFIFO(r))throw new xe.ErrnoError(63);Te.ops_table||(Te.ops_table={dir:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,lookup:Te.node_ops.lookup,mknod:Te.node_ops.mknod,rename:Te.node_ops.rename,unlink:Te.node_ops.unlink,rmdir:Te.node_ops.rmdir,readdir:Te.node_ops.readdir,symlink:Te.node_ops.symlink},stream:{llseek:Te.stream_ops.llseek}},file:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:{llseek:Te.stream_ops.llseek,read:Te.stream_ops.read,write:Te.stream_ops.write,allocate:Te.stream_ops.allocate,mmap:Te.stream_ops.mmap,msync:Te.stream_ops.msync}},link:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,readlink:Te.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:xe.chrdev_stream_ops}});var n=xe.createNode(e,t,r,i);return xe.isDir(n.mode)?(n.node_ops=Te.ops_table.dir.node,n.stream_ops=Te.ops_table.dir.stream,n.contents={}):xe.isFile(n.mode)?(n.node_ops=Te.ops_table.file.node,n.stream_ops=Te.ops_table.file.stream,n.usedBytes=0,n.contents=null):xe.isLink(n.mode)?(n.node_ops=Te.ops_table.link.node,n.stream_ops=Te.ops_table.link.stream):xe.isChrdev(n.mode)&&(n.node_ops=Te.ops_table.chrdev.node,n.stream_ops=Te.ops_table.chrdev.stream),n.timestamp=Date.now(),e&&(e.contents[t]=n,e.timestamp=n.timestamp),n},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,t){t>>>=0;var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var i=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,t){if(t>>>=0,e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr:function(e){var t={};return t.dev=xe.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,xe.isDir(e.mode)?t.size=4096:xe.isFile(e.mode)?t.size=e.usedBytes:xe.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&Te.resizeFileStorage(e,t.size)},lookup:function(e,t){throw xe.genericErrors[44]},mknod:function(e,t,r,i){return Te.createNode(e,t,r,i)},rename:function(e,t,r){if(xe.isDir(e.mode)){var i;try{i=xe.lookupNode(t,r)}catch(e){}if(i)for(var n in i.contents)throw new xe.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink:function(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir:function(e,t){var r=xe.lookupNode(e,t);for(var i in r.contents)throw new xe.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir:function(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink:function(e,t,r){var i=Te.createNode(e,t,41471,0);return i.link=r,i},readlink:function(e){if(!xe.isLink(e.mode))throw new xe.ErrnoError(28);return e.link}},stream_ops:{read:function(e,t,r,i,n){var s=e.node.contents;if(n>=e.node.usedBytes)return 0;var o=Math.min(e.node.usedBytes-n,i);if(o>8&&s.subarray)t.set(s.subarray(n,n+o),r);else for(var a=0;a0||r+t>>=0,L.set(a,s>>>0)}else o=!1,s=a.byteOffset;return{ptr:s,allocated:o}},msync:function(e,t,r,i,n){if(!xe.isFile(e.node.mode))throw new xe.ErrnoError(43);return 2&n||Te.stream_ops.write(e,t,0,i,r,!1),0}}},xe={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(e,t={})=>{if(!(e=be.resolve(xe.cwd(),e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new xe.ErrnoError(32);for(var r=Se.normalizeArray(e.split("/").filter((e=>!!e)),!1),i=xe.root,n="/",s=0;s40)throw new xe.ErrnoError(32)}}return{path:n,node:i}},getPath:e=>{for(var t;;){if(xe.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?r+"/"+t:r+t:r}t=t?e.name+"/"+t:e.name,e=e.parent}},hashName:(e,t)=>{for(var r=0,i=0;i>>0)%xe.nameTable.length},hashAddNode:e=>{var t=xe.hashName(e.parent.id,e.name);e.name_next=xe.nameTable[t],xe.nameTable[t]=e},hashRemoveNode:e=>{var t=xe.hashName(e.parent.id,e.name);if(xe.nameTable[t]===e)xe.nameTable[t]=e.name_next;else for(var r=xe.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode:(e,t)=>{var r=xe.mayLookup(e);if(r)throw new xe.ErrnoError(r,e);for(var i=xe.hashName(e.id,t),n=xe.nameTable[i];n;n=n.name_next){var s=n.name;if(n.parent.id===e.id&&s===t)return n}return xe.lookup(e,t)},createNode:(e,t,r,i)=>{var n=new xe.FSNode(e,t,r,i);return xe.hashAddNode(n),n},destroyNode:e=>{xe.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagModes:{r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},modeStringToFlags:e=>{var t=xe.flagModes[e];if(void 0===t)throw new Error("Unknown file open mode: "+e);return t},flagsToPermissionString:e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>xe.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>xe.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return xe.lookupNode(e,t),20}catch(e){}return xe.nodePermissions(e,"wx")},mayDelete:(e,t,r)=>{var i;try{i=xe.lookupNode(e,t)}catch(e){return e.errno}var n=xe.nodePermissions(e,"wx");if(n)return n;if(r){if(!xe.isDir(i.mode))return 54;if(xe.isRoot(i)||xe.getPath(i)===xe.cwd())return 10}else if(xe.isDir(i.mode))return 31;return 0},mayOpen:(e,t)=>e?xe.isLink(e.mode)?32:xe.isDir(e.mode)&&("r"!==xe.flagsToPermissionString(t)||512&t)?31:xe.nodePermissions(e,xe.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:(e=0,t=xe.MAX_OPEN_FDS)=>{for(var r=e;r<=t;r++)if(!xe.streams[r])return r;throw new xe.ErrnoError(33)},getStream:e=>xe.streams[e],createStream:(e,t,r)=>{xe.FSStream||(xe.FSStream=function(){this.shared={}},xe.FSStream.prototype={},Object.defineProperties(xe.FSStream.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return!!(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}},flags:{get:function(){return this.shared.flags},set:function(e){this.shared.flags=e}},position:{get:function(){return this.shared.position},set:function(e){this.shared.position=e}}})),e=Object.assign(new xe.FSStream,e);var i=xe.nextfd(t,r);return e.fd=i,xe.streams[i]=e,e},closeStream:e=>{xe.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=xe.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new xe.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{xe.devices[e]={stream_ops:t}},getDevice:e=>xe.devices[e],getMounts:e=>{for(var t=[],r=[e];r.length;){var i=r.pop();t.push(i),r.push.apply(r,i.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),xe.syncFSRequests++,xe.syncFSRequests>1&&S("warning: "+xe.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var r=xe.getMounts(xe.root.mount),i=0;function n(e){return xe.syncFSRequests--,t(e)}function s(e){if(e)return s.errored?void 0:(s.errored=!0,n(e));++i>=r.length&&n(null)}r.forEach((t=>{if(!t.type.syncfs)return s(null);t.type.syncfs(t,e,s)}))},mount:(e,t,r)=>{var i,n="/"===r,s=!r;if(n&&xe.root)throw new xe.ErrnoError(10);if(!n&&!s){var o=xe.lookupPath(r,{follow_mount:!1});if(r=o.path,i=o.node,xe.isMountpoint(i))throw new xe.ErrnoError(10);if(!xe.isDir(i.mode))throw new xe.ErrnoError(54)}var a={type:e,opts:t,mountpoint:r,mounts:[]},c=e.mount(a);return c.mount=a,a.root=c,n?xe.root=c:i&&(i.mounted=a,i.mount&&i.mount.mounts.push(a)),c},unmount:e=>{var t=xe.lookupPath(e,{follow_mount:!1});if(!xe.isMountpoint(t.node))throw new xe.ErrnoError(28);var r=t.node,i=r.mounted,n=xe.getMounts(i);Object.keys(xe.nameTable).forEach((e=>{for(var t=xe.nameTable[e];t;){var r=t.name_next;n.includes(t.mount)&&xe.destroyNode(t),t=r}})),r.mounted=null;var s=r.mount.mounts.indexOf(i);r.mount.mounts.splice(s,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,r)=>{var i=xe.lookupPath(e,{parent:!0}).node,n=Se.basename(e);if(!n||"."===n||".."===n)throw new xe.ErrnoError(28);var s=xe.mayCreate(i,n);if(s)throw new xe.ErrnoError(s);if(!i.node_ops.mknod)throw new xe.ErrnoError(63);return i.node_ops.mknod(i,n,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,xe.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,xe.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var r=e.split("/"),i="",n=0;n(void 0===r&&(r=t,t=438),t|=8192,xe.mknod(e,t,r)),symlink:(e,t)=>{if(!be.resolve(e))throw new xe.ErrnoError(44);var r=xe.lookupPath(t,{parent:!0}).node;if(!r)throw new xe.ErrnoError(44);var i=Se.basename(t),n=xe.mayCreate(r,i);if(n)throw new xe.ErrnoError(n);if(!r.node_ops.symlink)throw new xe.ErrnoError(63);return r.node_ops.symlink(r,i,e)},rename:(e,t)=>{var r,i,n=Se.dirname(e),s=Se.dirname(t),o=Se.basename(e),a=Se.basename(t);if(r=xe.lookupPath(e,{parent:!0}).node,i=xe.lookupPath(t,{parent:!0}).node,!r||!i)throw new xe.ErrnoError(44);if(r.mount!==i.mount)throw new xe.ErrnoError(75);var c,h=xe.lookupNode(r,o),l=be.relative(e,s);if("."!==l.charAt(0))throw new xe.ErrnoError(28);if("."!==(l=be.relative(t,n)).charAt(0))throw new xe.ErrnoError(55);try{c=xe.lookupNode(i,a)}catch(e){}if(h!==c){var u=xe.isDir(h.mode),d=xe.mayDelete(r,o,u);if(d)throw new xe.ErrnoError(d);if(d=c?xe.mayDelete(i,a,u):xe.mayCreate(i,a))throw new xe.ErrnoError(d);if(!r.node_ops.rename)throw new xe.ErrnoError(63);if(xe.isMountpoint(h)||c&&xe.isMountpoint(c))throw new xe.ErrnoError(10);if(i!==r&&(d=xe.nodePermissions(r,"w")))throw new xe.ErrnoError(d);xe.hashRemoveNode(h);try{r.node_ops.rename(h,i,a)}catch(e){throw e}finally{xe.hashAddNode(h)}}},rmdir:e=>{var t=xe.lookupPath(e,{parent:!0}).node,r=Se.basename(e),i=xe.lookupNode(t,r),n=xe.mayDelete(t,r,!0);if(n)throw new xe.ErrnoError(n);if(!t.node_ops.rmdir)throw new xe.ErrnoError(63);if(xe.isMountpoint(i))throw new xe.ErrnoError(10);t.node_ops.rmdir(t,r),xe.destroyNode(i)},readdir:e=>{var t=xe.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new xe.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=xe.lookupPath(e,{parent:!0}).node;if(!t)throw new xe.ErrnoError(44);var r=Se.basename(e),i=xe.lookupNode(t,r),n=xe.mayDelete(t,r,!1);if(n)throw new xe.ErrnoError(n);if(!t.node_ops.unlink)throw new xe.ErrnoError(63);if(xe.isMountpoint(i))throw new xe.ErrnoError(10);t.node_ops.unlink(t,r),xe.destroyNode(i)},readlink:e=>{var t=xe.lookupPath(e).node;if(!t)throw new xe.ErrnoError(44);if(!t.node_ops.readlink)throw new xe.ErrnoError(28);return be.resolve(xe.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var r=xe.lookupPath(e,{follow:!t}).node;if(!r)throw new xe.ErrnoError(44);if(!r.node_ops.getattr)throw new xe.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>xe.stat(e,!0),chmod:(e,t,r)=>{var i;if(!(i="string"==typeof e?xe.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);i.node_ops.setattr(i,{mode:4095&t|-4096&i.mode,timestamp:Date.now()})},lchmod:(e,t)=>{xe.chmod(e,t,!0)},fchmod:(e,t)=>{var r=xe.getStream(e);if(!r)throw new xe.ErrnoError(8);xe.chmod(r.node,t)},chown:(e,t,r,i)=>{var n;if(!(n="string"==typeof e?xe.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);n.node_ops.setattr(n,{timestamp:Date.now()})},lchown:(e,t,r)=>{xe.chown(e,t,r,!0)},fchown:(e,t,r)=>{var i=xe.getStream(e);if(!i)throw new xe.ErrnoError(8);xe.chown(i.node,t,r)},truncate:(e,t)=>{if(t<0)throw new xe.ErrnoError(28);var r;if(!(r="string"==typeof e?xe.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);if(xe.isDir(r.mode))throw new xe.ErrnoError(31);if(!xe.isFile(r.mode))throw new xe.ErrnoError(28);var i=xe.nodePermissions(r,"w");if(i)throw new xe.ErrnoError(i);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var r=xe.getStream(e);if(!r)throw new xe.ErrnoError(8);if(!(2097155&r.flags))throw new xe.ErrnoError(28);xe.truncate(r.node,t)},utime:(e,t,r)=>{var i=xe.lookupPath(e,{follow:!0}).node;i.node_ops.setattr(i,{timestamp:Math.max(t,r)})},open:(t,r,i)=>{if(""===t)throw new xe.ErrnoError(44);var n;if(i=void 0===i?438:i,i=64&(r="string"==typeof r?xe.modeStringToFlags(r):r)?4095&i|32768:0,"object"==typeof t)n=t;else{t=Se.normalize(t);try{n=xe.lookupPath(t,{follow:!(131072&r)}).node}catch(e){}}var s=!1;if(64&r)if(n){if(128&r)throw new xe.ErrnoError(20)}else n=xe.mknod(t,i,0),s=!0;if(!n)throw new xe.ErrnoError(44);if(xe.isChrdev(n.mode)&&(r&=-513),65536&r&&!xe.isDir(n.mode))throw new xe.ErrnoError(54);if(!s){var o=xe.mayOpen(n,r);if(o)throw new xe.ErrnoError(o)}512&r&&!s&&xe.truncate(n,0),r&=-131713;var a=xe.createStream({node:n,path:xe.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return a.stream_ops.open&&a.stream_ops.open(a),!e.logReadFiles||1&r||(xe.readFiles||(xe.readFiles={}),t in xe.readFiles||(xe.readFiles[t]=1)),a},close:e=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{xe.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,r)=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new xe.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new xe.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read:(e,t,r,i,n)=>{if(r>>>=0,i<0||n<0)throw new xe.ErrnoError(28);if(xe.isClosed(e))throw new xe.ErrnoError(8);if(1==(2097155&e.flags))throw new xe.ErrnoError(8);if(xe.isDir(e.node.mode))throw new xe.ErrnoError(31);if(!e.stream_ops.read)throw new xe.ErrnoError(28);var s=void 0!==n;if(s){if(!e.seekable)throw new xe.ErrnoError(70)}else n=e.position;var o=e.stream_ops.read(e,t,r,i,n);return s||(e.position+=o),o},write:(e,t,r,i,n,s)=>{if(r>>>=0,i<0||n<0)throw new xe.ErrnoError(28);if(xe.isClosed(e))throw new xe.ErrnoError(8);if(!(2097155&e.flags))throw new xe.ErrnoError(8);if(xe.isDir(e.node.mode))throw new xe.ErrnoError(31);if(!e.stream_ops.write)throw new xe.ErrnoError(28);e.seekable&&1024&e.flags&&xe.llseek(e,0,2);var o=void 0!==n;if(o){if(!e.seekable)throw new xe.ErrnoError(70)}else n=e.position;var a=e.stream_ops.write(e,t,r,i,n,s);return o||(e.position+=a),a},allocate:(e,t,r)=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);if(t<0||r<=0)throw new xe.ErrnoError(28);if(!(2097155&e.flags))throw new xe.ErrnoError(8);if(!xe.isFile(e.node.mode)&&!xe.isDir(e.node.mode))throw new xe.ErrnoError(43);if(!e.stream_ops.allocate)throw new xe.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap:(e,t,r,i,n)=>{if(2&i&&!(2&n)&&2!=(2097155&e.flags))throw new xe.ErrnoError(2);if(1==(2097155&e.flags))throw new xe.ErrnoError(2);if(!e.stream_ops.mmap)throw new xe.ErrnoError(43);return e.stream_ops.mmap(e,t,r,i,n)},msync:(e,t,r,i,n)=>(r>>>=0,e&&e.stream_ops.msync?e.stream_ops.msync(e,t,r,i,n):0),munmap:e=>0,ioctl:(e,t,r)=>{if(!e.stream_ops.ioctl)throw new xe.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile:(e,t={})=>{if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'+t.encoding+'"');var r,i=xe.open(e,t.flags),n=xe.stat(e).size,s=new Uint8Array(n);return xe.read(i,s,0,n,0),"utf8"===t.encoding?r=A(s,0):"binary"===t.encoding&&(r=s),xe.close(i),r},writeFile:(e,t,r={})=>{r.flags=r.flags||577;var i=xe.open(e,r.flags,r.mode);if("string"==typeof t){var n=new Uint8Array(R(t)+1),s=O(t,n,0,n.length);xe.write(i,n,0,s,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");xe.write(i,t,0,t.byteLength,void 0,r.canOwn)}xe.close(i)},cwd:()=>xe.currentPath,chdir:e=>{var t=xe.lookupPath(e,{follow:!0});if(null===t.node)throw new xe.ErrnoError(44);if(!xe.isDir(t.node.mode))throw new xe.ErrnoError(54);var r=xe.nodePermissions(t.node,"x");if(r)throw new xe.ErrnoError(r);xe.currentPath=t.path},createDefaultDirectories:()=>{xe.mkdir("/tmp"),xe.mkdir("/home"),xe.mkdir("/home/web_user")},createDefaultDevices:()=>{xe.mkdir("/dev"),xe.registerDevice(xe.makedev(1,3),{read:()=>0,write:(e,t,r,i,n)=>i}),xe.mkdev("/dev/null",xe.makedev(1,3)),we.register(xe.makedev(5,0),we.default_tty_ops),we.register(xe.makedev(6,0),we.default_tty1_ops),xe.mkdev("/dev/tty",xe.makedev(5,0)),xe.mkdev("/dev/tty1",xe.makedev(6,0));var e=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return function(){return crypto.getRandomValues(e),e[0]}}if(v)try{var t=r(725);return function(){return t.randomBytes(1)[0]}}catch(e){}return function(){ae("randomDevice")}}();xe.createDevice("/dev","random",e),xe.createDevice("/dev","urandom",e),xe.mkdir("/dev/shm"),xe.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{xe.mkdir("/proc");var e=xe.mkdir("/proc/self");xe.mkdir("/proc/self/fd"),xe.mount({mount:()=>{var t=xe.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var r=+t,i=xe.getStream(r);if(!i)throw new xe.ErrnoError(8);var n={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>i.path}};return n.parent=n,n}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{e.stdin?xe.createDevice("/dev","stdin",e.stdin):xe.symlink("/dev/tty","/dev/stdin"),e.stdout?xe.createDevice("/dev","stdout",null,e.stdout):xe.symlink("/dev/tty","/dev/stdout"),e.stderr?xe.createDevice("/dev","stderr",null,e.stderr):xe.symlink("/dev/tty1","/dev/stderr"),xe.open("/dev/stdin",0),xe.open("/dev/stdout",1),xe.open("/dev/stderr",1)},ensureErrnoError:()=>{xe.ErrnoError||(xe.ErrnoError=function(e,t){this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},xe.ErrnoError.prototype=new Error,xe.ErrnoError.prototype.constructor=xe.ErrnoError,[44].forEach((e=>{xe.genericErrors[e]=new xe.ErrnoError(e),xe.genericErrors[e].stack=""})))},staticInit:()=>{xe.ensureErrnoError(),xe.nameTable=new Array(4096),xe.mount(Te,{},"/"),xe.createDefaultDirectories(),xe.createDefaultDevices(),xe.createSpecialDirectories(),xe.filesystems={MEMFS:Te}},init:(t,r,i)=>{xe.init.initialized=!0,xe.ensureErrnoError(),e.stdin=t||e.stdin,e.stdout=r||e.stdout,e.stderr=i||e.stderr,xe.createStandardStreams()},quit:()=>{xe.init.initialized=!1;for(var e=0;e{var r=0;return e&&(r|=365),t&&(r|=146),r},findObject:(e,t)=>{var r=xe.analyzePath(e,t);return r.exists?r.object:null},analyzePath:(e,t)=>{try{e=(i=xe.lookupPath(e,{follow:!t})).path}catch(e){}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var i=xe.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=i.path,r.parentObject=i.node,r.name=Se.basename(e),i=xe.lookupPath(e,{follow:!t}),r.exists=!0,r.path=i.path,r.object=i.node,r.name=i.node.name,r.isRoot="/"===i.path}catch(e){r.error=e.errno}return r},createPath:(e,t,r,i)=>{e="string"==typeof e?e:xe.getPath(e);for(var n=t.split("/").reverse();n.length;){var s=n.pop();if(s){var o=Se.join2(e,s);try{xe.mkdir(o)}catch(e){}e=o}}return o},createFile:(e,t,r,i,n)=>{var s=Se.join2("string"==typeof e?e:xe.getPath(e),t),o=xe.getMode(i,n);return xe.create(s,o)},createDataFile:(e,t,r,i,n,s)=>{var o=t;e&&(e="string"==typeof e?e:xe.getPath(e),o=t?Se.join2(e,t):e);var a=xe.getMode(i,n),c=xe.create(o,a);if(r){if("string"==typeof r){for(var h=new Array(r.length),l=0,u=r.length;l{var n=Se.join2("string"==typeof e?e:xe.getPath(e),t),s=xe.getMode(!!r,!!i);xe.createDevice.major||(xe.createDevice.major=64);var o=xe.makedev(xe.createDevice.major++,0);return xe.registerDevice(o,{open:e=>{e.seekable=!1},close:e=>{i&&i.buffer&&i.buffer.length&&i(10)},read:(e,t,i,n,s)=>{for(var o=0,a=0;a{for(var o=0;o{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!n)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=cr(n(e.url),!0),e.usedBytes=e.contents.length}catch(e){throw new xe.ErrnoError(29)}},createLazyFile:(e,t,r,i,n)=>{function s(){this.lengthKnown=!1,this.chunks=[]}if(s.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},s.prototype.setDataGetter=function(e){this.getter=e},s.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,i=Number(e.getResponseHeader("Content-length")),n=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,s=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,o=1048576;n||(o=i);var a=this;a.setDataGetter((e=>{var t=e*o,n=(e+1)*o-1;if(n=Math.min(n,i-1),void 0===a.chunks[e]&&(a.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>i-1)throw new Error("only "+i+" bytes available! programmer error!");var n=new XMLHttpRequest;if(n.open("GET",r,!1),i!==o&&n.setRequestHeader("Range","bytes="+e+"-"+t),n.responseType="arraybuffer",n.overrideMimeType&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.send(null),!(n.status>=200&&n.status<300||304===n.status))throw new Error("Couldn't load "+r+". Status: "+n.status);return void 0!==n.response?new Uint8Array(n.response||[]):cr(n.responseText||"",!0)})(t,n)),void 0===a.chunks[e])throw new Error("doXHR failed!");return a.chunks[e]})),!s&&i||(o=i=1,i=this.getter(0).length,o=i,y("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=i,this._chunkSize=o,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!g)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var o=new s;Object.defineProperties(o,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var a={isDevice:!1,contents:o}}else a={isDevice:!1,url:r};var c=xe.createFile(e,t,a,i,n);a.contents?c.contents=a.contents:a.url&&(c.contents=null,c.url=a.url),Object.defineProperties(c,{usedBytes:{get:function(){return this.contents.length}}});var h={};function l(e,t,r,i,n){var s=e.node.contents;if(n>=s.length)return 0;var o=Math.min(s.length-n,i);if(s.slice)for(var a=0;a{var t=c.stream_ops[e];h[e]=function(){return xe.forceLoadFile(c),t.apply(null,arguments)}})),h.read=(e,t,r,i,n)=>(xe.forceLoadFile(c),l(e,t,r,i,n)),h.mmap=(e,t,r,i,n)=>{xe.forceLoadFile(c);var s=Ee(t);if(!s)throw new xe.ErrnoError(48);return l(e,L,s,t,r),{ptr:s,allocated:!0}},c.stream_ops=h,c},createPreloadedFile:(e,t,r,i,n,o,a,c,h,l)=>{var u=t?be.resolve(Se.join2(e,t)):e;function d(r){function s(r){l&&l(),c||xe.createDataFile(e,t,r,i,n,h),o&&o(),oe()}Nt.handledByPreloadPlugin(r,u,s,(()=>{a&&a(),oe()}))||s(r)}se(),"string"==typeof r?function(e,t,r,i){var n="al "+e;s(e,(function(t){C(t,'Loading data file "'+e+'" failed (no arrayBuffer).'),d(new Uint8Array(t)),n&&oe()}),(function(t){if(!r)throw'Loading data file "'+e+'" failed.';r()})),n&&se()}(r,0,a):d(r)},indexedDB:()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,DB_NAME:()=>"EM_FS_"+window.location.pathname,DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(e,t,r)=>{t=t||(()=>{}),r=r||(()=>{});var i=xe.indexedDB();try{var n=i.open(xe.DB_NAME(),xe.DB_VERSION)}catch(e){return r(e)}n.onupgradeneeded=()=>{y("creating db"),n.result.createObjectStore(xe.DB_STORE_NAME)},n.onsuccess=()=>{var i=n.result.transaction([xe.DB_STORE_NAME],"readwrite"),s=i.objectStore(xe.DB_STORE_NAME),o=0,a=0,c=e.length;function h(){0==a?t():r()}e.forEach((e=>{var t=s.put(xe.analyzePath(e).object.contents,e);t.onsuccess=()=>{++o+a==c&&h()},t.onerror=()=>{a++,o+a==c&&h()}})),i.onerror=r},n.onerror=r},loadFilesFromDB:(e,t,r)=>{t=t||(()=>{}),r=r||(()=>{});var i=xe.indexedDB();try{var n=i.open(xe.DB_NAME(),xe.DB_VERSION)}catch(e){return r(e)}n.onupgradeneeded=r,n.onsuccess=()=>{var i=n.result;try{var s=i.transaction([xe.DB_STORE_NAME],"readonly")}catch(e){return void r(e)}var o=s.objectStore(xe.DB_STORE_NAME),a=0,c=0,h=e.length;function l(){0==c?t():r()}e.forEach((e=>{var t=o.get(e);t.onsuccess=()=>{xe.analyzePath(e).exists&&xe.unlink(e),xe.createDataFile(Se.dirname(e),Se.basename(e),t.result,!0,!0,!0),++a+c==h&&l()},t.onerror=()=>{c++,a+c==h&&l()}})),s.onerror=r},n.onerror=r}},ke={DEFAULT_POLLMASK:5,calculateAt:function(e,t,r){if(Se.isAbs(t))return t;var i;if(-100===e)i=xe.cwd();else{var n=xe.getStream(e);if(!n)throw new xe.ErrnoError(8);i=n.path}if(0==t.length){if(!r)throw new xe.ErrnoError(44);return i}return Se.join2(i,t)},doStat:function(e,t,r){try{var i=e(t)}catch(e){if(e&&e.node&&Se.normalize(t)!==Se.normalize(xe.getPath(e.node)))return-54;throw e}return U[r>>>2]=i.dev,U[r+4>>>2]=0,U[r+8>>>2]=i.ino,U[r+12>>>2]=i.mode,U[r+16>>>2]=i.nlink,U[r+20>>>2]=i.uid,U[r+24>>>2]=i.gid,U[r+28>>>2]=i.rdev,U[r+32>>>2]=0,ue=[i.size>>>0,(le=i.size,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[r+40>>>2]=ue[0],U[r+44>>>2]=ue[1],U[r+48>>>2]=4096,U[r+52>>>2]=i.blocks,U[r+56>>>2]=i.atime.getTime()/1e3|0,U[r+60>>>2]=0,U[r+64>>>2]=i.mtime.getTime()/1e3|0,U[r+68>>>2]=0,U[r+72>>>2]=i.ctime.getTime()/1e3|0,U[r+76>>>2]=0,ue=[i.ino>>>0,(le=i.ino,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[r+80>>>2]=ue[0],U[r+84>>>2]=ue[1],0},doMsync:function(e,t,r,i,n){var s=B.slice(e,e+r);xe.msync(t,s,n,r,i)},varargs:void 0,get:function(){return ke.varargs+=4,U[ke.varargs-4>>>2]},getStr:function(e){return _(e)},getStreamFromFD:function(e){var t=xe.getStream(e);if(!t)throw new xe.ErrnoError(8);return t}},Ce="To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking";function Ae(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+e)}}var _e=void 0;function Oe(e){for(var t="",r=e;B[r>>>0];)t+=_e[B[r++>>>0]];return t}var De={},Re={},Fe={},Le=48,Be=57;function Me(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=Le&&t<=Be?"_"+e:e}function Ie(e,t){return e=Me(e),new Function("body","return function "+e+'() {\n "use strict"; return body.apply(this, arguments);\n};\n')(t)}function Ue(e,t){var r=Ie(t,(function(e){this.name=t,this.message=e;var r=new Error(e).stack;void 0!==r&&(this.stack=this.toString()+"\n"+r.replace(/^Error(:[^\n]*)?\n/,""))}));return r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message},r}var We=void 0;function Ne(e){throw new We(e)}var Ge=void 0;function He(e){throw new Ge(e)}function Ve(e,t,r){function i(t){var i=r(t);i.length!==e.length&&He("Mismatched type converter count");for(var n=0;n{Re.hasOwnProperty(e)?n[t]=Re[e]:(s.push(e),De.hasOwnProperty(e)||(De[e]=[]),De[e].push((()=>{n[t]=Re[e],++o===s.length&&i(n)})))})),0===s.length&&i(n)}function ze(e,t,r={}){if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");var i=t.name;if(e||Ne('type "'+i+'" must have a positive integer typeid pointer'),Re.hasOwnProperty(e)){if(r.ignoreDuplicateRegistrations)return;Ne("Cannot register type '"+i+"' twice")}if(Re[e]=t,delete Fe[e],De.hasOwnProperty(e)){var n=De[e];delete De[e],n.forEach((e=>e()))}}function je(e){Ne(e.$$.ptrType.registeredClass.name+" instance already deleted")}var qe=!1;function $e(e){}function Ye(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}function Xe(e,t,r){if(t===r)return e;if(void 0===r.baseClass)return null;var i=Xe(e,t,r.baseClass);return null===i?null:r.downcast(i)}var Ze={};var Je=[];function Qe(){for(;Je.length;){var e=Je.pop();e.$$.deleteScheduled=!1,e.delete()}}var Ke=void 0;var et={};function tt(e,t){return t.ptrType&&t.ptr||He("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!=!!t.smartPtr&&He("Both smartPtrType and smartPtr must be specified"),t.count={value:1},rt(Object.create(e,{$$:{value:t}}))}function rt(e){return"undefined"==typeof FinalizationRegistry?(rt=e=>e,e):(qe=new FinalizationRegistry((e=>{Ye(e.$$)})),rt=e=>{var t=e.$$;if(t.smartPtr){var r={$$:t};qe.register(e,r,e)}return e},$e=e=>qe.unregister(e),rt(e))}function it(){}function nt(e,t,r){if(void 0===e[t].overloadTable){var i=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||Ne("Function '"+r+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+e[t].overloadTable+")!"),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[i.argCount]=i}}function st(t,r,i){e.hasOwnProperty(t)?((void 0===i||void 0!==e[t].overloadTable&&void 0!==e[t].overloadTable[i])&&Ne("Cannot register public name '"+t+"' twice"),nt(e,t,t),e.hasOwnProperty(i)&&Ne("Cannot register multiple overloads of a function with the same number of arguments ("+i+")!"),e[t].overloadTable[i]=r):(e[t]=r,void 0!==i&&(e[t].numArguments=i))}function ot(e,t,r,i,n,s,o,a){this.name=e,this.constructor=t,this.instancePrototype=r,this.rawDestructor=i,this.baseClass=n,this.getActualType=s,this.upcast=o,this.downcast=a,this.pureVirtualFunctions=[]}function at(e,t,r){for(;t!==r;)t.upcast||Ne("Expected null or instance of "+r.name+", got an instance of "+t.name),e=t.upcast(e),t=t.baseClass;return e}function ct(e,t){if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name);var r=t.$$.ptrType.registeredClass;return at(t.$$.ptr,r,this.registeredClass)}function ht(e,t){var r;if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),this.isSmartPointer?(r=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,r),r):0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&t.$$.ptrType.isConst&&Ne("Cannot convert argument of type "+(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name)+" to parameter type "+this.name);var i=t.$$.ptrType.registeredClass;if(r=at(t.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&Ne("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?r=t.$$.smartPtr:Ne("Cannot convert argument of type "+(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:r=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)r=t.$$.smartPtr;else{var n=t.clone();r=this.rawShare(r,kt.toHandle((function(){n.delete()}))),null!==e&&e.push(this.rawDestructor,r)}break;default:Ne("Unsupporting sharing policy")}return r}function lt(e,t){if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name),t.$$.ptrType.isConst&&Ne("Cannot convert argument of type "+t.$$.ptrType.name+" to parameter type "+this.name);var r=t.$$.ptrType.registeredClass;return at(t.$$.ptr,r,this.registeredClass)}function ut(e){return this.fromWireType(W[e>>>2])}function dt(e,t,r,i,n,s,o,a,c,h,l){this.name=e,this.registeredClass=t,this.isReference=r,this.isConst=i,this.isSmartPointer=n,this.pointeeType=s,this.sharingPolicy=o,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=h,this.rawDestructor=l,n||void 0!==t.baseClass?this.toWireType=ht:i?(this.toWireType=ct,this.destructorFunction=null):(this.toWireType=lt,this.destructorFunction=null)}function pt(t,r){var i,n,s,o=(t=Oe(t)).includes("j")?(i=t,n=r,s=[],function(){return s.length=0,Object.assign(s,arguments),function(t,r,i){return t.includes("j")?function(t,r,i){var n=e["dynCall_"+t];return i&&i.length?n.apply(null,[r].concat(i)):n.call(null,r)}(t,r,i):me(r).apply(null,i)}(i,n,s)}):me(r);return"function"!=typeof o&&Ne("unknown function pointer with signature "+t+": "+r),o}var ft=void 0;function gt(e){var t=fr(e),r=Oe(t);return dr(t),r}function vt(e,t){var r=[],i={};throw t.forEach((function e(t){i[t]||Re[t]||(Fe[t]?Fe[t].forEach(e):(r.push(t),i[t]=!0))})),new ft(e+": "+r.map(gt).join([", "]))}function mt(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type "+typeof e+" which is not a function");var r=Ie(e.name||"unknownFunctionName",(function(){}));r.prototype=e.prototype;var i=new r,n=e.apply(i,t);return n instanceof Object?n:i}function yt(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function St(e,t,r,i,n){var s=t.length;s<2&&Ne("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var o=null!==t[1]&&null!==r,a=!1,c=1;c0?", ":"")+u),d+=(h?"var rv = ":"")+"invoker(fn"+(u.length>0?", ":"")+u+");\n",a)d+="runDestructors(destructors);\n";else for(c=o?1:2;c>2)+i>>>0]);return r}function wt(e,t,r){return e instanceof Object||Ne(r+' with invalid "this": '+e),e instanceof t.registeredClass.constructor||Ne(r+' incompatible with "this" of type '+e.constructor.name),e.$$.ptr||Ne("cannot call emscripten binding method "+r+" on deleted object"),at(e.$$.ptr,e.$$.ptrType.registeredClass,t.registeredClass)}var Et=[],Tt=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function xt(e){e>4&&0==--Tt[e].refcount&&(Tt[e]=void 0,Et.push(e))}var kt={toValue:e=>(e||Ne("Cannot use deleted val. handle = "+e),Tt[e].value),toHandle:e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var t=Et.length?Et.pop():Tt.length;return Tt[t]={refcount:1,value:e},t}}};function Ct(e,t,r){switch(t){case 0:return function(e){var t=r?L:B;return this.fromWireType(t[e>>>0])};case 1:return function(e){var t=r?M:I;return this.fromWireType(t[e>>>1])};case 2:return function(e){var t=r?U:W;return this.fromWireType(t[e>>>2])};default:throw new TypeError("Unknown integer type: "+e)}}function Pt(e,t){var r=Re[e];return void 0===r&&Ne(t+" has unknown type "+gt(e)),r}function At(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function _t(e,t){switch(t){case 2:return function(e){return this.fromWireType(N[e>>>2])};case 3:return function(e){return this.fromWireType(G[e>>>3])};default:throw new TypeError("Unknown float type: "+e)}}function Ot(e,t,r){switch(t){case 0:return r?function(e){return L[e>>>0]}:function(e){return B[e>>>0]};case 1:return r?function(e){return M[e>>>1]}:function(e){return I[e>>>1]};case 2:return r?function(e){return U[e>>>2]}:function(e){return W[e>>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var Dt={};function Rt(e){var t=Dt[e];return void 0===t?Oe(e):t}var Ft=[];function Lt(){return"object"==typeof globalThis?globalThis:Function("return this")()}var Bt,Mt=[];function It(t,r){if(Nt.mainLoop.timingMode=t,Nt.mainLoop.timingValue=r,!Nt.mainLoop.func)return 1;if(Nt.mainLoop.running||(Nt.mainLoop.running=!0),0==t)Nt.mainLoop.scheduler=function(){var e=0|Math.max(0,Nt.mainLoop.tickStartTime+r-Bt());setTimeout(Nt.mainLoop.runner,e)},Nt.mainLoop.method="timeout";else if(1==t)Nt.mainLoop.scheduler=function(){Nt.requestAnimationFrame(Nt.mainLoop.runner)},Nt.mainLoop.method="rAF";else if(2==t){if("undefined"==typeof setImmediate){var i=[],n="setimmediate";addEventListener("message",(function(e){e.data!==n&&e.data.target!==n||(e.stopPropagation(),i.shift()())}),!0),setImmediate=function(t){i.push(t),g?(void 0===e.setImmediates&&(e.setImmediates=[]),e.setImmediates.push(t),postMessage({target:n})):postMessage(n,"*")}}Nt.mainLoop.scheduler=function(){setImmediate(Nt.mainLoop.runner)},Nt.mainLoop.method="immediate"}return 0}function Ut(e,t){if(!k)if(t)e();else try{e()}catch(e){!function(e){if(e instanceof yr||"unwind"==e)return x;p(1,e)}(e)}}function Wt(e,t){return setTimeout((function(){Ut(e)}),t)}Bt=v?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now();var Nt={mainLoop:{running:!1,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){Nt.mainLoop.scheduler=null,Nt.mainLoop.currentlyRunningMainloop++},resume:function(){Nt.mainLoop.currentlyRunningMainloop++;var e=Nt.mainLoop.timingMode,t=Nt.mainLoop.timingValue,r=Nt.mainLoop.func;Nt.mainLoop.func=null,function(e,t,r,i,n){C(!Nt.mainLoop.func,"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters."),Nt.mainLoop.func=e,Nt.mainLoop.arg=i;var s=Nt.mainLoop.currentlyRunningMainloop;function o(){return!(s0){var t=Date.now(),r=Nt.mainLoop.queue.shift();if(r.func(r.arg),Nt.mainLoop.remainingBlockers){var i=Nt.mainLoop.remainingBlockers,n=i%1==0?i-1:Math.floor(i);r.counted?Nt.mainLoop.remainingBlockers=n:(n+=.5,Nt.mainLoop.remainingBlockers=(8*i+n)/9)}if(y('main loop blocker "'+r.name+'" took '+(Date.now()-t)+" ms"),Nt.mainLoop.updateStatus(),!o())return;setTimeout(Nt.mainLoop.runner,0)}else o()&&(Nt.mainLoop.currentFrameNumber=Nt.mainLoop.currentFrameNumber+1|0,1==Nt.mainLoop.timingMode&&Nt.mainLoop.timingValue>1&&Nt.mainLoop.currentFrameNumber%Nt.mainLoop.timingValue!=0?Nt.mainLoop.scheduler():(0==Nt.mainLoop.timingMode&&(Nt.mainLoop.tickStartTime=Bt()),Nt.mainLoop.runIter(e),o()&&("object"==typeof SDL&&SDL.audio&&SDL.audio.queueNewAudioData&&SDL.audio.queueNewAudioData(),Nt.mainLoop.scheduler())))}}(r,0,0,Nt.mainLoop.arg),It(e,t),Nt.mainLoop.scheduler()},updateStatus:function(){if(e.setStatus){var t=e.statusMessage||"Please wait...",r=Nt.mainLoop.remainingBlockers,i=Nt.mainLoop.expectedBlockers;r?r{C(a.complete,"Image "+t+" could not be decoded");var i=document.createElement("canvas");i.width=a.width,i.height=a.height,i.getContext("2d").drawImage(a,0,0),ir[t]=i,Nt.URLObject.revokeObjectURL(o),r&&r(e)},a.onerror=e=>{y("Image "+o+" could not be decoded"),i&&i()},a.src=o}};e.preloadPlugins.push(t);var r={canHandle:function(t){return!e.noAudioDecoding&&t.substr(-4)in{".ogg":1,".wav":1,".mp3":1}},handle:function(e,t,r,i){var n=!1;function s(i){n||(n=!0,nr[t]=i,r&&r(e))}function o(){n||(n=!0,nr[t]=new Audio,i&&i())}if(!Nt.hasBlobConstructor)return o();try{var a=new Blob([e],{type:Nt.getMimetype(t)})}catch(e){return o()}var c=Nt.URLObject.createObjectURL(a),h=new Audio;h.addEventListener("canplaythrough",(function(){s(h)}),!1),h.onerror=function(r){n||(y("warning: browser could not fully decode audio "+t+", trying slower base64 approach"),h.src="data:audio/x-"+t.substr(-3)+";base64,"+function(e){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="",i=0,n=0,s=0;s=6;){var o=i>>n-6&63;n-=6,r+=t[o]}return 2==n?(r+=t[(3&i)<<4],r+="=="):4==n&&(r+=t[(15&i)<<2],r+="="),r}(e),s(h))},h.src=c,Wt((function(){s(h)}),1e4)}};e.preloadPlugins.push(r);var i=e.canvas;i&&(i.requestPointerLock=i.requestPointerLock||i.mozRequestPointerLock||i.webkitRequestPointerLock||i.msRequestPointerLock||function(){},i.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},i.exitPointerLock=i.exitPointerLock.bind(document),document.addEventListener("pointerlockchange",n,!1),document.addEventListener("mozpointerlockchange",n,!1),document.addEventListener("webkitpointerlockchange",n,!1),document.addEventListener("mspointerlockchange",n,!1),e.elementPointerLock&&i.addEventListener("click",(function(t){!Nt.pointerLock&&e.canvas.requestPointerLock&&(e.canvas.requestPointerLock(),t.preventDefault())}),!1))}function n(){Nt.pointerLock=document.pointerLockElement===e.canvas||document.mozPointerLockElement===e.canvas||document.webkitPointerLockElement===e.canvas||document.msPointerLockElement===e.canvas}},handledByPreloadPlugin:function(t,r,i,n){Nt.init();var s=!1;return e.preloadPlugins.forEach((function(e){s||e.canHandle(r)&&(e.handle(t,r,i,n),s=!0)})),s},createContext:function(t,r,i,n){if(r&&e.ctx&&t==e.canvas)return e.ctx;var s,o;if(r){var a={antialias:!1,alpha:!1,majorVersion:1};if(n)for(var c in n)a[c]=n[c];void 0!==$t&&(o=$t.createContext(t,a))&&(s=$t.getContext(o).GLctx)}else s=t.getContext("2d");return s?(i&&(r||C(void 0===rr,"cannot set in module if GLctx is used, but we are a non-GL context that would replace it"),e.ctx=s,r&&$t.makeContextCurrent(o),e.useWebGL=r,Nt.moduleContextCreatedCallbacks.forEach((function(e){e()})),Nt.init()),s):null},destroyContext:function(e,t,r){},fullscreenHandlersInstalled:!1,lockPointer:void 0,resizeCanvas:void 0,requestFullscreen:function(t,r){Nt.lockPointer=t,Nt.resizeCanvas=r,void 0===Nt.lockPointer&&(Nt.lockPointer=!0),void 0===Nt.resizeCanvas&&(Nt.resizeCanvas=!1);var i=e.canvas;function n(){Nt.isFullscreen=!1;var t=i.parentNode;(document.fullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement)===t?(i.exitFullscreen=Nt.exitFullscreen,Nt.lockPointer&&i.requestPointerLock(),Nt.isFullscreen=!0,Nt.resizeCanvas?Nt.setFullscreenCanvasSize():Nt.updateCanvasDimensions(i)):(t.parentNode.insertBefore(i,t),t.parentNode.removeChild(t),Nt.resizeCanvas?Nt.setWindowedCanvasSize():Nt.updateCanvasDimensions(i)),e.onFullScreen&&e.onFullScreen(Nt.isFullscreen),e.onFullscreen&&e.onFullscreen(Nt.isFullscreen)}Nt.fullscreenHandlersInstalled||(Nt.fullscreenHandlersInstalled=!0,document.addEventListener("fullscreenchange",n,!1),document.addEventListener("mozfullscreenchange",n,!1),document.addEventListener("webkitfullscreenchange",n,!1),document.addEventListener("MSFullscreenChange",n,!1));var s=document.createElement("div");i.parentNode.insertBefore(s,i),s.appendChild(i),s.requestFullscreen=s.requestFullscreen||s.mozRequestFullScreen||s.msRequestFullscreen||(s.webkitRequestFullscreen?function(){s.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)}:null)||(s.webkitRequestFullScreen?function(){s.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),s.requestFullscreen()},exitFullscreen:function(){return!!Nt.isFullscreen&&((document.exitFullscreen||document.cancelFullScreen||document.mozCancelFullScreen||document.msExitFullscreen||document.webkitCancelFullScreen||function(){}).apply(document,[]),!0)},nextRAF:0,fakeRequestAnimationFrame:function(e){var t=Date.now();if(0===Nt.nextRAF)Nt.nextRAF=t+1e3/60;else for(;t+2>=Nt.nextRAF;)Nt.nextRAF+=1e3/60;var r=Math.max(Nt.nextRAF-t,0);setTimeout(e,r)},requestAnimationFrame:function(e){"function"!=typeof requestAnimationFrame?(0,Nt.fakeRequestAnimationFrame)(e):requestAnimationFrame(e)},safeSetTimeout:function(e){return Wt(e)},safeRequestAnimationFrame:function(e){return Nt.requestAnimationFrame((function(){Ut(e)}))},getMimetype:function(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[e.substr(e.lastIndexOf(".")+1)]},getUserMedia:function(e){window.getUserMedia||(window.getUserMedia=navigator.getUserMedia||navigator.mozGetUserMedia),window.getUserMedia(e)},getMovementX:function(e){return e.movementX||e.mozMovementX||e.webkitMovementX||0},getMovementY:function(e){return e.movementY||e.mozMovementY||e.webkitMovementY||0},getMouseWheelDelta:function(e){var t=0;switch(e.type){case"DOMMouseScroll":t=e.detail/3;break;case"mousewheel":t=e.wheelDelta/120;break;case"wheel":switch(t=e.deltaY,e.deltaMode){case 0:t/=100;break;case 1:t/=3;break;case 2:t*=80;break;default:throw"unrecognized mouse wheel delta mode: "+e.deltaMode}break;default:throw"unrecognized mouse wheel event: "+e.type}return t},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(t){if(Nt.pointerLock)"mousemove"!=t.type&&"mozMovementX"in t?Nt.mouseMovementX=Nt.mouseMovementY=0:(Nt.mouseMovementX=Nt.getMovementX(t),Nt.mouseMovementY=Nt.getMovementY(t)),"undefined"!=typeof SDL?(Nt.mouseX=SDL.mouseX+Nt.mouseMovementX,Nt.mouseY=SDL.mouseY+Nt.mouseMovementY):(Nt.mouseX+=Nt.mouseMovementX,Nt.mouseY+=Nt.mouseMovementY);else{var r=e.canvas.getBoundingClientRect(),i=e.canvas.width,n=e.canvas.height,s=void 0!==window.scrollX?window.scrollX:window.pageXOffset,o=void 0!==window.scrollY?window.scrollY:window.pageYOffset;if("touchstart"===t.type||"touchend"===t.type||"touchmove"===t.type){var a=t.touch;if(void 0===a)return;var c=a.pageX-(s+r.left),h=a.pageY-(o+r.top),l={x:c*=i/r.width,y:h*=n/r.height};if("touchstart"===t.type)Nt.lastTouches[a.identifier]=l,Nt.touches[a.identifier]=l;else if("touchend"===t.type||"touchmove"===t.type){var u=Nt.touches[a.identifier];u||(u=l),Nt.lastTouches[a.identifier]=u,Nt.touches[a.identifier]=l}return}var d=t.pageX-(s+r.left),p=t.pageY-(o+r.top);d*=i/r.width,p*=n/r.height,Nt.mouseMovementX=d-Nt.mouseX,Nt.mouseMovementY=p-Nt.mouseY,Nt.mouseX=d,Nt.mouseY=p}},resizeListeners:[],updateResizeListeners:function(){var t=e.canvas;Nt.resizeListeners.forEach((function(e){e(t.width,t.height)}))},setCanvasSize:function(t,r,i){var n=e.canvas;Nt.updateCanvasDimensions(n,t,r),i||Nt.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if("undefined"!=typeof SDL){var t=W[SDL.screen>>>2];t|=8388608,U[SDL.screen>>>2]=t}Nt.updateCanvasDimensions(e.canvas),Nt.updateResizeListeners()},setWindowedCanvasSize:function(){if("undefined"!=typeof SDL){var t=W[SDL.screen>>>2];t&=-8388609,U[SDL.screen>>>2]=t}Nt.updateCanvasDimensions(e.canvas),Nt.updateResizeListeners()},updateCanvasDimensions:function(t,r,i){r&&i?(t.widthNative=r,t.heightNative=i):(r=t.widthNative,i=t.heightNative);var n=r,s=i;if(e.forcedAspectRatio&&e.forcedAspectRatio>0&&(n/s>>16),Z(E.buffer),1}catch(e){}}var Ht={};function Vt(){if(!Vt.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"};for(var t in Ht)void 0===Ht[t]?delete e[t]:e[t]=Ht[t];var r=[];for(var t in e)r.push(t+"="+e[t]);Vt.strings=r}return Vt.strings}function zt(e){for(var t=e.split("."),r=0;r<4;r++){var i=Number(t[r]);if(isNaN(i))return null;t[r]=i}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0}function jt(e){return parseInt(e)}var qt={address_map:{id:1,addrs:{},names:{}},lookup_name:function(e){var t,r=zt(e);if(null!==r)return e;if(null!==(r=function(e){var t,r,i,n,s=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jt(t[t.length-4])+256*jt(t[t.length-3]),t[t.length-3]=jt(t[t.length-2])+256*jt(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),i=0,n=0,r=0;r>>2]:-1;n+=_(U[r+4*s>>>2],o<0?void 0:o)}return n},createContext:function(e,t){if(!e.getContextSafariWebGL2Fixed){function i(t,r){var i=e.getContextSafariWebGL2Fixed(t,r);return"webgl"==t==i instanceof WebGLRenderingContext?i:null}e.getContextSafariWebGL2Fixed=e.getContext,e.getContext=i}var r=e.getContext("webgl",t);return r?$t.registerContext(r,t):0},registerContext:function(e,t){var r=$t.getNewId($t.contexts),i={handle:r,attributes:t,version:t.majorVersion,GLctx:e};return e.canvas&&(e.canvas.GLctxObject=i),$t.contexts[r]=i,(void 0===t.enableExtensionsByDefault||t.enableExtensionsByDefault)&&$t.initExtensions(i),r},makeContextCurrent:function(t){return $t.currentContext=$t.contexts[t],e.ctx=rr=$t.currentContext&&$t.currentContext.GLctx,!(t&&!rr)},getContext:function(e){return $t.contexts[e]},deleteContext:function(e){$t.currentContext===$t.contexts[e]&&($t.currentContext=null),"object"==typeof JSEvents&&JSEvents.removeAllHandlersOnTarget($t.contexts[e].GLctx.canvas),$t.contexts[e]&&$t.contexts[e].GLctx.canvas&&($t.contexts[e].GLctx.canvas.GLctxObject=void 0),$t.contexts[e]=null},initExtensions:function(e){if(e||(e=$t.currentContext),!e.initExtensionsDone){e.initExtensionsDone=!0;var t,r=e.GLctx;!function(e){var t=e.getExtension("ANGLE_instanced_arrays");t&&(e.vertexAttribDivisor=function(e,r){t.vertexAttribDivisorANGLE(e,r)},e.drawArraysInstanced=function(e,r,i,n){t.drawArraysInstancedANGLE(e,r,i,n)},e.drawElementsInstanced=function(e,r,i,n,s){t.drawElementsInstancedANGLE(e,r,i,n,s)})}(r),function(e){var t=e.getExtension("OES_vertex_array_object");t&&(e.createVertexArray=function(){return t.createVertexArrayOES()},e.deleteVertexArray=function(e){t.deleteVertexArrayOES(e)},e.bindVertexArray=function(e){t.bindVertexArrayOES(e)},e.isVertexArray=function(e){return t.isVertexArrayOES(e)})}(r),function(e){var t=e.getExtension("WEBGL_draw_buffers");t&&(e.drawBuffers=function(e,r){t.drawBuffersWEBGL(e,r)})}(r),r.disjointTimerQueryExt=r.getExtension("EXT_disjoint_timer_query"),(t=r).multiDrawWebgl=t.getExtension("WEBGL_multi_draw"),(r.getSupportedExtensions()||[]).forEach((function(e){e.includes("lose_context")||e.includes("debug")||r.getExtension(e)}))}}};function Yt(e){return"]"==e.slice(-1)&&e.lastIndexOf("[")}function Xt(e){var t=rr.currentProgram;if(t){var r=t.uniformLocsById[e];return"number"==typeof r&&(t.uniformLocsById[e]=r=rr.getUniformLocation(t,t.uniformArrayNamesById[e]+(r>0?"["+r+"]":""))),r}$t.recordError(1282)}var Zt=[],Jt=[];function Qt(e){return e%4==0&&(e%100!=0||e%400==0)}var Kt=[31,29,31,30,31,30,31,31,30,31,30,31],er=[31,28,31,30,31,30,31,31,30,31,30,31];var tr=function(e,t,r,i){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=xe.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=i};Object.defineProperties(tr.prototype,{read:{get:function(){return!(365&~this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return!(146&~this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return xe.isDir(this.mode)}},isDevice:{get:function(){return xe.isChrdev(this.mode)}}}),xe.FSNode=tr,xe.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);_e=e}(),We=e.BindingError=Ue(Error,"BindingError"),Ge=e.InternalError=Ue(Error,"InternalError"),it.prototype.isAliasOf=function(e){if(!(this instanceof it))return!1;if(!(e instanceof it))return!1;for(var t=this.$$.ptrType.registeredClass,r=this.$$.ptr,i=e.$$.ptrType.registeredClass,n=e.$$.ptr;t.baseClass;)r=t.upcast(r),t=t.baseClass;for(;i.baseClass;)n=i.upcast(n),i=i.baseClass;return t===i&&r===n},it.prototype.clone=function(){if(this.$$.ptr||je(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e,t=rt(Object.create(Object.getPrototypeOf(this),{$$:{value:(e=this.$$,{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType})}}));return t.$$.count.value+=1,t.$$.deleteScheduled=!1,t},it.prototype.delete=function(){this.$$.ptr||je(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),$e(this),Ye(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},it.prototype.isDeleted=function(){return!this.$$.ptr},it.prototype.deleteLater=function(){return this.$$.ptr||je(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),Je.push(this),1===Je.length&&Ke&&Ke(Qe),this.$$.deleteScheduled=!0,this},e.getInheritedInstanceCount=function(){return Object.keys(et).length},e.getLiveInheritedInstances=function(){var e=[];for(var t in et)et.hasOwnProperty(t)&&e.push(et[t]);return e},e.flushPendingDeletes=Qe,e.setDelayFunction=function(e){Ke=e,Je.length&&Ke&&Ke(Qe)},dt.prototype.getPointee=function(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e},dt.prototype.destructor=function(e){this.rawDestructor&&this.rawDestructor(e)},dt.prototype.argPackAdvance=8,dt.prototype.readValueFromPointer=ut,dt.prototype.deleteObject=function(e){null!==e&&e.delete()},dt.prototype.fromWireType=function(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var r=function(e,t){return t=function(e,t){for(void 0===t&&Ne("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),et[t]}(this.registeredClass,t);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=t,r.$$.smartPtr=e,r.clone();var i=r.clone();return this.destructor(e),i}function n(){return this.isSmartPointer?tt(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):tt(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var s,o=this.registeredClass.getActualType(t),a=Ze[o];if(!a)return n.call(this);s=this.isConst?a.constPointerType:a.pointerType;var c=Xe(t,this.registeredClass,s.registeredClass);return null===c?n.call(this):this.isSmartPointer?tt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c,smartPtrType:this,smartPtr:e}):tt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c})},ft=e.UnboundTypeError=Ue(Error,"UnboundTypeError"),e.count_emval_handles=function(){for(var e=0,t=5;t0?r:R(e)+1,n=new Array(i),s=O(e,n,0,n.length);return t&&(n.length=s),n}var hr,lr={na:function(){return e.HEAP8.length},g:function(e,t,r,i){ae("Assertion failed: "+_(e)+", at: "+[t?_(t):"unknown filename",r,i?_(i):"unknown function"])},b:function(e){return ur(e+24)+24},c:function(e,t,r){throw new ye(e).init(t,r),e},Z:function(e,t){try{return e=ke.getStr(e),xe.chmod(e,t),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},_:function(e,t,r,i){try{if(t=ke.getStr(t),t=ke.calculateAt(e,t),-8&r)return-28;var n=xe.lookupPath(t,{follow:!0}).node;if(!n)return-44;var s="";return 4&r&&(s+="r"),2&r&&(s+="w"),1&r&&(s+="x"),s&&xe.nodePermissions(n,s)?-2:0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},r:function(e,t,r){ke.varargs=r;try{var i=ke.getStreamFromFD(e);switch(t){case 0:return(n=ke.get())<0?-28:xe.createStream(i,n).fd;case 1:case 2:case 6:case 7:return 0;case 3:return i.flags;case 4:var n=ke.get();return i.flags|=n,0;case 5:return n=ke.get(),M[n+0>>>1]=2,0;case 16:case 8:default:return-28;case 9:return 28,U[pr()>>>2]=28,-1}}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},Q:function(e,t){try{var r=ke.getStreamFromFD(e);return ke.doStat(xe.stat,r.path,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},I:function(e,t,r){try{var i=ke.getStreamFromFD(e);i.getdents||(i.getdents=xe.readdir(i.path));for(var n=280,s=0,o=xe.llseek(i,0,1),a=Math.floor(o/n);a>>0,(le=c,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[t+s>>>2]=ue[0],U[t+s+4>>>2]=ue[1],ue=[(a+1)*n>>>0,(le=(a+1)*n,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[t+s+8>>>2]=ue[0],U[t+s+12>>>2]=ue[1],M[t+s+16>>>1]=280,L[t+s+18>>>0]=h,D(l,t+s+19,256),s+=n,a+=1}return xe.llseek(i,a*n,0),s}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},$:function(e,t,r){ke.varargs=r;try{var i=ke.getStreamFromFD(e);switch(t){case 21509:case 21505:case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:case 21523:case 21524:return i.tty?0:-59;case 21519:if(!i.tty)return-59;var n=ke.get();return U[n>>>2]=0,0;case 21520:return i.tty?-28:-59;case 21531:return n=ke.get(),xe.ioctl(i,t,n);default:ae("bad ioctl syscall "+t)}}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},N:function(e,t){try{return e=ke.getStr(e),ke.doStat(xe.lstat,e,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},K:function(e,t,r){try{return t=ke.getStr(t),t=ke.calculateAt(e,t),"/"===(t=Se.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),xe.mkdir(t,r,0),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},O:function(e,t,r,i){try{t=ke.getStr(t);var n=256&i,s=4096&i;return i&=-4353,t=ke.calculateAt(e,t,s),ke.doStat(n?xe.lstat:xe.stat,t,r)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},v:function(e,t,r,i){ke.varargs=i;try{t=ke.getStr(t),t=ke.calculateAt(e,t);var n=i?ke.get():0;return xe.open(t,r,n).fd}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},H:function(e){try{return e=ke.getStr(e),xe.rmdir(e),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},P:function(e,t){try{return e=ke.getStr(e),ke.doStat(xe.stat,e,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},F:function(e,t,r){try{return t=ke.getStr(t),t=ke.calculateAt(e,t),0===r?xe.unlink(t):512===r?xe.rmdir(t):ae("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},W:function(e){},Y:function(e,t){ae(Ce)},X:function(e,t){ae(Ce)},B:function(e,t,r,i,n){},ba:function(e,t,r,i,n){var s=Ae(r);ze(e,{name:t=Oe(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?i:n},argPackAdvance:8,readValueFromPointer:function(e){var i;if(1===r)i=L;else if(2===r)i=M;else{if(4!==r)throw new TypeError("Unknown boolean type size: "+t);i=U}return this.fromWireType(i[e>>>s])},destructorFunction:null})},d:function(t,r,i,n,s,o,a,c,h,l,u,d,p){u=Oe(u),o=pt(s,o),c&&(c=pt(a,c)),l&&(l=pt(h,l)),p=pt(d,p);var f=Me(u);st(f,(function(){vt("Cannot construct "+u+" due to unbound types",[n])})),Ve([t,r,i],n?[n]:[],(function(r){var i,s;r=r[0],s=n?(i=r.registeredClass).instancePrototype:it.prototype;var a=Ie(f,(function(){if(Object.getPrototypeOf(this)!==h)throw new We("Use 'new' to construct "+u);if(void 0===d.constructor_body)throw new We(u+" has no accessible constructor");var e=d.constructor_body[arguments.length];if(void 0===e)throw new We("Tried to invoke ctor of "+u+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(d.constructor_body).toString()+") parameters instead!");return e.apply(this,arguments)})),h=Object.create(s,{constructor:{value:a}});a.prototype=h;var d=new ot(u,a,h,p,i,o,c,l),g=new dt(u,d,!0,!1,!1),v=new dt(u+"*",d,!1,!1,!1),m=new dt(u+" const*",d,!1,!0,!1);return Ze[t]={pointerType:v,constPointerType:m},function(t,r,i){e.hasOwnProperty(t)||He("Replacing nonexistant public symbol"),e[t].overloadTable,e[t]=r,e[t].argCount=i}(f,a),[g,v,m]}))},f:function(e,t,r,i,n,s,o){var a=bt(r,i);t=Oe(t),s=pt(n,s),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t;function n(){vt("Cannot call "+i+" due to unbound types",a)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]);var c=e.registeredClass.constructor;return void 0===c[t]?(n.argCount=r-1,c[t]=n):(nt(c,t,i),c[t].overloadTable[r-1]=n),Ve([],a,(function(e){var n=[e[0],null].concat(e.slice(1)),a=St(i,n,null,s,o);return void 0===c[t].overloadTable?(a.argCount=r-1,c[t]=a):c[t].overloadTable[r-1]=a,[]})),[]}))},e:function(e,t,r,i,n,s){C(t>0);var o=bt(t,r);n=pt(i,n),Ve([],[e],(function(e){var r="constructor "+(e=e[0]).name;if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new We("Cannot register multiple constructors with identical number of parameters ("+(t-1)+") for class '"+e.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return e.registeredClass.constructor_body[t-1]=()=>{vt("Cannot construct "+e.name+" due to unbound types",o)},Ve([],o,(function(i){return i.splice(1,0,null),e.registeredClass.constructor_body[t-1]=St(r,i,null,n,s),[]})),[]}))},a:function(e,t,r,i,n,s,o,a){var c=bt(r,i);t=Oe(t),s=pt(n,s),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t;function n(){vt("Cannot call "+i+" due to unbound types",c)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),a&&e.registeredClass.pureVirtualFunctions.push(t);var h=e.registeredClass.instancePrototype,l=h[t];return void 0===l||void 0===l.overloadTable&&l.className!==e.name&&l.argCount===r-2?(n.argCount=r-2,n.className=e.name,h[t]=n):(nt(h,t,i),h[t].overloadTable[r-2]=n),Ve([],c,(function(n){var a=St(i,n,e,s,o);return void 0===h[t].overloadTable?(a.argCount=r-2,h[t]=a):h[t].overloadTable[r-2]=a,[]})),[]}))},k:function(e,t,r,i,n,s,o,a,c,h){t=Oe(t),n=pt(i,n),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t,l={get:function(){vt("Cannot access "+i+" due to unbound types",[r,o])},enumerable:!0,configurable:!0};return l.set=c?()=>{vt("Cannot access "+i+" due to unbound types",[r,o])}:e=>{Ne(i+" is a read-only property")},Object.defineProperty(e.registeredClass.instancePrototype,t,l),Ve([],c?[r,o]:[r],(function(r){var o=r[0],l={get:function(){var t=wt(this,e,i+" getter");return o.fromWireType(n(s,t))},enumerable:!0};if(c){c=pt(a,c);var u=r[1];l.set=function(t){var r=wt(this,e,i+" setter"),n=[];c(h,r,u.toWireType(n,t)),yt(n)}}return Object.defineProperty(e.registeredClass.instancePrototype,t,l),[]})),[]}))},aa:function(e,t){ze(e,{name:t=Oe(t),fromWireType:function(e){var t=kt.toValue(e);return xt(e),t},toWireType:function(e,t){return kt.toHandle(t)},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:null})},i:function(e,t,r,i){var n=Ae(r);function s(){}t=Oe(t),s.values={},ze(e,{name:t,constructor:s,fromWireType:function(e){return this.constructor.values[e]},toWireType:function(e,t){return t.value},argPackAdvance:8,readValueFromPointer:Ct(t,n,i),destructorFunction:null}),st(t,s)},h:function(e,t,r){var i=Pt(e,"enum");t=Oe(t);var n=i.constructor,s=Object.create(i.constructor.prototype,{value:{value:r},constructor:{value:Ie(i.name+"_"+t,(function(){}))}});n.values[r]=s,n[t]=s},y:function(e,t,r){var i=Ae(r);ze(e,{name:t=Oe(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:_t(t,i),destructorFunction:null})},l:function(e,t,r,i,n){t=Oe(t),-1===n&&(n=4294967295);var s=Ae(r),o=e=>e;if(0===i){var a=32-8*r;o=e=>e<>>a}var c=t.includes("unsigned");ze(e,{name:t,fromWireType:o,toWireType:c?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:Ot(t,s,0!==i),destructorFunction:null})},j:function(e,t,r){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function n(e){var t=W,r=t[(e>>=2)>>>0],n=t[e+1>>>0];return new i(F,n,r)}ze(e,{name:r=Oe(r),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{ignoreDuplicateRegistrations:!0})},x:function(e,t){var r="std::string"===(t=Oe(t));ze(e,{name:t,fromWireType:function(e){var t,i=W[e>>>2];if(r)for(var n=e+4,s=0;s<=i;++s){var o=e+4+s;if(s==i||0==B[o>>>0]){var a=_(n,o-n);void 0===t?t=a:(t+=String.fromCharCode(0),t+=a),n=o+1}}else{var c=new Array(i);for(s=0;s>>0]);t=c.join("")}return dr(e),t},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i="string"==typeof t;i||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||Ne("Cannot pass non-string to std::string");var n=(r&&i?()=>R(t):()=>t.length)(),s=ur(4+n+1);if(W[(s>>>=0)>>>2]=n,r&&i)D(t,s+4,n+1);else if(i)for(var o=0;o255&&(dr(s),Ne("String has UTF-16 code units that do not fit in 8 bits")),B[s+4+o>>>0]=a}else for(o=0;o>>0]=t[o];return null!==e&&e.push(dr,s),s},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:function(e){dr(e)}})},s:function(e,t,r){var i,n,s,o,a;r=Oe(r),2===t?(i=V,n=z,o=j,s=()=>I,a=1):4===t&&(i=q,n=$,o=Y,s=()=>W,a=2),ze(e,{name:r,fromWireType:function(e){for(var r,n=W[e>>>2],o=s(),c=e+4,h=0;h<=n;++h){var l=e+4+h*t;if(h==n||0==o[l>>>a]){var u=i(c,l-c);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),c=l+t}}return dr(e),r},toWireType:function(e,i){"string"!=typeof i&&Ne("Cannot pass non-string to C++ string type "+r);var s=o(i),c=ur(4+s+t);return W[(c>>>=0)>>>2]=s>>a,n(i,c+4,s+t),null!==e&&e.push(dr,c),c},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:function(e){dr(e)}})},ca:function(e,t){ze(e,{isVoid:!0,name:t=Oe(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},T:function(){return Date.now()},S:function(){return!0},n:function(e,t,r){e=kt.toValue(e),t=Pt(t,"emval::as");var i=[],n=kt.toHandle(i);return U[r>>>2]=n,t.toWireType(i,e)},sa:function(e,t,r,i,n){return(e=Ft[e])(t=kt.toValue(t),r=Rt(r),function(e){var t=[];return U[e>>>2]=kt.toHandle(t),t}(i),n)},wa:xt,ta:function(e){return 0===e?kt.toHandle(Lt()):(e=Rt(e),kt.toHandle(Lt()[e]))},ra:function(e,t){var r=function(e,t){for(var r=new Array(e),i=0;i>>2],"parameter "+i);return r}(e,t),i=r[0],n=i.name+"_$"+r.slice(1).map((function(e){return e.name})).join("_")+"$",s=Mt[n];if(void 0!==s)return s;for(var o=["retType"],a=[i],c="",h=0;h4&&(Tt[e].refcount+=1)},qa:function(e){return kt.toHandle(Rt(e))},ua:function(e){yt(kt.toValue(e)),xt(e)},o:function(e,t,r){e=kt.toValue(e),t=kt.toValue(t),r=kt.toValue(r),e[t]=r},m:function(e,t){var r=(e=Pt(e,"_emval_take_value")).readValueFromPointer(t);return kt.toHandle(r)},va:function(e){return e=kt.toValue(e),kt.toHandle(typeof e)},U:function(e,t){var r=new Date(1e3*U[e>>>2]);U[t>>>2]=r.getSeconds(),U[t+4>>>2]=r.getMinutes(),U[t+8>>>2]=r.getHours(),U[t+12>>>2]=r.getDate(),U[t+16>>>2]=r.getMonth(),U[t+20>>>2]=r.getFullYear()-1900,U[t+24>>>2]=r.getDay();var i=new Date(r.getFullYear(),0,1),n=(r.getTime()-i.getTime())/864e5|0;U[t+28>>>2]=n,U[t+36>>>2]=-60*r.getTimezoneOffset();var s=new Date(r.getFullYear(),6,1).getTimezoneOffset(),o=i.getTimezoneOffset(),a=0|(s!=o&&r.getTimezoneOffset()==Math.min(o,s));U[t+32>>>2]=a},J:function(e,t,r,i,n,s){try{e>>>=0;var o=xe.getStream(n);o&&(2&r&&ke.doMsync(e,o,t,i,s),xe.munmap(o))}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},V:function e(t,r,i){e.called||(e.called=!0,function(e,t,r){var i=(new Date).getFullYear(),n=new Date(i,0,1),s=new Date(i,6,1),o=n.getTimezoneOffset(),a=s.getTimezoneOffset(),c=Math.max(o,a);function h(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}U[e>>>2]=60*c,U[t>>>2]=Number(o!=a);var l=h(n),u=h(s),d=X(l),p=X(u);a>>2]=d,W[r+4>>>2]=p):(W[r>>>2]=p,W[r+4>>>2]=d)}(t,r,i))},u:function(){ae("")},G:function(){return 4294901760},da:function(e,t,r){(0|e)===e&&(e=_(e)),e=be.resolve(e);var i=ir[e];if(i){var n=i.getContext("2d").getImageData(0,0,i.width,i.height),s=ur(i.width*i.height*4);return B.set(n.data,s>>>0),U[t>>>2]=i.width,U[r>>>2]=i.height,s}return 0},R:function(e,t,r){B.copyWithin(e>>>0,t>>>0,t+r>>>0)},E:function(e){var t,r=B.length,i=4294901760;if((e>>>=0)>i)return!1;for(var n=1;n<=4;n*=2){var s=r*(1+.2/n);if(s=Math.min(s,e+100663296),Gt(Math.min(i,(t=Math.max(e,s))+(65536-t%65536)%65536)))return!0}return!1},L:function(e,t){var r=0;return Vt().forEach((function(i,n){var s=t+r;W[e+4*n>>>2]=s,function(e,t,r){for(var i=0;i>>0]=e.charCodeAt(i);L[t>>>0]=0}(i,s),r+=i.length+1})),0},M:function(e,t){var r=Vt();W[e>>>2]=r.length;var i=0;return r.forEach((function(e){i+=e.length+1})),W[t>>>2]=i,0},oa:function(t){!function(t,r){var i;x=t,x=i=t,te()||(e.onExit&&e.onExit(i),k=!0),p(i,new yr(i))}(t)},p:function(e){try{var t=ke.getStreamFromFD(e);return xe.close(t),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},w:function(e,t,r,i){try{var n=function(e,t,r,i){for(var n=0,s=0;s>>2],a=W[t+4>>>2];t+=8;var c=xe.read(e,L,o,a,undefined);if(c<0)return-1;if(n+=c,c>>2]=n,0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},A:function(e,t,r,i,n){try{var s=(c=r)+2097152>>>0<4194305-!!(a=t)?(a>>>0)+4294967296*c:NaN;if(isNaN(s))return 61;var o=ke.getStreamFromFD(e);return xe.llseek(o,s,i),ue=[o.position>>>0,(le=o.position,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[n>>>2]=ue[0],U[n+4>>>2]=ue[1],o.getdents&&0===s&&0===i&&(o.getdents=null),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}var a,c},q:function(e,t,r,i){try{var n=function(e,t,r,i){for(var n=0,s=0;s>>2],a=W[t+4>>>2];t+=8;var c=xe.write(e,L,o,a,undefined);if(c<0)return-1;n+=c}return n}(ke.getStreamFromFD(e),t,r);return W[i>>>2]=n,0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},pa:function(e){return function(e){var t=ur(20),r=ur(e.length+1);D(e,r,e.length+1),W[t>>>2]=r;var i=ur(4);W[i>>>2]=0,W[t+4>>>2]=i,U[t+8>>>2]=2,U[t+12>>>2]=4;var n=ur(12);return W[n>>>2]=n+8,W[n+4>>>2]=0,U[n+8>>>2]=zt(qt.lookup_name(e)),W[t+16>>>2]=n,t}(_(e))},ma:function(e,t){if(t=_(t),e=$t.programs[e]){!function(e){var t,r,i=e.uniformLocsById,n=e.uniformSizeAndIdsByName;if(!i)for(e.uniformLocsById=i={},e.uniformArrayNamesById={},t=0;t0?o.slice(0,c):o,l=e.uniformIdCounter;for(e.uniformIdCounter+=a,n[h]=[a,l],r=0;r0&&(i=jt(t.slice(s+1))>>>0,n=t.slice(0,s));var o=e.uniformSizeAndIdsByName[n];if(o&&i>>2],i[n+1]=N[r+(4*n+4)>>>2];else i=N.subarray(r>>>2,r+8*t>>>2);rr.uniform2fv(Xt(e),i)},ja:function(e,t,r){if(t<=144)for(var i=Jt[2*t-1],n=0;n<2*t;n+=2)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2];else i=U.subarray(r>>>2,r+8*t>>>2);rr.uniform2iv(Xt(e),i)},fa:function(e,t,r){if(t<=96)for(var i=Zt[3*t-1],n=0;n<3*t;n+=3)i[n]=N[r+4*n>>>2],i[n+1]=N[r+(4*n+4)>>>2],i[n+2]=N[r+(4*n+8)>>>2];else i=N.subarray(r>>>2,r+12*t>>>2);rr.uniform3fv(Xt(e),i)},ia:function(e,t,r){if(t<=96)for(var i=Jt[3*t-1],n=0;n<3*t;n+=3)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2],i[n+2]=U[r+(4*n+8)>>>2];else i=U.subarray(r>>>2,r+12*t>>>2);rr.uniform3iv(Xt(e),i)},ea:function(e,t,r){if(t<=72){var i=Zt[4*t-1],n=N;r>>=2;for(var s=0;s<4*t;s+=4){var o=r+s;i[s]=n[o>>>0],i[s+1]=n[o+1>>>0],i[s+2]=n[o+2>>>0],i[s+3]=n[o+3>>>0]}}else i=N.subarray(r>>>2,r+16*t>>>2);rr.uniform4fv(Xt(e),i)},ha:function(e,t,r){if(t<=72)for(var i=Jt[4*t-1],n=0;n<4*t;n+=4)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2],i[n+2]=U[r+(4*n+8)>>>2],i[n+3]=U[r+(4*n+12)>>>2];else i=U.subarray(r>>>2,r+16*t>>>2);rr.uniform4iv(Xt(e),i)},C:function(e){},D:function(e,t,r,i){return function(e,t,r,i){var n=U[i+40>>>2],s={tm_sec:U[i>>>2],tm_min:U[i+4>>>2],tm_hour:U[i+8>>>2],tm_mday:U[i+12>>>2],tm_mon:U[i+16>>>2],tm_year:U[i+20>>>2],tm_wday:U[i+24>>>2],tm_yday:U[i+28>>>2],tm_isdst:U[i+32>>>2],tm_gmtoff:U[i+36>>>2],tm_zone:n?_(n):""},o=_(r),a={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var c in a)o=o.replace(new RegExp(c,"g"),a[c]);var h=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["January","February","March","April","May","June","July","August","September","October","November","December"];function u(e,t,r){for(var i="number"==typeof e?e.toString():e||"";i.length0?1:0}var i;return 0===(i=r(e.getFullYear()-t.getFullYear()))&&0===(i=r(e.getMonth()-t.getMonth()))&&(i=r(e.getDate()-t.getDate())),i}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function g(e){var t=function(e,t){for(var r=new Date(e.getTime());t>0;){var i=Qt(r.getFullYear()),n=r.getMonth(),s=(i?Kt:er)[n];if(!(t>s-r.getDate()))return r.setDate(r.getDate()+t),r;t-=s-r.getDate()+1,r.setDate(1),n<11?r.setMonth(n+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r}(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),i=new Date(t.getFullYear()+1,0,4),n=f(r),s=f(i);return p(n,t)<=0?p(s,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var v={"%a":function(e){return h[e.tm_wday].substring(0,3)},"%A":function(e){return h[e.tm_wday]},"%b":function(e){return l[e.tm_mon].substring(0,3)},"%B":function(e){return l[e.tm_mon]},"%C":function(e){return d((e.tm_year+1900)/100|0,2)},"%d":function(e){return d(e.tm_mday,2)},"%e":function(e){return u(e.tm_mday,2," ")},"%g":function(e){return g(e).toString().substring(2)},"%G":function(e){return g(e)},"%H":function(e){return d(e.tm_hour,2)},"%I":function(e){var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":function(e){return d(e.tm_mday+function(e,t){for(var r=0,i=0;i<=t;r+=e[i++]);return r}(Qt(e.tm_year+1900)?Kt:er,e.tm_mon-1),3)},"%m":function(e){return d(e.tm_mon+1,2)},"%M":function(e){return d(e.tm_min,2)},"%n":function(){return"\n"},"%p":function(e){return e.tm_hour>=0&&e.tm_hour<12?"AM":"PM"},"%S":function(e){return d(e.tm_sec,2)},"%t":function(){return"\t"},"%u":function(e){return e.tm_wday||7},"%U":function(e){var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":function(e){var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&Qt(e.tm_year)||(t=1)}}else{t=52;var i=(e.tm_wday+7-e.tm_yday-1)%7;(4==i||5==i&&Qt(e.tm_year%400-1))&&t++}return d(t,2)},"%w":function(e){return e.tm_wday},"%W":function(e){var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":function(e){return(e.tm_year+1900).toString().substring(2)},"%Y":function(e){return e.tm_year+1900},"%z":function(e){var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":function(e){return e.tm_zone},"%%":function(){return"%"}};for(var c in o=o.replace(/%%/g,"\0\0"),v)o.includes(c)&&(o=o.replace(new RegExp(c,"g"),v[c](s)));var m=cr(o=o.replace(/\0\0/g,"%"),!1);return m.length>t?0:(function(e,t){L.set(e,t>>>0)}(m,e),m.length-1)}(e,t,r,i)}},ur=(function(){var t={a:lr};function r(t,r){var i,n=t.exports;e.asm=n,Z((E=e.asm.xa).buffer),J=e.asm.Ea,i=e.asm.ya,K.unshift(i),oe()}function n(e){r(e.instance)}function o(e){return function(){if(!b&&(f||g)){if("function"==typeof fetch&&!pe(ce))return fetch(ce,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+ce+"'";return e.arrayBuffer()})).catch((function(){return fe(ce)}));if(s)return new Promise((function(e,t){s(ce,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return fe(ce)}))}().then((function(e){return WebAssembly.instantiate(e,t)})).then((function(e){return e})).then(e,(function(e){S("failed to asynchronously prepare wasm: "+e),ae(e)}))}if(se(),e.instantiateWasm)try{return e.instantiateWasm(t,r)}catch(e){return S("Module.instantiateWasm callback failed with error: "+e),!1}(b||"function"!=typeof WebAssembly.instantiateStreaming||de(ce)||pe(ce)||v||"function"!=typeof fetch?o(n):fetch(ce,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,t).then(n,(function(e){return S("wasm streaming compile failed: "+e),S("falling back to ArrayBuffer instantiation"),o(n)}))}))).catch(i)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.ya).apply(null,arguments)},e._malloc=function(){return(ur=e._malloc=e.asm.za).apply(null,arguments)}),dr=e._free=function(){return(dr=e._free=e.asm.Aa).apply(null,arguments)},pr=e.___errno_location=function(){return(pr=e.___errno_location=e.asm.Ba).apply(null,arguments)},fr=e.___getTypeName=function(){return(fr=e.___getTypeName=e.asm.Ca).apply(null,arguments)},gr=(e.___embind_register_native_and_builtin_types=function(){return(e.___embind_register_native_and_builtin_types=e.asm.Da).apply(null,arguments)},e._htons=function(){return(gr=e._htons=e.asm.Fa).apply(null,arguments)}),vr=e._emscripten_builtin_memalign=function(){return(vr=e._emscripten_builtin_memalign=e.asm.Ga).apply(null,arguments)},mr=e.___cxa_is_pointer_type=function(){return(mr=e.___cxa_is_pointer_type=e.asm.Ha).apply(null,arguments)};function yr(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function Sr(r){function i(){hr||(hr=!0,e.calledRun=!0,k||(e.noFSInit||xe.init.initialized||xe.init(),xe.ignorePermissions=!1,we.init(),ge(K),t(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),function(){if(e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;)t=e.postRun.shift(),ee.unshift(t);var t;ge(ee)}()))}r=r||u,re>0||(function(){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)t=e.preRun.shift(),Q.unshift(t);var t;ge(Q)}(),re>0||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),i()}),1)):i()))}if(e.dynCall_jiji=function(){return(e.dynCall_jiji=e.asm.Ia).apply(null,arguments)},e.dynCall_viijii=function(){return(e.dynCall_viijii=e.asm.Ja).apply(null,arguments)},e.dynCall_iiiiij=function(){return(e.dynCall_iiiiij=e.asm.Ka).apply(null,arguments)},e.dynCall_iiiiijj=function(){return(e.dynCall_iiiiijj=e.asm.La).apply(null,arguments)},e.dynCall_iiiiiijj=function(){return(e.dynCall_iiiiiijj=e.asm.Ma).apply(null,arguments)},e.dynCall_viiiiji=function(){return(e.dynCall_viiiiji=e.asm.Na).apply(null,arguments)},e.dynCall_viiijj=function(){return(e.dynCall_viiijj=e.asm.Oa).apply(null,arguments)},e.FS=xe,ne=function e(){hr||Sr(),hr||(ne=e)},e.run=Sr,e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Sr(),e.ready});const _e=Ae;class Oe{constructor(e){this.occ=e,this.hashesFromPreviousRun={},this.usedHashes={},this.argCache={}}cleanAllCache(){Object.keys(this.usedHashes).forEach((e=>{if(this.argCache[e])try{const t=this.argCache[e];this.occ.BRepTools.Clean(t,!0),this.occ.BRepTools.CleanGeometry(t),t.delete()}catch(e){}})),this.argCache={},this.usedHashes={},this.hashesFromPreviousRun={}}cleanCacheForHash(e){if(this.argCache[e])try{const t=this.argCache[e];this.occ.BRepTools.Clean(t,!0),this.occ.BRepTools.CleanGeometry(t),t.delete()}catch(e){}delete this.argCache[e],delete this.usedHashes[e],delete this.hashesFromPreviousRun[e]}cleanUpCache(){}isOCCTObject(e){return null!=e&&!Array.isArray(e)&&void 0!==e.$$||Array.isArray(e)&&e.length>0&&void 0!==e[0].$$}cacheOp(e,t){let r=null;const i=this.computeHash(e);this.usedHashes[i]=i,this.hashesFromPreviousRun[i]=i;const n=this.checkCache(i);if(n)this.isOCCTObject(n)?(r=n,r.hash=n.hash):n.value&&(r=n.value);else if(r=t(),Array.isArray(r)&&this.isOCCTObject(r))r.forEach(((t,r)=>{const i=this.computeHash(Object.assign(Object.assign({},e),{index:r}));t.hash=i,this.addToCache(i,t)}));else if(this.isOCCTObject(r))r.hash=i,this.addToCache(i,r);else if(r.compound&&r.data&&r.shapes&&r.shapes.length>0){const t=r,n=this.computeHash(Object.assign(Object.assign({},e),{index:"compound"}));t.compound.hash=n,this.addToCache(n,t.compound),t.shapes.forEach(((t,r)=>{const i=this.computeHash(Object.assign(Object.assign({},e),{index:r}));t.shape.hash=i,this.addToCache(i,t.shape)})),this.addToCache(i,{value:t})}else this.addToCache(i,{value:r});return r}checkCache(e){return this.argCache[e]||null}addToCache(e,t){const r=t;return r.hash=e,this.argCache[e]=r,e}computeHash(e,t){let r=JSON.stringify(e);r=r.replace(/(\"ptr\"\:(-?[0-9]*?)\,)/g,""),r=r.replace(/(\"ptr\"\:(-?[0-9]*))/g,""),r.includes("ptr")&&console.error("YOU DONE MESSED UP YOUR REGEX.");const i=Math.random.toString()+r;return t?i:this.stringToHash(i)}stringToHash(e){let t=0;if(0===e.length)return t;for(let r=0;re.hash!==t.hash||e.ptr!==t.ptr))}dupShape(e){return e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?this.occ.TopoDS.Wire_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?this.occ.TopoDS.Shell_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?this.occ.TopoDS.Edge_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?this.occ.TopoDS.Solid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?this.occ.TopoDS.Face_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.occ.TopoDS.Compound_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.occ.TopoDS.CompSolid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?this.occ.TopoDS.Vertex_1(e):void 0}}let De,Re,Fe;class Le{static distributeBetweenBounds(e,t,r,i=!1){const n=[];let s=r;for(i&&n.push(s);s>t;)s-=e,n.push(s);return n}static computeSideA(e,t){const r=e*Math.PI/180,i=t/Math.cos(r),n=Math.pow(i,2)-Math.pow(t,2);return Math.sqrt(n)}static computeSideAFromHypotenuseAndAngle(e,t){const r=e*Math.PI/180;return t*Math.sin(r)}static computeHypotenuse(e,t){return t/Math.cos(e*Math.PI/180)}}var Be,Me,Ie,Ue,We,Ne;!function(e){e.low="low",e.middle="middle",e.high="high"}(Be||(Be={}));class Ge{constructor(){this.lod=Be.low}}class He{}class Ve{constructor(e,t,r,i,n,s,o,a,c){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.addRadiusNarrow=r),void 0!==i&&(this.addRadiusWide=i),void 0!==n&&(this.addMiddleHeight=n),void 0!==s&&(this.addTopHeight=s),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==c&&(this.origin=c)}}class ze{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class je{}class qe{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=Be.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==r&&(this.archCenterThickness=r),void 0!==i&&(this.edgesThickness=i),void 0!==n&&(this.thickness=n),void 0!==s&&(this.baseHeight=s),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.origin=h),void 0!==l&&(this.direction=l),void 0!==u&&(this.scale=u)}}class $e{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class Ye{}class Xe{}class Ze{}class Je{constructor(e,t,r,i,n,s,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==r&&(this.fullModel=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.decorationThickness=n),void 0!==s&&(this.rotation=s),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class Qe{constructor(){this.type="parametric-model",this.name="eternalLove"}}class Ke{}class et{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==r&&(this.radiusTopOffset=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.fillet=n),void 0!==s&&(this.nrOfHandles=s),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.scale=h),void 0!==l&&(this.origin=l),void 0!==u&&(this.direction=u)}}class tt{constructor(){this.type="parametric-model",this.name="calmCup"}}class rt{}class it{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y,S,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==r&&(this.radiusTopOffset=r),void 0!==i&&(this.radiusMidOffset=i),void 0!==n&&(this.rotationTopAngle=n),void 0!==s&&(this.rotationMidAngle=s),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==c&&(this.nrSkinCellDivisionsTop=c),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==l&&(this.skinCellOuterHeight=l),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==p&&(this.skinCellTopHeight=p),void 0!==f&&(this.thickness=f),void 0!==g&&(this.bottomThickness=g),void 0!==v&&(this.precision=v),void 0!==m&&(this.rotation=m),void 0!==y&&(this.scale=y),void 0!==S&&(this.origin=S),void 0!==b&&(this.direction=b)}}class nt{constructor(){this.type="parametric-model",this.name="dragonCup"}}class st{}class ot{}class at{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==r&&(this.widthBack=r),void 0!==i&&(this.widthFront=i),void 0!==n&&(this.length=n),void 0!==s&&(this.backOffset=s),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==c&&(this.filletRadius=c),void 0!==h&&(this.phoneHeight=h),void 0!==l&&(this.phoneWidth=l),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdges=p),void 0!==f&&(this.rotation=f),void 0!==g&&(this.scale=g),void 0!==v&&(this.origin=v),void 0!==m&&(this.direction=m)}}class ct{constructor(){this.type="parametric-model",this.name="phoneNest"}}class ht extends He{}class lt{}class ut extends He{}class dt{}class pt{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class ft{}class gt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==r&&(this.nrSides=r),void 0!==i&&(this.nrOffsets=i),void 0!==n&&(this.height=n),void 0!==s&&(this.coverHeight=s),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==c&&(this.radiusOffset=c),void 0!==h&&(this.thickness=h),void 0!==l&&(this.ornamentalThickness=l),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==p&&(this.fillet=p),void 0!==f&&(this.precision=f),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==m&&(this.origin=m),void 0!==y&&(this.direction=y)}}class vt{constructor(){this.type="parametric-model",this.name="spicyBox"}}class mt{}class yt{}class St{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y,S,b,w,E,T,x,k,C,P,A,_){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=Be.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==r&&(this.terraceWidth=r),void 0!==i&&(this.widthSecondWing=i),void 0!==n&&(this.lengthSecondWing=n),void 0!==s&&(this.heightWalls=s),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==c&&(this.roofOffset=c),void 0!==h&&(this.roofInsideOverhang=h),void 0!==l&&(this.roofMaxDistAttachmentBeams=l),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==p&&(this.roofOutsideOverhang=p),void 0!==f&&(this.columnSize=f),void 0!==g&&(this.ceilingBeamHeight=g),void 0!==v&&(this.ceilingBeamWidth=v),void 0!==m&&(this.nrCeilingBeamsBetweenColumns=m),void 0!==y&&(this.distBetweenColumns=y),void 0!==S&&(this.floorHeight=S),void 0!==b&&(this.groundLevel=b),void 0!==w&&(this.facadePanelThickness=w),void 0!==E&&(this.windowWidthOffset=E),void 0!==T&&(this.windowHeightOffset=T),void 0!==x&&(this.windowFrameThickness=x),void 0!==k&&(this.windowGlassFrameThickness=k),void 0!==C&&(this.lod=C),void 0!==P&&(this.skinOpacity=P),void 0!==A&&(this.rotation=A),void 0!==_&&(this.origin=_)}}class bt{constructor(){this.type="parametric-model",this.name="zenHideout"}}class wt{}class Et{}class Tt{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class xt{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class kt extends xt{}class Ct extends Tt{}class Pt{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class At{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class _t extends Pt{}class Ot extends At{}class Dt{}class Rt{}class Ft{}class Lt{}class Bt{}class Mt{}class It{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class Ut extends It{}class Wt{}class Nt{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=Be.high,this.center=[0,0,0],this.direction=[0,1,0]}}class Gt extends Nt{}class Ht{}class Vt{}class zt{constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class jt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==r&&(this.interiorHeight=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.holeDiameter=n),void 0!==s&&(this.holeDistToBottom=s),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==c&&(this.baseAttachmentHeight=c),void 0!==h&&(this.roofOverhang=h),void 0!==l&&(this.rotation=l),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class qt{constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class $t{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==r&&(this.interiorHeight=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.holeDiameter=n),void 0!==s&&(this.holeDistToBottom=s),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==c&&(this.baseAttachmentHeight=c),void 0!==h&&(this.roofOverhang=h),void 0!==l&&(this.roofAngle=l),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class Yt{constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class Xt{}class Zt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==r&&(this.backRestHeight=r),void 0!==i&&(this.width=i),void 0!==n&&(this.length=n),void 0!==s&&(this.thickness=s),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==c&&(this.filletRadius=c),void 0!==h&&(this.precision=h),void 0!==l&&(this.drawEdges=l),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==p&&(this.origin=p),void 0!==f&&(this.direction=f)}}class Jt{constructor(){this.type="parametric-model",this.name="snakeChair"}}class Qt extends He{}class Kt{}class er extends He{}class tr{}class rr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class ir{}class nr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.topThickness=i),void 0!==n&&(this.topOffset=n),void 0!==s&&(this.bottomThickness=s),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==c&&(this.radiusLegBottom=c),void 0!==h&&(this.nrLegPairs=h),void 0!==l&&(this.precision=l),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==p&&(this.scale=p),void 0!==f&&(this.origin=f),void 0!==g&&(this.direction=g)}}class sr{constructor(){this.type="parametric-model",this.name="elegantTable"}}class or extends He{}class ar{}class cr extends He{}class hr extends He{}class lr{constructor(){this.index=0}}class ur{}class dr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class pr{}class fr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.chamfer=i),void 0!==n&&(this.topThickness=n),void 0!==s&&(this.topGlassOffset=s),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==c&&(this.shelfTopOffset=c),void 0!==h&&(this.shelfThickness=h),void 0!==l&&(this.legWidth=l),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdges=p),void 0!==f&&(this.rotation=f),void 0!==g&&(this.scale=g),void 0!==v&&(this.origin=v),void 0!==m&&(this.direction=m)}}class gr{constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class vr extends He{}class mr{}class yr extends He{}class Sr extends He{}class br extends He{}class wr{constructor(){this.index=0}}class Er{}class Tr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class xr{}class kr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.supportLength=i),void 0!==n&&(this.shelfHeight=n),void 0!==s&&(this.thickness=s),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==c&&(this.nrOrnamentPlanks=c),void 0!==h&&(this.ornamentDepth=h),void 0!==l&&(this.filletRadius=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class Cr{constructor(){this.type="parametric-model",this.name="snakeTable"}}class Pr extends He{}class Ar{}class _r extends He{}class Or{}class Dr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(Me||(Me={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(Ie||(Ie={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(Ue||(Ue={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(We||(We={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(Ne||(Ne={}));const Rr=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class Fr{constructor(e,t,r,i,n,s,o,a,c){this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==r&&(this.fontVariant=r),void 0!==i&&(this.fontSize=i),void 0!==n&&(this.height=n),void 0!==s&&(this.rotation=s),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==c&&(this.originAlignment=c)}}class Lr{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.facePlanar=!1,this.faceTextVar=Ue.separatedExtrusion,this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==r&&(this.faceTextVar=r),void 0!==i&&(this.text=i),void 0!==n&&(this.fontType=n),void 0!==s&&(this.fontVariant=s),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.originParamU=h),void 0!==l&&(this.originParamV=l),void 0!==u&&(this.originAlignment=u)}}class Br{constructor(){this.type="parametric-model",this.name="text3d"}}class Mr{constructor(){this.index=0}}class Ir{}class Ur{}class Wr{constructor(e,t,r,i,n,s,o,a,c,h){this.faceTextVar=Ue.separatedExtrusion,this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==r&&(this.fontType=r),void 0!==i&&(this.fontVariant=i),void 0!==n&&(this.fontSize=n),void 0!==s&&(this.height=s),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==c&&(this.originParamV=c),void 0!==h&&(this.originAlignment=h)}}class Nr{constructor(e,t,r){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==r&&(this.definitions=r)}}class Gr{constructor(e,t,r,i){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==i&&(this.height=i)}}class Hr{constructor(e,t,r,i,n,s,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==r&&(this.uNumber=r),void 0!==i&&(this.vNumber=i),void 0!==n&&(this.affectMinHeight=n),void 0!==s&&(this.affectMaxHeight=s),void 0!==o&&(this.precision=o)}}class Vr{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class zr{constructor(){this.index=0}}class jr{}class qr{}class $r{}class Yr{}class Xr{constructor(){this.faceIndex=0}}class Zr{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class Jr{constructor(){this.faceIndex=0,this.uIndex=0}}class Qr{constructor(){this.faceIndex=0,this.vIndex=0}}class Kr{}class ei{}var ti,ri,ii;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(ti||(ti={}));class ni{static parse(e,t,r){const i=[e];let n=0;for(;i.length>0;){const e=i.pop();if("object"==typeof e&&null!==e)if(Array.isArray(e))for(let t=0;t{const a=o.shapes[e];if(a){const c=t.transforms.rotate({shape:a,angle:r,axis:[0,1,0]}),h=t.transforms.alignAndTranslate({shape:c,direction:i,center:n});1!==s[0]||1!==s[1]||1!==s[2]?(o.shapes[e]=t.transforms.scale3d({shape:h,scale:s,center:n}),h.delete()):o.shapes[e]=h,c.delete()}})),Object.keys(o).forEach((e=>{const a=o[e];a&&Array.isArray(a)?o[e]=a.map((e=>e&&"object"==typeof e&&null!==e&&e.shapes?this.alignAndTranslateShapesWithChildren(e,t,r,i,n,s):e)):a&&"object"==typeof a&&null!==a&&a.shapes&&(o[e]=this.alignAndTranslateShapesWithChildren(a,t,r,i,n,s))})),o}static deleteAllShapes(e){Object.keys(e.shapes).forEach((t=>{e.shapes[t].delete()})),Object.keys(e).forEach((t=>{const r=e[t];r&&Array.isArray(r)?r.forEach((e=>{e&&"object"==typeof e&&null!==e&&e.shapes&&this.deleteAllShapes(e)})):r&&"object"==typeof r&&null!==r&&r.shapes&&this.deleteAllShapes(r)}))}static deepCopy(e){const t=Object.assign(Object.assign({},e),{shapes:Object.assign({},e.shapes)});return Object.keys(e).forEach((r=>{const i=e[r];i&&"object"==typeof i&&null!==i?i.shapes&&(t[r]=this.deepCopy(i)):i&&Array.isArray(i)&&(t[r]=i.map((e=>e&&"object"==typeof e&&null!==e&&e.shapes?this.deepCopy(e):e)))})),t}}class si{constructor(e,t,r){this.occtService=e,this.dependencies=r,this.occtAdv=t}wingtipVilla(e){return function(e,t){!function(e){let t;if(["interiorWidth","interiorLength","interiorHeight","chimneyHeight","roofOverhang","thickness","holeDiameter","holeDistToBottom","stickDiameter","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.interiorWidth<=0?t=`interior width can't be ${e.interiorWidth}, which is lower or equal to 0`:e.interiorLength<=0?t=`interior length can't be ${e.interiorLength}, which is lower or equal to 0`:e.interiorHeight<=0?t=`interior height can't be ${e.interiorHeight}, which is lower or equal to 0`:e.chimneyHeight<=0?t=`chimney height can't be ${e.chimneyHeight}, which is lower or equal to 0`:e.interiorWidthe.holeDistToBottom&&(t="The stick diameter is larger than the hole's distance to bottom. Stick can't fit the surface. Model can't be made."),t)throw new Error(t)}(e);const r=e.baseAttachmentHeight,i=e.roofOverhang,n=e.chimneyHeight,s=(e.interiorWidth+2*e.thickness)/2,o=Le.computeSideA(45,s),a=function(e,t){const r=Math.pow(e,2)+Math.pow(t,2);return Math.sqrt(r)}(o,s),c=e.thickness,h=[],l=t.shapes.wire.createPolygonWire({points:[[-s,-r-c,0],[s,-r-c,0],[s,e.interiorHeight,0],[0,e.interiorHeight+o,0],[-s,e.interiorHeight,0]].reverse()});h.push(l);const u=e.interiorLength+e.thickness,d=t.shapes.wire.createPolygonWire({points:[[-s,-c,u],[s,-c,u],[s,e.interiorHeight,u],[0,e.interiorHeight+o,u],[-s,e.interiorHeight,u]].reverse()});h.push(d);const p=t.shapes.wire.createCircleWire({radius:e.holeDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom+e.holeDiameter/2,u]});h.push(p);const f=t.shapes.wire.createCircleWire({radius:e.stickDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom/2,u+c]});h.push(f);const g=t.shapes.face.createFaceFromWire({shape:f,planar:!0});h.push(g);const v=t.operations.extrude({shape:g,direction:[0,0,e.stickLength]}),m=t.shapes.solid.createBoxFromCorner({corner:[-s+c,-c,c],width:e.interiorWidth,length:e.interiorLength,height:c}),y=t.shapes.solid.createBoxFromCorner({corner:[-s,-c,c],width:c,length:e.interiorLength,height:e.interiorHeight+c}),S=t.shapes.solid.createBoxFromCorner({corner:[s-c,-c,c],width:c,length:e.interiorLength,height:e.interiorHeight+c}),b=t.shapes.solid.createBoxFromCorner({corner:[0,0,0],width:a+i,length:e.interiorLength+2*c+i,height:c}),w=t.shapes.solid.createBoxFromCorner({corner:[0,-c,0],width:a+i+c,length:e.interiorLength+2*c+i,height:c}),E=t.transforms.rotate({shape:b,angle:-45,axis:[0,0,1]});h.push(E);const T=t.transforms.translate({shape:E,translation:[0,e.interiorHeight+o,0]}),x=t.shapes.edge.getCornerPointsOfEdgesForShape({shape:T}),k=t.transforms.rotate({shape:w,angle:225,axis:[0,0,1]});h.push(k);const C=t.transforms.translate({shape:k,translation:x[3]}),P=t.shapes.face.createFaceFromWire({shape:l,planar:!0});h.push(P);const A=t.operations.makeThickSolidSimple({shape:P,offset:-e.thickness}),_=t.shapes.face.createFaceFromWire({shape:d,planar:!0});h.push(_);const O=t.operations.splitShapeWithShapes({shape:_,shapes:[p]});h.push(O);const D=t.shapes.face.getFace({shape:O,index:0});h.push(D);const R=t.operations.makeThickSolidSimple({shape:D,offset:-e.thickness}),F=function(e,t,r){const i=e.shapes.face.getFaces({shape:t})[3],n=e.shapes.face.getFaceCenterOfMass({shape:i}),s=e.transforms.scale3d({shape:i,scale:[.3,.3,.3],center:n}),o=e.shapes.edge.getCornerPointsOfEdgesForShape({shape:s}),a=o[0],c=o[1],h=o[2],l=o[3],u=Math.max(a[1],c[1],h[1],l[1]),d=[a[0],u+r,a[2]],p=[c[0],u+r,c[2]],f=[h[0],u+r,h[2]],g=[l[0],u+r,l[2]],v=e.shapes.wire.createPolygonWire({points:[a,c,h,l]}),m=e.shapes.wire.createPolygonWire({points:[d,p,f,g]}),y=e.operations.loft({shapes:[v,m],makeSolid:!0});return i.delete(),s.delete(),v.delete(),m.delete(),y}(t,T,n),L=[m,A,R,y,S,T,C,v,t.shapes.compound.makeCompound({shapes:[T,C]}),t.shapes.compound.makeCompound({shapes:[A,R,y,S]}),F],B=L.map(((r,i)=>{const n=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]});return t.transforms.translate({shape:n,translation:e.origin})})),M=t.shapes.compound.makeCompound({shapes:B});return L.forEach((e=>e.delete())),h.forEach((e=>e.delete())),{compound:M,shapes:B.map(((e,t)=>({id:t.toString(),shape:e}))),data:{type:"parametric-model",name:"wingtipVilla",roof:{compound:"8",shapes:["5","6"]},walls:{compound:"9",shapes:["1","2","3","4"]},floor:{shape:"0"},stick:{shape:"7"},chimney:{shape:"10"},basicPoints:[{kind:"origin",point:e.origin}]}}}(e,this.occtService)}chirpyChalet(e){return function(e,t){!function(e){let t;if(["interiorWidth","interiorLength","interiorHeight","roofAngle","roofOverhang","thickness","holeDiameter","holeDistToBottom","stickDiameter","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.interiorWidth<=0?t=`interior width can't be ${e.interiorWidth}, which is lower or equal to 0`:e.interiorLength<=0?t=`interior length can't be ${e.interiorLength}, which is lower or equal to 0`:e.interiorHeight<=0?t=`interior height can't be ${e.interiorHeight}, which is lower or equal to 0`:e.interiorWidthe.holeDistToBottom&&(t="The stick diameter is larger than the hole's distance to bottom. Stick can't fit the surface. Model can't be made."),t)throw new Error(t)}(e);const r=e.baseAttachmentHeight,i=e.roofOverhang,n=e.roofAngle,s=e.interiorWidth/2,o=e.interiorLength+2*e.thickness,a=Le.computeSideA(n,o),c=Le.computeSideA(n,o-e.thickness),h=function(e,t){const r=Math.pow(e,2)+Math.pow(t,2);return Math.sqrt(r)}(a,o),l=e.thickness,u=[],d=t.shapes.wire.createPolygonWire({points:[[-s,-r-l,0],[s,-r-l,0],[s,e.interiorHeight+c,0],[-s,e.interiorHeight+c,0]].reverse()});u.push(d);const p=e.interiorLength+e.thickness,f=t.shapes.wire.createPolygonWire({points:[[-s,-l,p],[s,-l,p],[s,e.interiorHeight,p],[-s,e.interiorHeight,p]].reverse()});u.push(f);const g=t.shapes.wire.createCircleWire({radius:e.holeDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom+e.holeDiameter/2,p]});u.push(g);const v=t.shapes.wire.createCircleWire({radius:e.stickDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom/2,p+l]});u.push(v);const m=t.shapes.face.createFaceFromWire({shape:v,planar:!0});u.push(m);const y=t.operations.extrude({shape:m,direction:[0,0,e.stickLength]}),S=t.shapes.solid.createBoxFromCorner({corner:[-s,-l,l],width:e.interiorWidth,length:e.interiorLength,height:l}),b=t.shapes.wire.createPolygonWire({points:[[-s,-l,0],[-s,-l,p+l],[-s,e.interiorHeight,p+l],[-s,e.interiorHeight+a,0]].reverse()}),w=t.shapes.face.createFaceFromWire({shape:b,planar:!0}),E=t.operations.extrude({shape:w,direction:[-l,0,0]}),T=t.transforms.translate({shape:E,translation:[e.interiorWidth+l,0,0]}),x=t.shapes.solid.createBoxFromCorner({corner:[-s-l-i,0,0],width:e.interiorWidth+2*l+2*i,length:h+i,height:l}),k=t.transforms.rotate({shape:x,angle:n,axis:[1,0,0]});u.push(k);const C=t.transforms.translate({shape:k,translation:[0,e.interiorHeight+a,0]}),P=t.shapes.face.createFaceFromWire({shape:d,planar:!0});u.push(P);const A=t.operations.makeThickSolidSimple({shape:P,offset:-e.thickness}),_=t.shapes.face.createFaceFromWire({shape:f,planar:!0});u.push(_);const O=t.operations.splitShapeWithShapes({shape:_,shapes:[g]});u.push(O);const D=t.shapes.face.getFace({shape:O,index:0});u.push(D);const R=t.operations.makeThickSolidSimple({shape:D,offset:-e.thickness}),F=[S,A,R,E,T,C,y,t.shapes.compound.makeCompound({shapes:[C]}),t.shapes.compound.makeCompound({shapes:[A,R,E,T]})],L=F.map(((r,i)=>{const n=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]});return t.transforms.translate({shape:n,translation:e.origin})})),B=t.shapes.compound.makeCompound({shapes:L});return F.forEach((e=>e.delete())),u.forEach((e=>e.delete())),{compound:B,shapes:L.map(((e,t)=>({id:t.toString(),shape:e}))),data:{type:"parametric-model",name:"chirpyChalet",roof:{compound:"7",shapes:["5","6"]},walls:{compound:"8",shapes:["1","2","3","4"]},floor:{shape:"0"},stick:{shape:"6"},basicPoints:[{kind:"origin",point:e.origin}]}}}(e,this.occtService)}serenitySwirl(t){return function(t,r,i){if(function(e){let t;if(["swirl","nrOfDivisions","addRadiusNarrow","addRadiusWide","addMiddleHeight","addTopHeight","thickness","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.swirl<0?t="swirl value should be between 0 and 1":e.nrOfDivisions<=0?t=`nrOfDivisions can't be ${e.nrOfDivisions}, which is lower or equal to 0`:e.addRadiusNarrow<0?t=`addRadiusNarrow can't be ${e.addRadiusNarrow}, which is lower then 0`:e.addRadiusWide<0?t=`addRadiusWide can't be ${e.addRadiusWide}, which is lower then 0`:e.addMiddleHeight<=0?t=`addMiddleHeight can't be ${e.addMiddleHeight}, which is lower or equal to 0`:e.addTopHeight<=0?t=`addTopHeight can't be ${e.addTopHeight}, which is lower or equal to 0`:e.thickness<=0?t=`thickness can't be ${e.thickness}, which is lower or equal to 0`:3!==e.origin.length&&(t="The origin should be a vector of 3 numbers."),t)throw new Error(t)}(t),!i.serenitySwirl)throw new Error("Could not compute, to use Serenity Swirl algorithm you must be subscribed.");try{const n=`\n ${i.serenitySwirl}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}arabicArchway(t){return function(t,r,i){if(function(e){let t;if(["nrOfSides","thickness","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.nrOfSides<0?t="swirl value should be between 0 and 1":e.nrOfSides<3?t=`nrOfSides can't be ${e.nrOfSides}, which is lower to 3`:e.nrOfSides>30?t=`nrOfSides can't be ${e.nrOfSides}, which is higher then 30`:e.thickness<=0?t=`thickness can't be ${e.thickness}, which is lower or equal to 0`:3!==e.origin.length&&(t="The origin should be a vector of 3 numbers."),t)throw new Error(t)}(t),!i.arabicArchway)throw new Error("Could not compute, to use Arabic Archway algorithm you must be subscribed.");try{const n=`\n ${i.arabicArchway}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}eternalLove(t){return function(t,r,i,n){if(!n.eternalLove)throw new Error("Could not compute, to use Eternal Love algorithm you must be subscribed to our silver plan.");try{const s=`\n ${n.eternalLove}\n `;return new Function(s).apply({inputs:t,occt:r,occtAdv:i,Inputs:e,Text3D:R})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}calmCup(t){return function(t,r,i,n){if(function(e){let t;if(["height","radiusBottom","radiusTopOffset","thickness","fillet","nrOfHandles","handleDist","precision","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<6*e.thickness?t="Height must be at least 6 times greater than thickness.":e.radiusBottom<=0?t="Radius bottom must be greater than 0.":e.thickness<=0?t="Thickness must be greater than 0.":e.fillet<0||e.fillet>e.thickness/2?t="Fillet must be greater than 0 and less than half of the thickness.":e.handleDist<=2*e.thickness?t="Handle distance from cup must be greater than 2 times the thickness.":e.nrOfHandles<0||e.nrOfHandles>2?t="Nr of handles must be between 0 and 2.":e.radiusTopOffset>.75*e.radiusBottom&&(t="Top offset radius must be less than 0.75 times the bottom radius."),t)throw new Error(t)}(t),!n.calmCup)throw new Error("Could not compute, to use Calm Cup algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.calmCup}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}spicyBox(t){return function(t,r,i,n){if(!n.spicyBox)throw new Error("Could not compute, to use Spicy Box algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.spicyBox}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}dragonCup(t){return function(t,r,i,n){if(function(e){let t;if(["height","radiusBottom","radiusTopOffset","thickness","nrSkinCellsHorizontal","nrSkinCellsVertical","precision","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.radiusBottom<=0?t="Radius bottom must be greater than 0.":e.thickness<=0?t="Thickness must be greater than 0.":e.nrSkinCellsHorizontal<=2?t="Nr of horizontal skin cells must be larger than 2.":e.nrSkinCellsVertical<1&&(t="Nr of horizontal skin cells must be larger than 0."),t)throw new Error(t)}(t),!n.dragonCup)throw new Error("Could not compute, to use Dragon Cup algorithm you must be subscribed to our silver plan.");try{const s=`\n ${n.dragonCup}\n `;return new Function(s).apply({inputs:t,occt:r,occtAdv:i,Inputs:e,Advanced:G})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}zenHideout(t){return function(t,r,i){if(function(e){let t;if([].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),t)throw new Error(t)}(t),!i.zenHideout)throw new Error("Could not compute, to use Zen Hideout algorithm you must be subscribed.");try{const n=`\n ${i.zenHideout}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e,Things:D,MathHelper:Le,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}elegantTable(t){return function(t,r,i,n){if(!n.elegantTable)throw new Error("Could not compute, to use Elegant Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.elegantTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}goodCoffeeTable(t){return function(t,r,i,n){if(function(e){let t;if(["height","width","length","topThickness","topGlassOffset","glassThickness","glassHolderLength","chamfer","legWidth","legDepth","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<=e.topThickness?t="Height must be greated then top thickness.":e.width<=0?t="Width must be greater than 0.":e.width<=2*(e.topGlassOffset+e.glassHolderLength)?t="Width must be greater than two top glass offsets and glass holder lengths.":e.length<=0?t="Length must be greater than 0.":e.length<=2*(e.topGlassOffset+e.glassHolderLength)?t="Length must be greater than two top glass offsets and glass holder lengths.":e.topThickness<=2*e.glassThickness?t="Table top thickness must be greater 2 x glass thickness.":e.glassThickness<=0?t="Glass thickness must be greater than 0":e.glassHolderLengthe.height-e.topThickness-e.shelfThickness?t=`Shelf top offset is larger than ${e.height-e.topThickness-e.shelfThickness}, which make it go underground.`:e.chamfer>=e.topThickness/2?t="Chamfer distance must be lower or equal than half of the top thickness.":e.chamfer>=e.shelfThickness/2?t="Chamfer distance must be lower or equal than half of the shelf thickness.":e.chamfer>=e.topGlassOffset/2?t="Chamfer distance must be lower or equal than half of the top glass offset.":e.chamfer>=e.legWidth/2?t="Chamfer distance must be lower or equal than half of the leg width.":e.chamfer>=e.legDepth/2?t="Chamfer distance must be lower or equal than half of the leg depth.":e.width<=2*e.legWidth?t="Width of the table must be greater or equal to the width of the two legs.":e.length<=2*e.legDepth?t="Length of the table must be greater or equal to the length of the two legs.":e.legDepth>=e.topGlassOffset+e.glassHolderLength?t="The depth of the leg must be lower or equal to the sum of glass offset and glass holder length.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.goodCoffeeTable)throw new Error("Could not compute, to use Good Coffee Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.goodCoffeeTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}snakeChair(t){return function(t,r,i,n){if(function(e){let t;if(["sittingHeight","backRestOffset","backRestHeight","width","length","thickness","ornamentDepth","nrOrnamentPlanks","filletRadius","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.sittingHeight<=2*e.thickness?t="Sitting height must be greater than 2 x thickness.":e.backRestOffset<0?t="Back rest offset can't be negative.":e.backRestHeight<=0?t="Back rest height must be greater than 0":e.width<=0?t="Width must be greater than 0.":e.length<=2*e.thickness?t="Length height must be greater than 2 x thickness.":e.thickness<=0?t="Width must be greater than 0.":e.nrOrnamentPlanks<0?t="Number of ornament planks must be greater than 0":e.filletRadius<=0?t="Fillet radius must be greater than 0.":e.filletRadius>=e.sittingHeight/2?t="Fillet radius must be lower than half of the sitting height.":e.filletRadius>=e.length/2?t="Fillet radius must be lower than half of the length.":e.filletRadius>=e.backRestHeight/2?t="Fillet radius must be lower than half of the back height.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.snakeChair)throw new Error("Could not compute, to use Snake Chair algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.snakeChair}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}snakeTable(t){return function(t,r,i,n){if(function(e){let t;if(["height","width","length","shelfHeight","supportLength","glassThickness","glassOffset","thickness","ornamentDepth","nrOrnamentPlanks","filletRadius","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<=2*e.thickness?t="Sitting height must be greater than 2 x thickness.":e.width<=0?t="Width must be greater than 0.":e.length<=2*e.thickness?t="Length height must be greater than 2 x thickness.":e.thickness<=0?t="Width must be greater than 0.":e.nrOrnamentPlanks<0?t="Number of ornament planks must be greater than 0":e.filletRadius<=0?t="Fillet radius must be greater than 0.":e.filletRadius>=e.height/2?t="Fillet radius must be lower than half of the sitting height.":e.filletRadius>=e.length/2?t="Fillet radius must be lower than half of the length.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.snakeTable)throw new Error("Could not compute, to use Snake Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.snakeTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}phoneNest(t){return function(t,r,i,n){if(!n.phoneNest)throw new Error("Could not compute, to use Phone Nest algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.phoneNest}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}}function oi(e,t,r,i){const n=r.find((t=>t.name===`${e.fontType}-${e.fontVariant}`));if(!n)throw new Error(`Font ${e.fontType}-${e.fontVariant}.ttf does not exist. Current font probably does not have corresponding variant.`);const s=n.font.getPath(e.text,0,0,e.fontSize),o=[];let a=n.font.getPaths(e.text,0,0,e.fontSize,{});const c=n.font.getAdvanceWidth(e.text,e.fontSize),h=s.getBoundingBox();switch(e.originAlignment){case Ne.leftBottom:break;case Ne.leftMiddle:a=n.font.getPaths(e.text,0,(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.leftTop:a=n.font.getPaths(e.text,0,h.y2-h.y1,e.fontSize,{});break;case Ne.centerBottom:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,0,e.fontSize,{});break;case Ne.centerMiddle:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.centerTop:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,h.y2-h.y1,e.fontSize,{});break;case Ne.rightBottom:a=n.font.getPaths(e.text,-(h.x2-h.x1),0,e.fontSize,{});break;case Ne.rightMiddle:a=n.font.getPaths(e.text,-(h.x2-h.x1),(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.rightTop:a=n.font.getPaths(e.text,-(h.x2-h.x1),h.y2-h.y1,e.fontSize,{})}a.forEach((e=>{const r=e.commands,n=[];let s,a,c;for(let e=0;e0?new i.BRepBuilderAPI_MakeFace_22(n[n.length-1],c.Wire()):new i.BRepBuilderAPI_MakeFace_15(c.Wire(),!0),n.push(e.Face()),e.delete(),c.delete()}catch(e){console.error("We could not create faces from this font probably due to self intersections! You should try removing weird characters and pick a more reliable font like 'Roboto'.")}else if("L"===o.type){const e=[-o.x,0,o.y];if(a[0]===e[0]&&a[2]===e[2])continue;const r=t.shapes.edge.line({start:a,end:e});c.Add_1(r),r.delete(),a=e}else if("Q"===o.type){const e=[-o.x1,0,o.y1],r=[-o.x,0,o.y],i=[a,e,r],n=t.shapes.wire.createBezier({points:i,closed:!1});c.Add_2(n),n.delete(),a=r}else if("C"===o.type){const e=[-o.x,0,o.y],r=[a,[-o.x1,0,o.y1],[-o.x2,0,o.y2],e],i=t.shapes.wire.createBezier({points:r,closed:!1});c.Add_2(i),i.delete(),a=e}}if(void 0!==n[n.length-1]){const e=n[n.length-1],r=new U.BasicShapeRepairDto;r.shape=e,r.minTolerance=1e-8,r.maxTolerance=1e-4,r.precision=.001;const i=t.shapeFix.basicShapeRepair(r);e.delete(),o.push(i)}}));const l=new Br;if(l.advanceWidth=c,l.boundingBox={x1:h.x1,y1:h.y1,x2:h.x2,y2:h.y2},e.height>0){const r=o.map((r=>t.operations.extrude({shape:r,direction:[0,e.height,0]})));o.forEach((e=>e.delete()));const i=r.map((r=>{const i=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=t.transforms.alignAndTranslate({shape:i,center:e.origin,direction:e.direction});return i.delete(),n}));i.reverse();const n=t.shapes.solid.getSolidsCentersOfMass({shapes:i});l.characterCenterCoordinates=n;const s=t.shapes.compound.makeCompound({shapes:i});return l.characterParts=i.map(((e,t)=>({id:`character-${t.toString()}`,shapes:{compound:e}}))),ai(l,s)}{const r=o.map((r=>{const i=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=t.transforms.alignAndTranslate({shape:i,center:e.origin,direction:e.direction});return i.delete(),n}));r.reverse(),o.forEach((e=>e.delete()));const i=t.shapes.face.getFacesCentersOfMass({shapes:r});l.characterCenterCoordinates=i;const n=t.shapes.compound.makeCompound({shapes:r});return l.characterParts=r.map(((e,t)=>({id:`character-${t.toString()}`,shapes:{compound:e}}))),ai(l,n)}}function ai(e,t){if(e){const r=[],i=ni.parse(e,r,"text-3d");return{compound:t,shapes:[{id:"1",shape:t},...r],data:Object.assign({compound:"1"},i)}}}String.prototype.codePointAt||(ii=function(e){if(null==this)throw TypeError();var t=String(this),r=t.length,i=e?Number(e):0;if(i!=i&&(i=0),!(i<0||i>=r)){var n,s=t.charCodeAt(i);return s>=55296&&s<=56319&&r>i+1&&(n=t.charCodeAt(i+1))>=56320&&n<=57343?1024*(s-55296)+n-56320+65536:s}},(ri=function(){try{var e={},t=Object.defineProperty,r=t(e,e,e)&&t}catch(e){}return r}())?ri(String.prototype,"codePointAt",{value:ii,configurable:!0,writable:!0}):String.prototype.codePointAt=ii);function ci(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}function hi(e,t){this.source=e,this.sourceIndex=0,this.tag=0,this.bitcount=0,this.dest=t,this.destLen=0,this.ltree=new ci,this.dtree=new ci}var li=new ci,ui=new ci,di=new Uint8Array(30),pi=new Uint16Array(30),fi=new Uint8Array(30),gi=new Uint16Array(30),vi=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),mi=new ci,yi=new Uint8Array(320);function Si(e,t,r,i){var n,s;for(n=0;n>>=1,t}function Ti(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,i+r}function xi(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++n,r+=t.table[n],i-=t.table[n]}while(i>=0);return e.tag=s,e.bitcount-=n,t.trans[r+i]}function ki(e,t,r){var i,n,s,o,a,c;for(i=Ti(e,5,257),n=Ti(e,5,1),s=Ti(e,4,4),o=0;o<19;++o)yi[o]=0;for(o=0;o8;)e.sourceIndex--,e.bitcount-=8;if((t=256*(t=e.source[e.sourceIndex+1])+e.source[e.sourceIndex])!==(65535&~(256*e.source[e.sourceIndex+3]+e.source[e.sourceIndex+2])))return-3;for(e.sourceIndex+=4,r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,0}!function(e,t){var r;for(r=0;r<7;++r)e.table[r]=0;for(e.table[7]=24,e.table[8]=152,e.table[9]=112,r=0;r<24;++r)e.trans[r]=256+r;for(r=0;r<144;++r)e.trans[24+r]=r;for(r=0;r<8;++r)e.trans[168+r]=280+r;for(r=0;r<112;++r)e.trans[176+r]=144+r;for(r=0;r<5;++r)t.table[r]=0;for(t.table[5]=32,r=0;r<32;++r)t.trans[r]=r}(li,ui),Si(di,pi,4,3),Si(fi,gi,2,1),di[28]=0,pi[28]=258;var Ai=function(e,t){var r,i,n=new hi(e,t);do{switch(r=Ei(n),Ti(n,2,0)){case 0:i=Pi(n);break;case 1:i=Ci(n,li,ui);break;case 2:ki(n,n.ltree,n.dtree),i=Ci(n,n.ltree,n.dtree);break;default:i=-3}if(0!==i)throw new Error("Data error")}while(!r);return n.destLenthis.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},Oi.prototype.addX=function(e){this.addPoint(e,null)},Oi.prototype.addY=function(e){this.addPoint(null,e)},Oi.prototype.addBezier=function(e,t,r,i,n,s,o,a){var c=[e,t],h=[r,i],l=[n,s],u=[o,a];this.addPoint(e,t),this.addPoint(o,a);for(var d=0;d<=1;d++){var p=6*c[d]-12*h[d]+6*l[d],f=-3*c[d]+9*h[d]-9*l[d]+3*u[d],g=3*h[d]-3*c[d];if(0!==f){var v=Math.pow(p,2)-4*g*f;if(!(v<0)){var m=(-p+Math.sqrt(v))/(2*f);0=0&&i>0&&(r+=" "),r+=t(n)}return r}e=void 0!==e?e:2;for(var i="",n=0;n"},Di.prototype.toDOMElement=function(e){var t=this.toPathData(e),r=document.createElementNS("http://www.w3.org/2000/svg","path");return r.setAttribute("d",t),r};var Li={fail:Ri,argument:Fi,assert:Fi},Bi=2147483648,Mi={},Ii={},Ui={};function Wi(e){return function(){return e}}Ii.BYTE=function(e){return Li.argument(e>=0&&e<=255,"Byte value should be between 0 and 255."),[e]},Ui.BYTE=Wi(1),Ii.CHAR=function(e){return[e.charCodeAt(0)]},Ui.CHAR=Wi(1),Ii.CHARARRAY=function(e){void 0===e&&(e="",console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."));for(var t=[],r=0;r>8&255,255&e]},Ui.USHORT=Wi(2),Ii.SHORT=function(e){return e>=32768&&(e=-(65536-e)),[e>>8&255,255&e]},Ui.SHORT=Wi(2),Ii.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},Ui.UINT24=Wi(3),Ii.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.ULONG=Wi(4),Ii.LONG=function(e){return e>=Bi&&(e=-(2*Bi-e)),[e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.LONG=Wi(4),Ii.FIXED=Ii.ULONG,Ui.FIXED=Ui.ULONG,Ii.FWORD=Ii.SHORT,Ui.FWORD=Ui.SHORT,Ii.UFWORD=Ii.USHORT,Ui.UFWORD=Ui.USHORT,Ii.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.LONGDATETIME=Wi(8),Ii.TAG=function(e){return Li.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},Ui.TAG=Wi(4),Ii.Card8=Ii.BYTE,Ui.Card8=Ui.BYTE,Ii.Card16=Ii.USHORT,Ui.Card16=Ui.USHORT,Ii.OffSize=Ii.BYTE,Ui.OffSize=Ui.BYTE,Ii.SID=Ii.USHORT,Ui.SID=Ui.USHORT,Ii.NUMBER=function(e){return e>=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?Ii.NUMBER16(e):Ii.NUMBER32(e)},Ui.NUMBER=function(e){return Ii.NUMBER(e).length},Ii.NUMBER16=function(e){return[28,e>>8&255,255&e]},Ui.NUMBER16=Wi(3),Ii.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.NUMBER32=Wi(5),Ii.REAL=function(e){var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t);if(r){var i=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length));t=(Math.round(e*i)/i).toString()}for(var n="",s=0,o=t.length;s>8&255,t[t.length]=255&i}return t},Ui.UTF16=function(e){return 2*e.length};var Ni={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};Mi.MACSTRING=function(e,t,r,i){var n=Ni[i];if(void 0!==n){for(var s="",o=0;o=-128&&e<=127}function zi(e,t,r){for(var i=0,n=e.length;t>8&255,c+256&255)}return s}Ii.MACSTRING=function(e,t){var r=function(e){if(!Gi)for(var t in Gi={},Ni)Gi[t]=new String(t);var r=Gi[e];if(void 0!==r){if(Hi){var i=Hi.get(r);if(void 0!==i)return i}var n=Ni[e];if(void 0!==n){for(var s={},o=0;o=128&&void 0===(s=r[s]))return;i[n]=s}return i}},Ui.MACSTRING=function(e,t){var r=Ii.MACSTRING(e,t);return void 0!==r?r.length:0},Ii.VARDELTAS=function(e){for(var t=0,r=[];t=-128&&i<=127?ji(e,t,r):qi(e,t,r)}return r},Ii.INDEX=function(e){for(var t=1,r=[t],i=[],n=0;n>8,t[u+1]=255&d,t=t.concat(i[l])}return t},Ui.TABLE=function(e){for(var t=0,r=e.fields.length,i=0;i0)return new hn(this.data,this.offset+t).parseStruct(e)},hn.prototype.parsePointer32=function(e){var t=this.parseOffset32();if(t>0)return new hn(this.data,this.offset+t).parseStruct(e)},hn.prototype.parseListOfLists=function(e){for(var t=this.parseOffset16List(),r=t.length,i=this.relativeOffset,n=new Array(r),s=0;s=0;n-=1){var s=un.getUShort(e,t+4+8*n),o=un.getUShort(e,t+4+8*n+2);if(3===s&&(0===o||1===o||10===o)||0===s&&(0===o||1===o||2===o||3===o||4===o)){i=un.getULong(e,t+4+8*n+4);break}}if(-1===i)throw new Error("No valid cmap sub-tables found.");var a=new un.Parser(e,t+i);if(r.format=a.parseUShort(),12===r.format)!function(e,t){var r;t.parseUShort(),e.length=t.parseULong(),e.language=t.parseULong(),e.groupCount=r=t.parseULong(),e.glyphIndexMap={};for(var i=0;i>1,t.skip("uShort",3),e.glyphIndexMap={};for(var o=new un.Parser(r,i+n+14),a=new un.Parser(r,i+n+16+2*s),c=new un.Parser(r,i+n+16+4*s),h=new un.Parser(r,i+n+16+6*s),l=i+n+16+8*s,u=0;u0;t-=1)if(e.get(t).unicode>65535){console.log("Adding CMAP format 12 (needed!)"),r=!1;break}var i=[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:r?1:2},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:r?12:20}];r||(i=i.concat([{name:"cmap12PlatformID",type:"USHORT",value:3},{name:"cmap12EncodingID",type:"USHORT",value:10},{name:"cmap12Offset",type:"ULONG",value:0}])),i=i.concat([{name:"format",type:"USHORT",value:4},{name:"cmap4Length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);var n=new rn.Table("cmap",i);for(n.segments=[],t=0;t>4,s=15&i;if(15===n)break;if(t+=r[n],15===s)break;t+=r[s]}return parseFloat(t)}(e);if(t>=32&&t<=246)return t-139;if(t>=247&&t<=250)return 256*(t-247)+e.parseByte()+108;if(t>=251&&t<=254)return 256*-(t-251)-e.parseByte()-108;throw new Error("Invalid b0 "+t)}function Dn(e,t,r){t=void 0!==t?t:0;var i=new un.Parser(e,t),n=[],s=[];for(r=void 0!==r?r:e.length;i.relativeOffset>1,d.length=0,f=!0}return function r(h){for(var y,S,T,x,k,C,P,A,_,O,D,R,F=0;F1&&!f&&(b=d.shift()+l,f=!0),m+=d.pop(),w(v,m);break;case 5:for(;d.length>0;)v+=d.shift(),m+=d.shift(),u.lineTo(v,m);break;case 6:for(;d.length>0&&(v+=d.shift(),u.lineTo(v,m),0!==d.length);)m+=d.shift(),u.lineTo(v,m);break;case 7:for(;d.length>0&&(m+=d.shift(),u.lineTo(v,m),0!==d.length);)v+=d.shift(),u.lineTo(v,m);break;case 8:for(;d.length>0;)i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 10:k=d.pop()+c,(C=a[k])&&r(C);break;case 11:return;case 12:switch(L=h[F],F+=1,L){case 35:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),P=s+d.shift(),A=o+d.shift(),_=P+d.shift(),O=A+d.shift(),D=_+d.shift(),R=O+d.shift(),v=D+d.shift(),m=R+d.shift(),d.shift(),u.curveTo(i,n,s,o,P,A),u.curveTo(_,O,D,R,v,m);break;case 34:i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),P=s+d.shift(),A=o,_=P+d.shift(),O=o,D=_+d.shift(),R=m,v=D+d.shift(),u.curveTo(i,n,s,o,P,A),u.curveTo(_,O,D,R,v,m);break;case 36:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),P=s+d.shift(),A=o,_=P+d.shift(),O=o,D=_+d.shift(),R=O+d.shift(),v=D+d.shift(),u.curveTo(i,n,s,o,P,A),u.curveTo(_,O,D,R,v,m);break;case 37:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),P=s+d.shift(),A=o+d.shift(),_=P+d.shift(),O=A+d.shift(),D=_+d.shift(),R=O+d.shift(),Math.abs(D-v)>Math.abs(R-m)?v=D+d.shift():m=R+d.shift(),u.curveTo(i,n,s,o,P,A),u.curveTo(_,O,D,R,v,m);break;default:console.log("Glyph "+t.index+": unknown operator 1200"+L),d.length=0}break;case 14:d.length>0&&!f&&(b=d.shift()+l,f=!0),g&&(u.closePath(),g=!1);break;case 19:case 20:E(),F+=p+7>>3;break;case 21:d.length>2&&!f&&(b=d.shift()+l,f=!0),m+=d.pop(),w(v+=d.pop(),m);break;case 22:d.length>1&&!f&&(b=d.shift()+l,f=!0),w(v+=d.pop(),m);break;case 24:for(;d.length>2;)i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);v+=d.shift(),m+=d.shift(),u.lineTo(v,m);break;case 25:for(;d.length>6;)v+=d.shift(),m+=d.shift(),u.lineTo(v,m);i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 26:for(d.length%2&&(v+=d.shift());d.length>0;)i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s,m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 27:for(d.length%2&&(m+=d.shift());d.length>0;)i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o,u.curveTo(i,n,s,o,v,m);break;case 28:y=h[F],S=h[F+1],d.push((y<<24|S<<16)>>16),F+=2;break;case 29:k=d.pop()+e.gsubrsBias,(C=e.gsubrs[k])&&r(C);break;case 30:for(;d.length>0&&(i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m),0!==d.length);)i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),m=o+d.shift(),v=s+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m);break;case 31:for(;d.length>0&&(i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),m=o+d.shift(),v=s+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m),0!==d.length);)i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m);break;default:L<32?console.log("Glyph "+t.index+": unknown operator "+L):L<247?d.push(L-139):L<251?(y=h[F],F+=1,d.push(256*(L-247)+y+108)):L<255?(y=h[F],F+=1,d.push(256*-(L-251)-y-108)):(y=h[F],S=h[F+1],T=h[F+2],x=h[F+3],F+=4,d.push((y<<24|S<<16|T<<8|x)/65536))}}}(r),t.advanceWidth=b,u}function Nn(e,t){var r,i=fn.indexOf(e);return i>=0&&(r=i),(i=t.indexOf(e))>=0?r=i+fn.length:(r=fn.length+t.length,t.push(e)),r}function Gn(e,t,r){for(var i={},n=0;n=i)throw new Error("CFF table CID Font FDSelect has bad FD index value "+n+" (FD count "+i+")");s.push(n)}else{if(3!==a)throw new Error("CFF Table CID Font FDSelect table has unsupported format "+a);var h,l=o.parseCard16(),u=o.parseCard16();if(0!==u)throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+u);for(var d=0;d=i)throw new Error("CFF table CID Font FDSelect has bad FD index value "+n+" (FD count "+i+")");if(h>r)throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+h);for(;u=1&&(r.ulCodePageRange1=i.parseULong(),r.ulCodePageRange2=i.parseULong()),r.version>=2&&(r.sxHeight=i.parseShort(),r.sCapHeight=i.parseShort(),r.usDefaultChar=i.parseUShort(),r.usBreakChar=i.parseUShort(),r.usMaxContent=i.parseUShort()),r},make:function(e){return new rn.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],e)},unicodeRanges:ls,getUnicodeRange:function(e){for(var t=0;t=r.begin&&e=mn.length){var o=i.parseChar();r.names.push(i.parseString(o))}break;case 2.5:r.numberOfGlyphs=i.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var a=0;at.value.tag?1:-1})),t.fields=t.fields.concat(i),t.fields=t.fields.concat(n),t}function Es(e,t,r){for(var i=0;i0)return e.glyphs.get(n).getMetrics()}return r}function Ts(e){for(var t=0,r=0;rv||void 0===t)&&v>0&&(t=v),h 123 are reserved for internal usage");p|=1<0?Xn.make(R):void 0,B=ds.make(),M=jn.make(e.glyphs,{version:e.getEnglishName("version"),fullName:A,familyName:C,weightName:P,postScriptName:_,unitsPerEm:e.unitsPerEm,fontBBox:[0,S.yMin,S.ascender,S.advanceWidthMax]}),I=e.metas&&Object.keys(e.metas).length>0?ms.make(e.metas):void 0,U=[b,w,E,T,F,k,B,M,x];L&&U.push(L),e.tables.gsub&&U.push(vs.make(e.tables.gsub)),I&&U.push(I);for(var W=ws(U),N=Ss(W.encode()),G=W.fields,H=!1,V=0;V>>1,s=e[n].tag;if(s===t)return n;s>>1,s=e[n];if(s===t)return n;s>>1,o=(r=e[s]).start;if(o===t)return r;o0)return t>(r=e[i-1]).end?0:r}function As(e,t){this.font=e,this.tableName=t}function _s(e){As.call(this,e,"gpos")}function Os(e){As.call(this,e,"gsub")}function Ds(e,t){var r=e.length;if(r!==t.length)return!1;for(var i=0;i0?(s=e.parseByte(),t&n||(s=-s),s=r+s):s=(t&n)>0?r:r+e.parseShort(),s}function Bs(e,t,r){var i,n,s=new un.Parser(t,r);if(e.numberOfContours=s.parseShort(),e._xMin=s.parseShort(),e._yMin=s.parseShort(),e._xMax=s.parseShort(),e._yMax=s.parseShort(),e.numberOfContours>0){for(var o=e.endPointIndices=[],a=0;a0)for(var u=s.parseByte(),d=0;d0){var p,f=[];if(h>0){for(var g=0;g=0,f.push(p);for(var v=0,m=0;m0?(2&i)>0?(w.dx=s.parseShort(),w.dy=s.parseShort()):w.matchedPoints=[s.parseUShort(),s.parseUShort()]:(2&i)>0?(w.dx=s.parseChar(),w.dy=s.parseChar()):w.matchedPoints=[s.parseByte(),s.parseByte()],(8&i)>0?w.xScale=w.yScale=s.parseF2Dot14():(64&i)>0?(w.xScale=s.parseF2Dot14(),w.yScale=s.parseF2Dot14()):(128&i)>0&&(w.xScale=s.parseF2Dot14(),w.scale01=s.parseF2Dot14(),w.scale10=s.parseF2Dot14(),w.yScale=s.parseF2Dot14()),e.components.push(w),b=!!(32&i)}if(256&i){e.instructionLength=s.parseUShort(),e.instructions=[];for(var E=0;Et.points.length-1||i.matchedPoints[1]>n.points.length-1)throw Error("Matched points out of range in "+t.name);var o=t.points[i.matchedPoints[0]],a=n.points[i.matchedPoints[1]],c={xScale:i.xScale,scale01:i.scale01,scale10:i.scale10,yScale:i.yScale,dx:0,dy:0};a=Ms([a],c)[0],c.dx=o.x-a.x,c.dy=o.y-a.y,s=Ms(n.points,c)}t.points=t.points.concat(s)}}return Is(t.points)}As.prototype={searchTag:ks,binSearch:Cs,getTable:function(e){var t=this.font.tables[this.tableName];return!t&&e&&(t=this.font.tables[this.tableName]=this.createDefaultTable()),t},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map((function(e){return e.tag})):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var t=!1,r=0;r=0)return i[n].script;if(t){var s={tag:e,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};return i.splice(-1-n,0,s),s.script}}},getLangSysTable:function(e,t,r){var i=this.getScriptTable(e,r);if(i){if(!t||"dflt"===t||"DFLT"===t)return i.defaultLangSys;var n=ks(i.langSysRecords,t);if(n>=0)return i.langSysRecords[n].langSys;if(r){var s={tag:t,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};return i.langSysRecords.splice(-1-n,0,s),s.langSys}}},getFeatureTable:function(e,t,r,i){var n=this.getLangSysTable(e,t,i);if(n){for(var s,o=n.featureIndexes,a=this.font.tables[this.tableName].features,c=0;c=a[h-1].tag,"Features must be added in alphabetical order."),s={tag:r,feature:{params:0,lookupListIndexes:[]}},a.push(s),o.push(h),s.feature}}},getLookupTables:function(e,t,r,i,n){var s=this.getFeatureTable(e,t,r,n),o=[];if(s){for(var a,c=s.lookupListIndexes,h=this.font.tables[this.tableName].lookups,l=0;l=0?r:-1;case 2:var i=Ps(e.ranges,t);return i?i.index+t-i.start:-1}},expandCoverage:function(e){if(1===e.format)return e.glyphs;for(var t=[],r=e.ranges,i=0;i1,'Multiple: "by" must be an array of two or more ids');var n=Rs(this.getLookupTables(r,i,e,2,!0)[0],1,{substFormat:1,coverage:{format:1,glyphs:[]},sequences:[]});Li.assert(1===n.coverage.format,"Multiple: unable to modify coverage table format "+n.coverage.format);var s=t.sub,o=this.binSearch(n.coverage.glyphs,s);o<0&&(o=-1-o,n.coverage.glyphs.splice(o,0,s),n.sequences.splice(o,0,0)),n.sequences[o]=t.by},Os.prototype.addAlternate=function(e,t,r,i){var n=Rs(this.getLookupTables(r,i,e,3,!0)[0],1,{substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});Li.assert(1===n.coverage.format,"Alternate: unable to modify coverage table format "+n.coverage.format);var s=t.sub,o=this.binSearch(n.coverage.glyphs,s);o<0&&(o=-1-o,n.coverage.glyphs.splice(o,0,s),n.alternateSets.splice(o,0,0)),n.alternateSets[o]=t.by},Os.prototype.addLigature=function(e,t,r,i){var n=this.getLookupTables(r,i,e,4,!0)[0],s=n.subtables[0];s||(s={substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]},n.subtables[0]=s),Li.assert(1===s.coverage.format,"Ligature: unable to modify coverage table format "+s.coverage.format);var o=t.sub[0],a=t.sub.slice(1),c={ligGlyph:t.by,components:a},h=this.binSearch(s.coverage.glyphs,o);if(h>=0){for(var l=s.ligatureSets[h],u=0;u=176&&r<=183)n+=r-176+1;else if(r>=184&&r<=191)n+=2*(r-184+1);else if(t&&1===s&&27===r)break}while(s>0);e.ip=n}function co(e,t){exports.DEBUG&&console.log(t.step,"SVTCA["+e.axis+"]"),t.fv=t.pv=t.dpv=e}function ho(e,t){exports.DEBUG&&console.log(t.step,"SPVTCA["+e.axis+"]"),t.pv=t.dpv=e}function lo(e,t){exports.DEBUG&&console.log(t.step,"SFVTCA["+e.axis+"]"),t.fv=e}function uo(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log("SPVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.pv=t.dpv=to(r,i)}function po(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log("SFVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.fv=to(r,i)}function fo(e){exports.DEBUG&&console.log(e.step,"POP[]"),e.stack.pop()}function go(e,t){var r=t.stack.pop(),i=t.z0[r],n=t.fv,s=t.pv;exports.DEBUG&&console.log(t.step,"MDAP["+e+"]",r);var o=s.distance(i,io);e&&(o=t.round(o)),n.setRelative(i,io,o,s),n.touch(i),t.rp0=t.rp1=r}function vo(e,t){var r,i,n,s=t.z2,o=s.length-2;exports.DEBUG&&console.log(t.step,"IUP["+e.axis+"]");for(var a=0;a1?"loop "+(t.loop-a)+": ":"")+"SHP["+(e?"rp1":"rp2")+"]",h)}t.loop=1}function yo(e,t){var r=t.stack,i=e?t.rp1:t.rp2,n=(e?t.z0:t.z1)[i],s=t.fv,o=t.pv,a=r.pop(),c=t.z2[t.contours[a]],h=c;exports.DEBUG&&console.log(t.step,"SHC["+e+"]",a);var l=o.distance(n,n,!1,!0);do{h!==n&&s.setRelative(h,h,l,o),h=h.nextPointOnContour}while(h!==c)}function So(e,t){var r,i,n=t.stack,s=e?t.rp1:t.rp2,o=(e?t.z0:t.z1)[s],a=t.fv,c=t.pv,h=n.pop();switch(exports.DEBUG&&console.log(t.step,"SHZ["+e+"]",h),h){case 0:r=t.tZone;break;case 1:r=t.gZone;break;default:throw new Error("Invalid zone")}for(var l=c.distance(o,o,!1,!0),u=r.length-2,d=0;d",a),t.stack.push(Math.round(64*a))}function xo(e,t){var r=t.stack,i=r.pop(),n=t.fv,s=t.pv,o=t.ppem,a=t.deltaBase+16*(e-1),c=t.deltaShift,h=t.z0;exports.DEBUG&&console.log(t.step,"DELTAP["+e+"]",i,r);for(var l=0;l>4)===o){var p=(15&d)-8;p>=0&&p++,exports.DEBUG&&console.log(t.step,"DELTAPFIX",u,"by",p*c);var f=h[u];n.setRelative(f,f,p*c,s)}}}function ko(e,t){var r=t.stack,i=r.pop();exports.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(i/64))}function Co(e,t){var r=t.stack,i=r.pop(),n=t.ppem,s=t.deltaBase+16*(e-1),o=t.deltaShift;exports.DEBUG&&console.log(t.step,"DELTAC["+e+"]",i,r);for(var a=0;a>4)===n){var l=(15&h)-8;l>=0&&l++;var u=l*o;exports.DEBUG&&console.log(t.step,"DELTACFIX",c,"by",u),t.cvt[c]+=u}}}function Po(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.dpv=to(r,i)}function Ao(e,t){var r=t.stack,i=t.prog,n=t.ip;exports.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var s=0;s=0?1:-1,a=Math.abs(a),e&&(h=s.cvt[u],i&&Math.abs(a-h)":"_")+(i?"R":"_")+(0===n?"Gr":1===n?"Bl":2===n?"Wh":"")+"]",e?u+"("+s.cvt[u]+","+h+")":"",d,"(d =",o,"->",c*a,")"),s.rp1=s.rp0,s.rp2=d,t&&(s.rp0=d)}function Do(e){this.char=e,this.state={},this.activeState=null}function Ro(e,t,r){this.contextName=r,this.startIndex=e,this.endOffset=t}function Fo(e,t,r){this.contextName=e,this.openRange=null,this.ranges=[],this.checkStart=t,this.checkEnd=r}function Lo(e,t){this.context=e,this.index=t,this.length=e.length,this.current=e[t],this.backtrack=e.slice(0,t),this.lookahead=e.slice(t+1)}function Bo(e){this.eventId=e,this.subscribers=[]}function Mo(e){var t=this,r=["start","end","next","newToken","contextStart","contextEnd","insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD","updateContextsRanges"];r.forEach((function(e){Object.defineProperty(t.events,e,{value:new Bo(e)})})),e&&r.forEach((function(r){var i=e[r];"function"==typeof i&&t.events[r].subscribe(i)})),["insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD"].forEach((function(e){t.events[e].subscribe(t.updateContextsRanges)}))}function Io(e){this.tokens=[],this.registeredContexts={},this.contextCheckers=[],this.events={},this.registeredModifiers=[],Mo.call(this,e)}function Uo(e){return/[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(e)}function Wo(e){return/[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(e)}function No(e){return/[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(e)}function Go(e){return/[A-z]/.test(e)}function Ho(e){this.font=e,this.features={}}function Vo(e){this.id=e.id,this.tag=e.tag,this.substitution=e.substitution}function zo(e,t){if(!e)return-1;switch(t.format){case 1:return t.glyphs.indexOf(e);case 2:for(var r=t.ranges,i=0;i=n.start&&e<=n.end){var s=e-n.start;return n.index+s}}break;default:return-1}return-1}function jo(e,t){return-1===zo(e,t.coverage)?null:e+t.deltaGlyphId}function qo(e,t){var r=zo(e,t.coverage);return-1===r?null:t.substitute[r]}function $o(e,t){for(var r=[],i=0;i2)){var r=this.font,i=this._prepState;if(!i||i.ppem!==t){var n=this._fpgmState;if(!n){so.prototype=no,(n=this._fpgmState=new so("fpgm",r.tables.fpgm)).funcs=[],n.font=r,exports.DEBUG&&(console.log("---EXEC FPGM---"),n.step=-1);try{Ns(n)}catch(e){return console.log("Hinting error in FPGM:"+e),void(this._errorState=3)}}so.prototype=n,(i=this._prepState=new so("prep",r.tables.prep)).ppem=t;var s=r.tables.cvt;if(s)for(var o=i.cvt=new Array(s.length),a=t/r.unitsPerEm,c=0;c1))try{return Gs(e,i)}catch(e){return this._errorState<1&&(console.log("Hinting error:"+e),console.log("Note: further hinting errors are silenced")),void(this._errorState=1)}}},Gs=function(e,t){var r,i,n,s=t.ppem/t.font.unitsPerEm,o=s,a=e.components;if(so.prototype=t,a){var c=t.font;i=[],r=[];for(var h=0;h1?"loop "+(e.loop-r)+": ":"")+"SHPIX[]",o,n),i.setRelative(a,a,n),i.touch(a)}e.loop=1},function(e){for(var t=e.stack,r=e.rp1,i=e.rp2,n=e.loop,s=e.z0[r],o=e.z1[i],a=e.fv,c=e.dpv,h=e.z2;n--;){var l=t.pop(),u=h[l];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-n)+": ":"")+"IP[]",l,r,"<->",i),a.interpolate(u,s,o,c),a.touch(u)}e.loop=1},bo.bind(void 0,0),bo.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,i=e.z0[r],n=e.loop,s=e.fv,o=e.pv,a=e.z1;n--;){var c=t.pop(),h=a[c];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-n)+": ":"")+"ALIGNRP[]",c),s.setRelative(h,i,0,o),s.touch(h)}e.loop=1},function(e){exports.DEBUG&&console.log(e.step,"RTDG[]"),e.round=$s},wo.bind(void 0,0),wo.bind(void 0,1),function(e){var t=e.prog,r=e.ip,i=e.stack,n=t[++r];exports.DEBUG&&console.log(e.step,"NPUSHB[]",n);for(var s=0;sr?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"GTEQ[]",r,i),t.push(i>=r?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"EQ[]",r,i),t.push(r===i?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"NEQ[]",r,i),t.push(r!==i?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"ODD[]",r),t.push(Math.trunc(r)%2?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"EVEN[]",r),t.push(Math.trunc(r)%2?0:1)},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"IF[]",t),t||(ao(e,!0),exports.DEBUG&&console.log(e.step,"EIF[]"))},function(e){exports.DEBUG&&console.log(e.step,"EIF[]")},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"AND[]",r,i),t.push(r&&i?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"OR[]",r,i),t.push(r||i?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"NOT[]",r),t.push(r?0:1)},xo.bind(void 0,1),function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SDB[]",t),e.deltaBase=t},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SDS[]",t),e.deltaShift=Math.pow(.5,t)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"ADD[]",r,i),t.push(i+r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"SUB[]",r,i),t.push(i-r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"DIV[]",r,i),t.push(64*i/r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MUL[]",r,i),t.push(i*r/64)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"ABS[]",r),t.push(Math.abs(r))},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"NEG[]",r),t.push(-r)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"FLOOR[]",r),t.push(64*Math.floor(r/64))},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"CEILING[]",r),t.push(64*Math.ceil(r/64))},ko.bind(void 0,0),ko.bind(void 0,1),ko.bind(void 0,2),ko.bind(void 0,3),void 0,void 0,void 0,void 0,function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"WCVTF[]",r,i),e.cvt[i]=r*e.ppem/e.font.unitsPerEm},xo.bind(void 0,2),xo.bind(void 0,3),Co.bind(void 0,1),Co.bind(void 0,2),Co.bind(void 0,3),function(e){var t,r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"SROUND[]",r),e.round=Js,192&r){case 0:t=.5;break;case 64:t=1;break;case 128:t=2;break;default:throw new Error("invalid SROUND value")}switch(e.srPeriod=t,48&r){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*t;break;case 32:e.srPhase=.5*t;break;case 48:e.srPhase=.75*t;break;default:throw new Error("invalid SROUND value")}r&=15,e.srThreshold=0===r?0:(r/8-.5)*t},function(e){var t,r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"S45ROUND[]",r),e.round=Js,192&r){case 0:t=Math.sqrt(2)/2;break;case 64:t=Math.sqrt(2);break;case 128:t=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}switch(e.srPeriod=t,48&r){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*t;break;case 32:e.srPhase=.5*t;break;case 48:e.srPhase=.75*t;break;default:throw new Error("invalid S45ROUND value")}r&=15,e.srThreshold=0===r?0:(r/8-.5)*t},void 0,void 0,function(e){exports.DEBUG&&console.log(e.step,"ROFF[]"),e.round=js},void 0,function(e){exports.DEBUG&&console.log(e.step,"RUTG[]"),e.round=Xs},function(e){exports.DEBUG&&console.log(e.step,"RDTG[]"),e.round=Zs},fo,fo,void 0,void 0,void 0,void 0,void 0,function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANCTRL[]",t)},Po.bind(void 0,0),Po.bind(void 0,1),function(e){var t=e.stack,r=t.pop(),i=0;exports.DEBUG&&console.log(e.step,"GETINFO[]",r),1&r&&(i=35),32&r&&(i|=4096),t.push(i)},void 0,function(e){var t=e.stack,r=t.pop(),i=t.pop(),n=t.pop();exports.DEBUG&&console.log(e.step,"ROLL[]"),t.push(i),t.push(r),t.push(n)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MAX[]",r,i),t.push(Math.max(i,r))},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MIN[]",r,i),t.push(Math.min(i,r))},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANTYPE[]",t)},function(e){var t=e.stack.pop(),r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"INSTCTRL[]",t,r),t){case 1:return void(e.inhibitGridFit=!!r);case 2:return void(e.ignoreCvt=!!r);default:throw new Error("invalid INSTCTRL[] selector")}},void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,Ao.bind(void 0,1),Ao.bind(void 0,2),Ao.bind(void 0,3),Ao.bind(void 0,4),Ao.bind(void 0,5),Ao.bind(void 0,6),Ao.bind(void 0,7),Ao.bind(void 0,8),_o.bind(void 0,1),_o.bind(void 0,2),_o.bind(void 0,3),_o.bind(void 0,4),_o.bind(void 0,5),_o.bind(void 0,6),_o.bind(void 0,7),_o.bind(void 0,8),Oo.bind(void 0,0,0,0,0,0),Oo.bind(void 0,0,0,0,0,1),Oo.bind(void 0,0,0,0,0,2),Oo.bind(void 0,0,0,0,0,3),Oo.bind(void 0,0,0,0,1,0),Oo.bind(void 0,0,0,0,1,1),Oo.bind(void 0,0,0,0,1,2),Oo.bind(void 0,0,0,0,1,3),Oo.bind(void 0,0,0,1,0,0),Oo.bind(void 0,0,0,1,0,1),Oo.bind(void 0,0,0,1,0,2),Oo.bind(void 0,0,0,1,0,3),Oo.bind(void 0,0,0,1,1,0),Oo.bind(void 0,0,0,1,1,1),Oo.bind(void 0,0,0,1,1,2),Oo.bind(void 0,0,0,1,1,3),Oo.bind(void 0,0,1,0,0,0),Oo.bind(void 0,0,1,0,0,1),Oo.bind(void 0,0,1,0,0,2),Oo.bind(void 0,0,1,0,0,3),Oo.bind(void 0,0,1,0,1,0),Oo.bind(void 0,0,1,0,1,1),Oo.bind(void 0,0,1,0,1,2),Oo.bind(void 0,0,1,0,1,3),Oo.bind(void 0,0,1,1,0,0),Oo.bind(void 0,0,1,1,0,1),Oo.bind(void 0,0,1,1,0,2),Oo.bind(void 0,0,1,1,0,3),Oo.bind(void 0,0,1,1,1,0),Oo.bind(void 0,0,1,1,1,1),Oo.bind(void 0,0,1,1,1,2),Oo.bind(void 0,0,1,1,1,3),Oo.bind(void 0,1,0,0,0,0),Oo.bind(void 0,1,0,0,0,1),Oo.bind(void 0,1,0,0,0,2),Oo.bind(void 0,1,0,0,0,3),Oo.bind(void 0,1,0,0,1,0),Oo.bind(void 0,1,0,0,1,1),Oo.bind(void 0,1,0,0,1,2),Oo.bind(void 0,1,0,0,1,3),Oo.bind(void 0,1,0,1,0,0),Oo.bind(void 0,1,0,1,0,1),Oo.bind(void 0,1,0,1,0,2),Oo.bind(void 0,1,0,1,0,3),Oo.bind(void 0,1,0,1,1,0),Oo.bind(void 0,1,0,1,1,1),Oo.bind(void 0,1,0,1,1,2),Oo.bind(void 0,1,0,1,1,3),Oo.bind(void 0,1,1,0,0,0),Oo.bind(void 0,1,1,0,0,1),Oo.bind(void 0,1,1,0,0,2),Oo.bind(void 0,1,1,0,0,3),Oo.bind(void 0,1,1,0,1,0),Oo.bind(void 0,1,1,0,1,1),Oo.bind(void 0,1,1,0,1,2),Oo.bind(void 0,1,1,0,1,3),Oo.bind(void 0,1,1,1,0,0),Oo.bind(void 0,1,1,1,0,1),Oo.bind(void 0,1,1,1,0,2),Oo.bind(void 0,1,1,1,0,3),Oo.bind(void 0,1,1,1,1,0),Oo.bind(void 0,1,1,1,1,1),Oo.bind(void 0,1,1,1,1,2),Oo.bind(void 0,1,1,1,1,3)],Do.prototype.setState=function(e,t){return this.state[e]=t,this.activeState={key:e,value:this.state[e]},this.activeState},Do.prototype.getState=function(e){return this.state[e]||null},Io.prototype.inboundIndex=function(e){return e>=0&&e0&&e<=this.lookahead.length:return this.lookahead[e-1];default:return null}},Io.prototype.rangeToText=function(e){if(e instanceof Ro)return this.getRangeTokens(e).map((function(e){return e.char})).join("")},Io.prototype.getText=function(){return this.tokens.map((function(e){return e.char})).join("")},Io.prototype.getContext=function(e){return this.registeredContexts[e]||null},Io.prototype.on=function(e,t){var r=this.events[e];return r?r.subscribe(t):null},Io.prototype.dispatch=function(e,t){var r=this,i=this.events[e];i instanceof Bo&&i.subscribers.forEach((function(e){e.apply(r,t||[])}))},Io.prototype.registerContextChecker=function(e,t,r){if(this.getContext(e))return{FAIL:"context name '"+e+"' is already registered."};if("function"!=typeof t)return{FAIL:"missing context start check."};if("function"!=typeof r)return{FAIL:"missing context end check."};var i=new Fo(e,t,r);return this.registeredContexts[e]=i,this.contextCheckers.push(i),i},Io.prototype.getRangeTokens=function(e){var t=e.startIndex+e.endOffset;return[].concat(this.tokens.slice(e.startIndex,t))},Io.prototype.getContextRanges=function(e){var t=this.getContext(e);return t?t.ranges:{FAIL:"context checker '"+e+"' is not registered."}},Io.prototype.resetContextsRanges=function(){var e=this.registeredContexts;for(var t in e)e.hasOwnProperty(t)&&(e[t].ranges=[])},Io.prototype.updateContextsRanges=function(){this.resetContextsRanges();for(var e=this.tokens.map((function(e){return e.char})),t=0;t=0;r--){var i=t[r],n=Wo(i),s=No(i);if(!n&&!s)return!0;if(n)return!1}return!1}(o)&&(h|=1),function(e){if(Wo(e.current))return!1;for(var t=0;t=1.2&&(n.markGlyphSets=r.parsePointer(Ca)),n}},Aa=new Array(10);Aa[1]=function(){var e=this.offset+this.relativeOffset,t=this.parseUShort();return 1===t?{posFormat:1,coverage:this.parsePointer(hn.coverage),value:this.parseValueRecord()}:2===t?{posFormat:2,coverage:this.parsePointer(hn.coverage),values:this.parseValueRecordList()}:void Li.assert(!1,"0x"+e.toString(16)+": GPOS lookup type 1 format must be 1 or 2.")},Aa[2]=function(){var e=this.offset+this.relativeOffset,t=this.parseUShort();Li.assert(1===t||2===t,"0x"+e.toString(16)+": GPOS lookup type 2 format must be 1 or 2.");var r=this.parsePointer(hn.coverage),i=this.parseUShort(),n=this.parseUShort();if(1===t)return{posFormat:t,coverage:r,valueFormat1:i,valueFormat2:n,pairSets:this.parseList(hn.pointer(hn.list((function(){return{secondGlyph:this.parseUShort(),value1:this.parseValueRecord(i),value2:this.parseValueRecord(n)}}))))};if(2===t){var s=this.parsePointer(hn.classDef),o=this.parsePointer(hn.classDef),a=this.parseUShort(),c=this.parseUShort();return{posFormat:t,coverage:r,valueFormat1:i,valueFormat2:n,classDef1:s,classDef2:o,class1Count:a,class2Count:c,classRecords:this.parseList(a,hn.list(c,(function(){return{value1:this.parseValueRecord(i),value2:this.parseValueRecord(n)}})))}}},Aa[3]=function(){return{error:"GPOS Lookup 3 not supported"}},Aa[4]=function(){return{error:"GPOS Lookup 4 not supported"}},Aa[5]=function(){return{error:"GPOS Lookup 5 not supported"}},Aa[6]=function(){return{error:"GPOS Lookup 6 not supported"}},Aa[7]=function(){return{error:"GPOS Lookup 7 not supported"}},Aa[8]=function(){return{error:"GPOS Lookup 8 not supported"}},Aa[9]=function(){return{error:"GPOS Lookup 9 not supported"}};var _a=new Array(10),Oa={parse:function(e,t){var r=new hn(e,t=t||0),i=r.parseVersion(1);return Li.argument(1===i||1.1===i,"Unsupported GPOS table version "+i),1===i?{version:i,scripts:r.parseScriptList(),features:r.parseFeatureList(),lookups:r.parseLookupList(Aa)}:{version:i,scripts:r.parseScriptList(),features:r.parseFeatureList(),lookups:r.parseLookupList(Aa),variations:r.parseFeatureVariationsList()}},make:function(e){return new rn.Table("GPOS",[{name:"version",type:"ULONG",value:65536},{name:"scripts",type:"TABLE",value:new rn.ScriptList(e.scripts)},{name:"features",type:"TABLE",value:new rn.FeatureList(e.features)},{name:"lookups",type:"TABLE",value:new rn.LookupList(e.lookups,_a)}])}},Da={parse:function(e,t){var r=new un.Parser(e,t),i=r.parseUShort();if(0===i)return function(e){var t={};e.skip("uShort");var r=e.parseUShort();Li.argument(0===r,"Unsupported kern sub-table version."),e.skip("uShort",2);var i=e.parseUShort();e.skip("uShort",3);for(var n=0;n1&&console.warn("Only the first kern subtable is supported."),e.skip("uLong");var r=255&e.parseUShort();if(e.skip("uShort"),0===r){var i=e.parseUShort();e.skip("uShort",3);for(var n=0;n{try{const r=e?Rr.filter((t=>e.includes(t.key))):Rr,i=r.reduce(((e,t)=>e+t.variants.length),0);let n=0;r.forEach((e=>{e.variants.forEach((r=>{const s=e.key,o=`${s}-${r}`;!function(e,t,r){r=null==r?{}:r;var i="undefined"!=typeof window||r.isUrl?La:Fa;new Promise((function(n,s){i(e,(function(e,i){if(e){if(t)return t(e);s(e)}var o;try{o=Ia(i,r)}catch(e){if(t)return t(e,null);s(e)}if(t)return t(null,o);n(o)}))}))}(`https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.14.7.6/fonts/${s}/${o}.ttf`,((e,a)=>{e||(this.fonts.push({name:o,type:s,variant:r,font:a}),n++,n===i&&t({}))}),{isUrl:!0})}))}))}catch(e){r(e)}}))},new((i=void 0)||(i=Promise))((function(e,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,a)}c((n=n.apply(t,r||[])).next())}));var t,r,i,n}text3d(e){return oi(e,this.occtService,this.fonts,this.occ)}text3dFace(t){return function(t,r,i,n,s,o){if(!o.text3dFace)throw new Error("Could not compute, to use Text 3D Face algorithm you must be subscribed to our silver or gold plan.");try{const a=`\n ${o.text3dFace}\n `,c=new Function(a),h={name:"text3dFace"};return c.apply({inputs:t,occt:r,fonts:i,occ:n,vectorHelper:s,Inputs:e,Advanced:G,ShapeParser:ni,text3d:oi,method:h})}catch(e){throw new Error(e)}}(t,this.occtService,this.fonts,this.occ,this.vectorHelper,this.dependencies)}texts3dFace(t){return function(t,r,i,n,s,o){if(!o.text3dFace)throw new Error("Could not compute, to use Texts 3D Face algorithm you must be subscribed to our silver or gold plan.");try{const a=`\n ${o.text3dFace}\n `,c=new Function(a),h={name:"texts3dFace"};return c.apply({inputs:t,occt:r,fonts:i,occ:n,vectorHelper:s,Inputs:e,Advanced:G,ShapeParser:ni,text3d:oi,method:h})}catch(e){throw new Error(e)}}(t,this.occtService,this.fonts,this.occ,this.vectorHelper,this.dependencies)}pyramidSimple(t){return function(t,r,i,n,s){if(function(e){let t;if(["uNumber","vNumber","height","precision"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.uNumber<=0?t="U number mus be greater than 0.":e.vNumber<=0?t="V number must be greater than 0.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!s.patternsFacePatternPyramidSimple)throw new Error("Could not compute, to use Pyramid Simple algorithm you must be subscribed to our silver or gold plan.");try{const o=`\n ${s.patternsFacePatternPyramidSimple}\n `,a=new Function(o),c={name:"pyramidSimple"};return a.apply({inputs:t,occt:r,occ:i,vectorHelper:n,Inputs:e,Advanced:G,ShapeParser:ni,method:c})}catch(e){throw new Error(e)}}(t,this.occtService,this.occ,this.vectorHelper,this.dependencies)}pyramidSimpleAffectors(t){return function(t,r,i,n,s){if(function(e){let t;if(["uNumber","vNumber","defaultHeight","affectMinHeight","affectMaxHeight","precision"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.uNumber<=0?t="U number mus be greater than 0.":e.vNumber<=0?t="V number must be greater than 0.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!s.patternsFacePatternPyramidSimple)throw new Error("Could not compute, to use Pyramid Simple Affectors algorithm you must be subscribed to our silver or gold plan.");try{const o=`\n ${s.patternsFacePatternPyramidSimple}\n `,a=new Function(o),c={name:"pyramidSimpleAffectors"};return a.apply({inputs:t,occt:r,occ:i,vectorHelper:n,Inputs:e,Advanced:G,ShapeParser:ni,method:c})}catch(e){throw new Error(e)}}(t,this.occtService,this.occ,this.vectorHelper,this.dependencies)}}class Wa{constructor(e){this.dependencies={serenitySwirl:void 0};const t=new V,r=new H;this.occtService=new Ce(e,new Se(t,r,e)),this.advanced=new Ua(this.occtService,this.dependencies,e,t),this.things=new si(this.occtService,this.advanced,this.dependencies)}}var Na=function(){return Na=Object.assign||function(e){for(var t,r=1,i=arguments.length;r0&&n[n.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!n||a[1]>n[0]&&a[1]{Re=new Oe(e);const i=new V,n=new H;De=new Ce(e,new Se(i,n,e)),t&&(De.plugins=t,Fe&&Object.keys(Fe).forEach((e=>{De.plugins.dependencies[e]=Fe[e]}))),postMessage("occ-initialised")})(e,t),postMessage("occ-initialised"),[2]}}))}))})):((e,t)=>{let r;t("busy");try{if("shapeToMesh"!==e.action.functionName&&"shapesToMeshes"!==e.action.functionName&&"deleteShape"!==e.action.functionName&&"deleteShapes"!==e.action.functionName&&"startedTheRun"!==e.action.functionName&&"cleanAllCache"!==e.action.functionName&&"addOc"!==e.action.functionName&&"saveShapeSTEP"!==e.action.functionName){Object.keys(e.action.inputs).forEach((t=>{const r=e.action.inputs[t];r&&r.type&&"occ-shape"===r.type&&r.hash&&(e.action.inputs[t]=Re.checkCache(e.action.inputs[t].hash)),r&&Array.isArray(r)&&r.length>0&&(r[0].type&&"occ-shape"===r[0].type&&r[0].hash?e.action.inputs[t]=e.action.inputs[t].map((e=>Re.checkCache(e.hash))):Array.isArray(r[0])&&r[0][0].type&&"occ-shape"===r[0][0].type&&r[0][0].hash&&(e.action.inputs[t]=e.action.inputs[t].map((e=>e.map((e=>Re.checkCache(e.hash)))))))}));const t=e.action.functionName.split(".");let i;if(i=3===t.length?Re.cacheOp(e.action,(()=>De[t[0]][t[1]][t[2]](e.action.inputs))):2===t.length?Re.cacheOp(e.action,(()=>De[t[0]][t[1]](e.action.inputs))):Re.cacheOp(e.action,(()=>De[e.action.functionName](e.action.inputs))),Re.isOCCTObject(i))r=Array.isArray(i)?i.map((e=>({hash:e.hash,type:"occ-shape"}))):{hash:i.hash,type:"occ-shape"};else if(i.compound&&i.data&&i.shapes&&i.shapes.length>0){const e=i;e.shapes=e.shapes.map((e=>({id:e.id,shape:{hash:e.shape.hash,type:"occ-shape"}}))),e.compound={hash:e.compound.hash,type:"occ-shape"},r=e}else r=i}if("saveShapeSTEP"===e.action.functionName&&(e.action.inputs.shape=Re.checkCache(e.action.inputs.shape.hash),r=De.io.saveShapeSTEP(e.action.inputs)),"addOc"===e.action.functionName&&(De&&De.plugins?Object.keys(e.action.inputs).forEach((t=>{De.plugins.dependencies[t]=e.action.inputs[t]})):Fe=e.action.inputs),"shapeToMesh"===e.action.functionName&&(e.action.inputs.shape=Re.checkCache(e.action.inputs.shape.hash),r=De.shapeToMesh(e.action.inputs)),"shapesToMeshes"===e.action.functionName){if(!(e.action.inputs.shapes&&e.action.inputs.shapes.length>0))throw new Error("No shapes detected");e.action.inputs.shapes=e.action.inputs.shapes.map((e=>Re.checkCache(e.hash))),r=De.shapesToMeshes(e.action.inputs)}"deleteShape"===e.action.functionName&&(Re.cleanCacheForHash(e.action.inputs.shape.hash),r={}),"deleteShapes"===e.action.functionName&&(e.action.inputs.shapes.forEach((e=>Re.cleanCacheForHash(e.hash))),r={}),"startedTheRun"===e.action.functionName&&(Re&&Object.keys(Re.usedHashes).length>1e4&&Re.cleanAllCache(),r={}),"cleanAllCache"===e.action.functionName&&(Re.cleanAllCache(),r={}),t({uid:e.uid,result:r})}catch(r){let i,n;e&&e.action&&e.action.inputs&&(i=`Input values were: {${Object.keys(e.action.inputs).map((t=>`${t}: ${JSON.stringify(e.action.inputs[t])}`)).join(",")}}. `),e&&e.action&&e.action.functionName&&(n=`- ${e.action.functionName}`),t({uid:e.uid,result:void 0,error:`OCCT computation failed. ${r} While executing function ${n}. ${i}`})}})(d,postMessage)}))})()})(); \ No newline at end of file +(()=>{var e={725:()=>{},439:()=>{},699:()=>{},256:()=>{}},t={};function r(i){var n=t[i];if(void 0!==n)return n.exports;var s=t[i]={exports:{}};return e[i](s,s.exports,r),s.exports}r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";var e={};r.r(e),r.d(e,{Base:()=>W,OCCT:()=>U});var t={};r.r(t),r.d(t,{LodDto:()=>Ge,lodEnum:()=>Be});var i={};r.r(i),r.d(i,{Part:()=>He});var n={};r.r(n),r.d(n,{SerenitySwirlData:()=>ze,SerenitySwirlDto:()=>Ve});var s={};r.r(s),r.d(s,{ArabicArchwayData:()=>$e,ArabicArchwayDrawingPart:()=>Ye,ArabicArchwayDrawingPartShapes:()=>Xe,ArabicArchwayDto:()=>qe,ArabicArchwayDtoBase:()=>je});var o={};r.r(o),r.d(o,{ArabicArchway:()=>s,SerenitySwirl:()=>n});var a={};r.r(a),r.d(a,{EternalLoveData:()=>Qe,EternalLoveDto:()=>Je,EternalLoveDtoBase:()=>Ze});var c={};r.r(c),r.d(c,{EternalLove:()=>a});var h={};r.r(h),r.d(h,{CalmCupData:()=>tt,CalmCupDto:()=>et,CalmCupDtoBase:()=>Ke});var l={};r.r(l),r.d(l,{DragonCupData:()=>nt,DragonCupDto:()=>it,DragonCupDtoBase:()=>rt,DragonCupModelDto:()=>st});var u={};r.r(u),r.d(u,{CalmCup:()=>h,DragonCup:()=>l});var d={};r.r(d),r.d(d,{PhoneNestData:()=>ct,PhoneNestDrawDto:()=>pt,PhoneNestDrawingPart:()=>ht,PhoneNestDrawingPartShapes:()=>lt,PhoneNestDto:()=>at,PhoneNestDtoBase:()=>ot,PhoneNestMainPart:()=>ut,PhoneNestModelDto:()=>dt});var p={};r.r(p),r.d(p,{PhoneNest:()=>d});var f={};r.r(f),r.d(f,{SpicyBoxData:()=>vt,SpicyBoxDto:()=>gt,SpicyBoxDtoBase:()=>ft,SpicyBoxModelDto:()=>mt});var g={};r.r(g),r.d(g,{SpicyBox:()=>f});var v={};r.r(v),r.d(v,{Boxes:()=>g,Cups:()=>u,Desktop:()=>p,Medals:()=>c,Vases:()=>o});var m={};r.r(m),r.d(m,{ZenHideoutData:()=>bt,ZenHideoutDrawingPart:()=>wt,ZenHideoutDrawingPartShapes:()=>Et,ZenHideoutDto:()=>St,ZenHideoutDtoBase:()=>yt});var y={};r.r(y),r.d(y,{ZenHideout:()=>m});var S={};r.r(S),r.d(S,{BeamPart:()=>Ft,CeilingPart:()=>Ht,ColumnPart:()=>Rt,CornerEntranceDto:()=>zt,CornerEntrancePart:()=>Wt,CornerPart:()=>Dt,CornerStairDto:()=>It,CornerStairPart:()=>Ut,FloorPart:()=>Vt,Houses:()=>y,RoofBeamsPart:()=>Bt,RoofCoverOneSidedDto:()=>Nt,RoofCoverPart:()=>Gt,RoofPanelPart:()=>Mt,RoofPart:()=>Lt,SandwitchPanelDto:()=>Pt,SandwitchPanelFlexDto:()=>At,SandwitchPart:()=>_t,SandwitchPartFlex:()=>Ot,WindowCornerDto:()=>Tt,WindowCornerPart:()=>Ct,WindowRectangularDto:()=>xt,WindowRectangularPart:()=>kt});var b={};r.r(b),r.d(b,{WingtipVillaData:()=>qt,WingtipVillaDto:()=>jt});var w={};r.r(w),r.d(w,{ChirpyChaletData:()=>Yt,ChirpyChaletDto:()=>$t});var E={};r.r(E),r.d(E,{ChirpyChalet:()=>w,WingtipVilla:()=>b});var T={};r.r(T),r.d(T,{BirdHouses:()=>E});var x={};r.r(x),r.d(x,{SnakeChairData:()=>Jt,SnakeChairDrawDto:()=>rr,SnakeChairDrawingPart:()=>Qt,SnakeChairDrawingPartShapes:()=>Kt,SnakeChairDto:()=>Zt,SnakeChairDtoBase:()=>Xt,SnakeChairMainPart:()=>er,SnakeChairModelDto:()=>tr});var k={};r.r(k),r.d(k,{SnakeChair:()=>x});var C={};r.r(C),r.d(C,{ElegantTableData:()=>sr,ElegantTableDrawDto:()=>dr,ElegantTableDrawingPart:()=>or,ElegantTableDrawingPartShapes:()=>ar,ElegantTableDto:()=>nr,ElegantTableDtoBase:()=>ir,ElegantTableLegByIndexDto:()=>lr,ElegantTableLegPart:()=>cr,ElegantTableModelDto:()=>ur,ElegantTableTopPart:()=>hr});var P={};r.r(P),r.d(P,{GoodCoffeeTableData:()=>gr,GoodCoffeeTableDrawDto:()=>Tr,GoodCoffeeTableDrawingPart:()=>vr,GoodCoffeeTableDrawingPartShapes:()=>mr,GoodCoffeeTableDto:()=>fr,GoodCoffeeTableDtoBase:()=>pr,GoodCoffeeTableLegByIndexDto:()=>wr,GoodCoffeeTableLegPart:()=>yr,GoodCoffeeTableModelDto:()=>Er,GoodCoffeeTableShelfPart:()=>Sr,GoodCoffeeTableTopPart:()=>br});var A={};r.r(A),r.d(A,{SnakeTableData:()=>Cr,SnakeTableDrawDto:()=>Dr,SnakeTableDrawingPart:()=>Pr,SnakeTableDrawingPartShapes:()=>Ar,SnakeTableDto:()=>kr,SnakeTableDtoBase:()=>xr,SnakeTableMainPart:()=>_r,SnakeTableModelDto:()=>Or});var _={};r.r(_),r.d(_,{ElegantTable:()=>C,GoodCoffeeTable:()=>P,SnakeTable:()=>A});var O={};r.r(O),r.d(O,{Chairs:()=>k,Tables:()=>_});var D={};r.r(D),r.d(D,{Architecture:()=>S,Enums:()=>t,Furniture:()=>O,KidsCorner:()=>T,Shared:()=>i,ThreeDPrinting:()=>v});var R={};r.r(R),r.d(R,{FontDefinition:()=>Ir,Text3DData:()=>Br,Text3DDto:()=>Fr,Text3DFaceDefinitionDto:()=>Wr,Text3DFaceDto:()=>Lr,Text3DLetterByIndexDto:()=>Mr,Text3DModelDto:()=>Ur,Texts3DFaceDto:()=>Nr,faceTextVarEnum:()=>Ue,faceTypeEnum:()=>We,fontVariantsEnum:()=>Ie,fontsEnum:()=>Me,fontsModel:()=>Rr,recAlignmentEnum:()=>Ne});var F={};r.r(F),r.d(F,{PyramidSimpeByIndexDto:()=>zr,PyramidSimpleAffectorsDto:()=>Hr,PyramidSimpleCellPart:()=>Kr,PyramidSimpleData:()=>Vr,PyramidSimpleDto:()=>Gr,PyramidSimpleFacePart:()=>ei,PyramidSimpleModelCellDto:()=>Yr,PyramidSimpleModelCellsDto:()=>qr,PyramidSimpleModelCellsIndexDto:()=>$r,PyramidSimpleModelDto:()=>jr,PyramidSimpleModelFaceCellIndexDto:()=>Zr,PyramidSimpleModelFaceCellsUIndexDto:()=>Jr,PyramidSimpleModelFaceCellsVIndexDto:()=>Qr,PyramidSimpleModelFaceIndexDto:()=>Xr});var L={};r.r(L),r.d(L,{PyramidSimple:()=>F});var B={};r.r(B),r.d(B,{FacePatterns:()=>L});var M={};r.r(M),r.d(M,{outputShapeEnum:()=>ti});var I,U,W,N,G={};r.r(G),r.d(G,{Enums:()=>M,Patterns:()=>B,Text3D:()=>R}),(N=I||(I={})).loading="loading",N.loaded="loaded",N.initialised="initialised",N.computing="computing";class H{starLines(e,t,r,i,n){let s=[];const o=2*Math.PI/r;for(let i=0;i=i&&(e=i-1e-6,console.warn("width first is bigger than length second, to make it work, width second is set to length first - 1e-6")),r>=t&&(r=t-1e-6,console.warn("width second is bigger than length first, to make it work, width second is set to length first - 1e-6")),[[0,0,0],[t,0,0],[t,0,e],[r,0,e],[r,0,i],[0,0,i]]}polygonLMiddle(e,t,r,i){return e>=i&&(e=i-1e-6,console.warn("width first is bigger than length second, to make it work, width second is set to length first - 1e-6")),r>=t&&(r=t-1e-6,console.warn("width second is bigger than length first, to make it work, width second is set to length first - 1e-6")),[[r/2,0,e/2],[r/2,0,i],[-r/2,0,i],[-r/2,0,-e/2],[t,0,-e/2],[t,0,e/2]]}}class V{constructor(){this.tolerance=1e-5}degToRad(e){return e*(Math.PI/180)}remap(e,t,r,i,n){return(e-t)/(r-t)*(n-i)+i}removeAllDuplicateVectors(e,t=1e-7){const r=[];return e.forEach((e=>{r.some((r=>this.vectorsTheSame(e,r,t)))||r.push(e)})),r}removeConsecutiveDuplicates(e,t=!0){const r=[];if(e.length>1){for(let t=1;te.map(((e,r)=>e+t[r]))),[0,0,0]).map((t=>t/e.length))}magnitude(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}normalize(e){const t=this.magnitude(e);return e.map((e=>e/t))}translatePoint(e,t,r){return[e[0]+t[0]*r,e[1]+t[1]*r,e[2]+t[2]*r]}distanceBetweenPoints(e,t){const r=t[0]-e[0],i=t[1]-e[1],n=t[2]-e[2];return Math.sqrt(r*r+i*i+n*n)}}!function(e){let t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(r=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(i=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(n=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(s=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(c=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(l=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(p=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(f=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(g=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(v=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,r,i,n){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.positionResult=i),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,r,i,n,s){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==r&&(this.point1=r),void 0!==i&&(this.tolerance=i),void 0!==n&&(this.positionResult=n),void 0!==s&&(this.circleRemainder=s)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,r,i,n){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.positionResult=i),void 0!==n&&(this.circleRemainders=n)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,r,i){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.radius=i)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,r,i){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.radius=i)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,r,i,n,s){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==r&&(this.planeOrigin=r),void 0!==i&&(this.planeDirection=i),void 0!==n&&(this.radius=n),void 0!==s&&(this.solution=s)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,r){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==r&&(this.inside=r)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==r&&(this.edgeOpacity=r),void 0!==i&&(this.edgeColour=i),void 0!==n&&(this.faceMaterial=n),void 0!==s&&(this.faceColour=s),void 0!==l&&(this.vertexColour=l),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==c&&(this.drawFaces=c),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==g&&(this.edgeIndexColour=g),void 0!==v&&(this.drawFaceIndexes=v),void 0!==m&&(this.faceIndexHeight=m),void 0!==y&&(this.faceIndexColour=y)}},e.DrawShapesDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==r&&(this.edgeOpacity=r),void 0!==i&&(this.edgeColour=i),void 0!==n&&(this.faceMaterial=n),void 0!==s&&(this.faceColour=s),void 0!==l&&(this.vertexColour=l),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==c&&(this.drawFaces=c),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==g&&(this.edgeIndexColour=g),void 0!==v&&(this.drawFaceIndexes=v),void 0!==m&&(this.faceIndexHeight=m),void 0!==y&&(this.faceIndexColour=y)}},e.FaceSubdivisionDto=class{constructor(e,t,r,i,n,s,o,a,c){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==r&&(this.nrDivisionsV=r),void 0!==i&&(this.shiftHalfStepU=i),void 0!==n&&(this.removeStartEdgeU=n),void 0!==s&&(this.removeEndEdgeU=s),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==c&&(this.removeEndEdgeV=c)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==r&&(this.nrDivisionsV=r),void 0!==i&&(this.shiftHalfStepNthU=i),void 0!==n&&(this.shiftHalfStepUOffsetN=n),void 0!==s&&(this.removeStartEdgeNthU=s),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==c&&(this.removeEndEdgeUOffsetN=c),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==l&&(this.shiftHalfStepVOffsetN=l),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==p&&(this.removeEndEdgeNthV=p),void 0!==f&&(this.removeEndEdgeVOffsetN=f)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,r,i,n,s,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==r&&(this.param=r),void 0!==i&&(this.nrPoints=i),void 0!==n&&(this.shiftHalfStep=n),void 0!==s&&(this.removeStartPoint=s),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,r){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==r&&(this.paramV=r)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,r){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.RectangleDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.center=r),void 0!==i&&(this.direction=i)}},e.LPolygonDto=class{constructor(e,t,r,i,s,o,a,c){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=n.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==r&&(this.widthSecond=r),void 0!==i&&(this.lengthSecond=i),void 0!==s&&(this.align=s),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==c&&(this.direction=c)}},e.BoxDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.height=r),void 0!==i&&(this.center=i)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.height=r),void 0!==i&&(this.corner=i)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,r,i,n,s){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==r&&(this.height=r),void 0!==i&&(this.angle=i),void 0!==n&&(this.center=n),void 0!==s&&(this.direction=s)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,r){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==r&&(this.end=r)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,r,i){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==r&&(this.end=r),void 0!==i&&(this.sense=i)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,r,i){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==r&&(this.alphaAngle2=r),void 0!==i&&(this.sense=i)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,r,i){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==i&&(this.sense=i)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,r){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==r&&(this.end=r)}},e.CylinderDto=class{constructor(e,t,r,i){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==r&&(this.center=r),void 0!==i&&(this.direction=i)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,r,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.indexes=i)}},e.FilletEdgesListDto=class{constructor(e,t,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusList=r)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,r){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radius=r)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.paramsU=i)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusLists=r),void 0!==i&&(this.paramsULists=i)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.paramsU=i)}},e.Fillet3DWireDto=class{constructor(e,t,r,i,n){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.direction=r),void 0!==i&&(this.radiusList=i),void 0!==n&&(this.indexes=n)}},e.ChamferDto=class{constructor(e,t,r,i){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==r&&(this.distanceList=r),void 0!==i&&(this.indexes=i)}},e.ChamferEdgesListDto=class{constructor(e,t,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.distanceList=r)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,r,i,n){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.face=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.angle=n)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,r,i,n){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.face=r),void 0!==i&&(this.distance1=i),void 0!==n&&(this.distance2=n)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,r,i,n){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distances1=i),void 0!==n&&(this.distances2=n)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,r,i,n){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distance1=i),void 0!==n&&(this.distance2=n)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,r,i,n){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distances=i),void 0!==n&&(this.angles=n)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,r,i,n){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.angle=n)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,r,i,n){this.keepLines=f.outside,this.circleRemainders=p.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.keepLines=r),void 0!==i&&(this.circleRemainders=i),void 0!==n&&(this.tolerance=n)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,r,i){this.combination=g.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==r&&(this.unify=r),void 0!==i&&(this.tolerance=i)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,r,i){this.combination=g.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==r&&(this.unify=r),void 0!==i&&(this.tolerance=i)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,r,i){this.nrZigZags=20,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==r&&(this.nrZigZags=r),void 0!==i&&(this.inverse=i)}},e.InterpolationDto=class{constructor(e,t,r){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==r&&(this.tolerance=r)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,r,i){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.removeStartPoint=r),void 0!==i&&(this.removeEndPoint=i)}},e.ProjectWireDto=class{constructor(e,t,r){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==r&&(this.direction=r)}},e.WiresToPointsDto=class{constructor(e,t,r,i,n,s){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==r&&(this.curvatureDeflection=r),void 0!==i&&(this.minimumOfPoints=i),void 0!==n&&(this.uTolerance=n),void 0!==s&&(this.minimumLength=s)}},e.EdgesToPointsDto=class{constructor(e,t,r,i,n,s){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==r&&(this.curvatureDeflection=r),void 0!==i&&(this.minimumOfPoints=i),void 0!==n&&(this.uTolerance=n),void 0!==s&&(this.minimumLength=s)}},e.ProjectWiresDto=class{constructor(e,t,r){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==r&&(this.direction=r)}},e.DivideShapesDto=class{constructor(e,t,r,i){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.removeStartPoint=r),void 0!==i&&(this.removeEndPoint=i)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,r,i){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.tEdgeParam=r),void 0!==i&&(this.distance2DParam=i)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,r){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,r,n,s,o,a,c,h,l,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=i.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==r&&(this.closed=r),void 0!==n&&(this.periodic=n),void 0!==s&&(this.straight=s),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==c&&(this.maxUDegree=c),void 0!==h&&(this.tolerance=h),void 0!==l&&(this.parType=l),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,r,i){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==r&&(this.distance=r),void 0!==i&&(this.tolerance=i)}},e.OffsetAdvancedDto=class{constructor(e,r,i,n,s,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==r&&(this.face=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.tolerance=n),void 0!==s&&(this.joinType=s),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,r,i){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==r&&(this.direction=r),void 0!==i&&(this.copy=i)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,r){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.nrCorners=r)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,r){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==r&&(this.keepEdges=r)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,r){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==r&&(this.precsmall=r)}},e.BasicShapeRepairDto=class{constructor(e,t,r,i){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.maxTolerance=r),void 0!==i&&(this.minTolerance=i)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,r){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==r&&(this.angle=r)}},e.ThickSolidByJoinDto=class{constructor(e,r,i,n,s,o,a,c){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==r&&(this.shapes=r),void 0!==i&&(this.offset=i),void 0!==n&&(this.tolerance=n),void 0!==s&&(this.intersection=s),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==c&&(this.removeIntEdges=c)}},e.TransformDto=class{constructor(e,t,r,i,n){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==r&&(this.rotationAxis=r),void 0!==i&&(this.rotationAngle=i),void 0!==n&&(this.scaleFactor=n)}},e.TransformShapesDto=class{constructor(e,t,r,i,n){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==r&&(this.rotationAxes=r),void 0!==i&&(this.rotationAngles=i),void 0!==n&&(this.scaleFactors=n)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,r,i,n){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==r&&(this.fromDirection=r),void 0!==i&&(this.toOrigin=i),void 0!==n&&(this.toDirection=n)}},e.AlignShapesDto=class{constructor(e,t,r,i,n){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==r&&(this.fromDirections=r),void 0!==i&&(this.toOrigins=i),void 0!==n&&(this.toDirections=n)}},e.MirrorDto=class{constructor(e,t,r){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==r&&(this.direction=r)}},e.MirrorShapesDto=class{constructor(e,t,r){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==r&&(this.directions=r)}},e.MirrorAlongNormalDto=class{constructor(e,t,r){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==r&&(this.normal=r)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,r){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==r&&(this.normals=r)}},e.AlignAndTranslateDto=class{constructor(e,t,r){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.center=r)}},e.UnifySameDomainDto=class{constructor(e,t,r,i){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==r&&(this.unifyFaces=r),void 0!==i&&(this.concatBSplines=i)}},e.FilterFacePointsDto=class{constructor(e,t,r,i,n,s,o,a,c){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.useBndBox=i),void 0!==n&&(this.gapTolerance=n),void 0!==s&&(this.keepIn=s),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==c&&(this.keepUnknown=c)}},e.FilterSolidPointsDto=class{constructor(e,t,r,i,n,s,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.keepIn=i),void 0!==n&&(this.keepOn=n),void 0!==s&&(this.keepOut=s),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,r){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==r&&(this.centers=r)}},e.RotateDto=class{constructor(e,t,r){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==r&&(this.angle=r)}},e.RotateAroundCenterDto=class{constructor(e,t,r,i){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==r&&(this.center=r),void 0!==i&&(this.axis=i)}},e.RotateShapesDto=class{constructor(e,t,r){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==r&&(this.angles=r)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,r,i){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==r&&(this.centers=r),void 0!==i&&(this.axes=i)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,r){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==r&&(this.center=r)}},e.Scale3DShapesDto=class{constructor(e,t,r){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==r&&(this.centers=r)}},e.ShapeToMeshDto=class{constructor(e,t,r){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.adjustYtoZ=r)}},e.ShapesToMeshesDto=class{constructor(e,t,r){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.adjustYtoZ=r)}},e.SaveStepDto=class{constructor(e,t,r,i){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.adjustYtoZ=r),void 0!==i&&(this.tryDownload=i)}},e.SaveStlDto=class{constructor(e,t,r,i,n,s){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.precision=r),void 0!==i&&(this.adjustYtoZ=i),void 0!==n&&(this.tryDownload=n),void 0!==s&&(this.binary=s)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,r){this.fileType=s.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==r&&(this.adjustZtoY=r)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,r){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.adjustZtoY=r)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,r){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==r&&(this.direction=r)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,r){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==r&&(this.dir=r)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,r,i){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==r&&(this.nrOfPointsV=r),void 0!==i&&(this.flat=i)}},e.Geom2dEllipseDto=class{constructor(e,t,r,i,n){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radiusMinor=r),void 0!==i&&(this.radiusMajor=i),void 0!==n&&(this.sense=n)}},e.Geom2dCircleDto=class{constructor(e,t,r,i){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radius=r),void 0!==i&&(this.sense=i)}},e.ChristmasTreeDto=class{constructor(e,t,r,i,n,s,o,a,c,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==r&&(this.outerDist=r),void 0!==i&&(this.nrSkirts=i),void 0!==n&&(this.trunkHeight=n),void 0!==s&&(this.trunkWidth=s),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==c&&(this.origin=c),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,r,i,n,s,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==r&&(this.numRays=r),void 0!==i&&(this.center=i),void 0!==n&&(this.direction=n),void 0!==s&&(this.offsetOuterEdges=s),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,r,i,n,s){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.aroundCenter=r),void 0!==i&&(this.width=i),void 0!==n&&(this.height=n),void 0!==s&&(this.angle=s)}},e.Heart2DDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.rotation=r),void 0!==i&&(this.sizeApprox=i)}},e.NGonWireDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.nrCorners=r),void 0!==i&&(this.radius=i)}},e.EllipseDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radiusMinor=r),void 0!==i&&(this.radiusMajor=i)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,r){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,r,i,n){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==r&&(this.u2=r),void 0!==i&&(this.sense=i),void 0!==n&&(this.adjustPeriodic=n)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,r){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==r&&(this.direction=r)}},e.SliceInStepPatternDto=class{constructor(e,t,r){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==r&&(this.direction=r)}}}(U||(U={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(W||(W={}));class z{constructor(e,t){this.occ=e,this.och=t}geom2dEllipse(e){const t=this.och.entitiesService.gpAx2d(e.center,e.direction),r=new this.occ.Geom2d_Ellipse_2(t,e.radiusMajor,e.radiusMinor,e.sense);return t.delete(),r}geom2dCircle(e){const t=this.och.entitiesService.gpAx2d(e.center,e.direction),r=new this.occ.Geom2d_Circle_2(t,e.radius,e.sense);return t.delete(),r}geom2dTrimmedCurve(e){const t=new this.occ.Handle_Geom2d_Curve_2(e.shape);return new this.occ.Geom2d_TrimmedCurve(t,e.u1,e.u2,e.sense,e.adjustPeriodic)}geom2dSegment(e){const t=this.och.entitiesService.gpPnt2d(e.start),r=this.och.entitiesService.gpPnt2d(e.end),i=new this.occ.GCE2d_MakeSegment_1(t,r),n=i.Value().get();return t.delete(),r.delete(),i.delete(),n}get2dPointFrom2dCurveOnParam(e){const t=e.shape.Value(e.param),r=[t.X(),t.Y()];return t.delete(),r}geomCircleCurve(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.curve)}geomEllipseCurve(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.curve)}}class j{constructor(e,t){this.occ=e,this.och=t}cylindricalSurface(e){const t=this.och.entitiesService.gpAx3(e.center,e.direction),r=new this.occ.Geom_CylindricalSurface_1(t,e.radius);return t.delete(),r}surfaceFromFace(e){return this.och.surfaceFromFace(e)}}class q{constructor(e,t){this.curves=new z(e,t),this.surfaces=new j(e,t)}}class ${constructor(e,t){this.occ=e,this.och=t}makeEdgeFromGeom2dCurveAndSurface(e){return this.och.edgesService.makeEdgeFromGeom2dCurveAndSurface(e)}line(e){return this.och.edgesService.lineEdge(e)}arcThroughThreePoints(e){return this.och.edgesService.arcThroughThreePoints(e)}arcThroughTwoPointsAndTangent(e){return this.och.edgesService.arcThroughTwoPointsAndTangent(e)}arcFromCircleAndTwoPoints(e){return this.och.edgesService.arcFromCircleAndTwoPoints(e)}arcFromCircleAndTwoAngles(e){return this.och.edgesService.arcFromCircleAndTwoAngles(e)}arcFromCirclePointAndAngle(e){return this.och.edgesService.arcFromCirclePointAndAngle(e)}createCircleEdge(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.edge)}createEllipseEdge(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.edge)}removeInternalEdges(e){const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e.shape,!0,!0,!1);t.Build();const r=t.Shape();return t.delete(),r}getEdge(e){return this.och.shapeGettersService.getEdge(e)}edgesToPoints(e){return this.och.edgesService.edgesToPoints(e)}reversedEdge(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}pointOnEdgeAtParam(e){return this.och.edgesService.pointOnEdgeAtParam(e)}tangentOnEdgeAtParam(e){return this.och.edgesService.tangentOnEdgeAtParam(e)}startPointOnEdge(e){return this.och.edgesService.startPointOnEdge(e)}endPointOnEdge(e){return this.och.edgesService.endPointOnEdge(e)}pointOnEdgeAtLength(e){return this.och.edgesService.pointOnEdgeAtLength(e)}tangentOnEdgeAtLength(e){return this.och.edgesService.tangentOnEdgeAtLength(e)}divideEdgeByParamsToPoints(e){return this.och.edgesService.divideEdgeByParamsToPoints(e)}divideEdgeByEqualDistanceToPoints(e){return this.och.edgesService.divideEdgeByEqualDistanceToPoints(e)}getEdges(e){return this.och.shapeGettersService.getEdges(e)}getEdgesAlongWire(e){return this.och.edgesService.getEdgesAlongWire(e)}getCircularEdgesAlongWire(e){return this.och.edgesService.getCircularEdgesAlongWire(e)}getLinearEdgesAlongWire(e){return this.och.edgesService.getLinearEdgesAlongWire(e)}getEdgeLength(e){return this.och.edgesService.getEdgeLength(e)}getEdgesLengths(e){return this.och.edgesService.getEdgesLengths(e)}getEdgeCenterOfMass(e){return this.och.geomService.getLinearCenterOfMass(e)}getEdgesCentersOfMass(e){return this.och.edgesService.getEdgesCentersOfMass(e)}getCornerPointsOfEdgesForShape(e){return this.och.edgesService.getCornerPointsOfEdgesForShape(e)}getCircularEdgeCenterPoint(e){return this.och.edgesService.getCircularEdgeCenterPoint(e)}getCircularEdgeRadius(e){return this.och.edgesService.getCircularEdgeRadius(e)}getCircularEdgePlaneDirection(e){return this.och.edgesService.getCircularEdgePlaneDirection(e)}constraintTanLinesFromTwoPtsToCircle(e){return this.och.edgesService.constraintTanLinesFromTwoPtsToCircle(e)}constraintTanLinesFromPtToCircle(e){return this.och.edgesService.constraintTanLinesFromPtToCircle(e)}constraintTanLinesOnTwoCircles(e){return this.och.edgesService.constraintTanLinesOnTwoCircles(e)}constraintTanCirclesOnTwoCircles(e){return this.och.edgesService.constraintTanCirclesOnTwoCircles(e)}constraintTanCirclesOnCircleAndPnt(e){return this.och.edgesService.constraintTanCirclesOnCircleAndPnt(e)}}class Y{constructor(e,t){this.occ=e,this.och=t}createFaceFromWire(e){return this.och.facesService.createFaceFromWire(e)}createFaceFromWires(e){return this.och.facesService.createFaceFromWires(e)}createFacesFromWires(e){return this.och.facesService.createFacesFromWires(e)}faceFromSurface(e){return this.och.facesService.faceFromSurface(e)}faceFromSurfaceAndWire(e){return this.och.facesService.faceFromSurfaceAndWire(e)}getUMinBound(e){return this.och.facesService.getUMinBound(e)}getUMaxBound(e){return this.och.facesService.getUMaxBound(e)}getVMinBound(e){return this.och.facesService.getVMinBound(e)}getVMaxBound(e){return this.och.facesService.getVMaxBound(e)}subdivideToPointsControlled(e){return this.och.facesService.subdivideToPointsControlled(e)}subdivideToPoints(e){return this.och.facesService.subdivideToPoints(e)}subdivideToNormals(e){return this.och.facesService.subdivideToNormals(e)}subdivideToPointsOnParam(e){return this.och.facesService.subdivideToPointsOnParam(e)}subdivideToUVOnParam(e){return this.och.facesService.subdivideToUVOnParam(e)}subdivideToUV(e){return this.och.facesService.subdivideToUV(e)}uvOnFace(e){return this.och.facesService.uvOnFace(e)}pointsOnUVs(e){return this.och.facesService.pointsOnUVs(e)}normalsOnUVs(e){return this.och.facesService.normalsOnUVs(e)}pointOnUV(e){return this.och.facesService.pointOnUV(e)}normalOnUV(e){return this.och.facesService.faceNormalOnUV(e)}createPolygonFace(e){return this.och.facesService.createPolygonFace(e)}createCircleFace(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.face)}createEllipseFace(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.face)}createSquareFace(e){return this.och.facesService.createSquareFace(e)}createRectangleFace(e){return this.och.facesService.createRectangleFace(e)}createFaceFromMultipleCircleTanWireCollections(e){return this.och.facesService.createFaceFromMultipleCircleTanWireCollections(e)}createFaceFromMultipleCircleTanWires(e){return this.och.facesService.createFaceFromMultipleCircleTanWires(e)}getFace(e){return this.och.shapeGettersService.getFace(e)}getFaces(e){return this.och.shapeGettersService.getFaces(e)}reversedFace(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}getFaceArea(e){return this.och.facesService.getFaceArea(e)}getFacesAreas(e){return this.och.facesService.getFacesAreas(e)}getFaceCenterOfMass(e){return this.och.facesService.getFaceCenterOfMass(e)}getFacesCentersOfMass(e){return this.och.facesService.getFacesCentersOfMass(e)}filterFacePoints(e){return this.och.facesService.filterFacePoints(e)}}class X{constructor(e,t){this.occ=e,this.och=t}makeCompound(e){return this.och.converterService.makeCompound(e)}}class Z{constructor(e,t){this.occ=e,this.och=t}vertexFromPoint(e){return this.och.entitiesService.makeVertex(e.point)}verticesFromPoints(e){return e.points.map((e=>this.vertexFromPoint({point:e})))}verticesCompoundFromPoints(e){const t=this.verticesFromPoints(e);return this.och.converterService.makeCompound({shapes:t})}getVertices(e){return this.och.shapeGettersService.getVertices(e)}getVerticesAsPoints(e){return this.och.verticesService.getVerticesAsPoints(e)}verticesToPoints(e){return this.och.verticesService.verticesToPoints(e)}vertexToPoint(e){return this.och.converterService.vertexToPoint(e)}}class J{constructor(e,t){this.occ=e,this.och=t}purgeInternalEdges(e){const t=new this.occ.TopOpeBRepTool_PurgeInternalEdges(e.shape,!0);if(t.Perform(),t.IsDone())return t.Shape();throw new Error("Could not purge internal edges for the shape")}unifySameDomain(e){const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e.shape,e.unifyEdges,e.unifyFaces,e.concatBSplines);return t.Build(),t.Shape()}isClosed(e){return e.shape.Closed_1()}isConvex(e){return e.shape.Convex_1()}isChecked(e){return e.shape.Checked_1()}isFree(e){return e.shape.Free_1()}isInfinite(e){return e.shape.Infinite_1()}isModified(e){return e.shape.Modified_1()}isLocked(e){return e.shape.Locked_1()}isNull(e){return e.shape.IsNull()}isEqual(e){return e.shape.IsEqual(e.otherShape)}isNotEqual(e){return e.shape.IsNotEqual(e.otherShape)}isPartner(e){return e.shape.IsPartner(e.otherShape)}isSame(e){return e.shape.IsSame(e.otherShape)}getOrientation(e){const t=e.shape.Orientation_1();let r;return t===this.occ.TopAbs_Orientation.TopAbs_FORWARD?r=U.topAbsOrientationEnum.forward:t===this.occ.TopAbs_Orientation.TopAbs_REVERSED?r=U.topAbsOrientationEnum.reversed:t===this.occ.TopAbs_Orientation.TopAbs_INTERNAL?r=U.topAbsOrientationEnum.internal:t===this.occ.TopAbs_Orientation.TopAbs_EXTERNAL&&(r=U.topAbsOrientationEnum.external),r}getShapeType(e){return this.och.enumService.getShapeTypeEnum(e.shape)}}class Q{constructor(e,t){this.occ=e,this.och=t}sewFaces(e){return this.och.shellsService.sewFaces(e)}isClosed(e){return this.occ.BRep_Tool.IsClosed_1(e.shape)}getShellSurfaceArea(e){return this.och.shellsService.getShellSurfaceArea(e)}}class K{constructor(e,t){this.occ=e,this.och=t}fromClosedShell(e){return this.och.solidsService.fromClosedShell(e)}createBox(e){return this.och.solidsService.createBox(e)}createCube(e){return this.och.solidsService.createCube(e)}createBoxFromCorner(e){return this.och.solidsService.createBoxFromCorner(e)}createCylinder(e){return this.och.solidsService.createCylinder(e)}createCylindersOnLines(e){return this.och.solidsService.createCylindersOnLines(e)}createSphere(e){return this.och.solidsService.createSphere(e)}createCone(e){return this.och.solidsService.createCone(e)}getSolidSurfaceArea(e){return this.och.solidsService.getSolidSurfaceArea(e)}getSolidVolume(e){return this.och.solidsService.getSolidVolume(e)}getSolidsVolumes(e){return this.och.solidsService.getSolidsVolumes(e)}getSolidCenterOfMass(e){return this.och.solidsService.getSolidCenterOfMass(e)}getSolidsCentersOfMass(e){return this.och.solidsService.getSolidsCentersOfMass(e)}getSolids(e){return this.och.solidsService.getSolids(e)}filterSolidPoints(e){return this.och.solidsService.filterSolidPoints(e)}}class ee{constructor(e,t){this.occ=e,this.och=t}createPolygonWire(e){return this.och.wiresService.createPolygonWire(e)}createPolygons(e){const t=e.polygons.map((e=>this.createPolygonWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createPolylineWire(e){return this.och.wiresService.createPolylineWire(e)}createPolylines(e){const t=e.polylines.map((e=>this.createPolylineWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createLineWire(e){return this.och.wiresService.createLineWire(e)}createLines(e){const t=e.lines.map((e=>this.createLineWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createBezier(e){return this.och.wiresService.createBezier(e)}createBezierWires(e){const t=e.bezierWires.map((e=>this.createBezier(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}interpolatePoints(e){return this.och.wiresService.interpolatePoints(e)}interpolateWires(e){const t=e.interpolations.map((e=>this.interpolatePoints(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}splitOnPoints(e){return this.och.wiresService.splitOnPoints(e)}combineEdgesAndWiresIntoAWire(e){return this.och.converterService.combineEdgesAndWiresIntoAWire(e)}createWireFromEdge(e){return this.och.wiresService.createWireFromEdges(e)}addEdgesAndWiresToWire(e){return this.och.wiresService.addEdgesAndWiresToWire(e)}createBSpline(e){return this.och.wiresService.createBSpline(e)}createBSplines(e){const t=e.bSplines.map((e=>this.createBSpline(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createZigZagBetweenTwoWires(e){return this.och.wiresService.createZigZagBetweenTwoWires(e)}divideWireByParamsToPoints(e){return this.och.wiresService.divideWireByParamsToPoints(e)}divideWiresByParamsToPoints(e){return e.shapes.map((t=>this.divideWireByParamsToPoints(Object.assign(Object.assign({},e),{shape:t}))))}divideWireByEqualDistanceToPoints(e){return this.och.wiresService.divideWireByEqualDistanceToPoints(e)}divideWiresByEqualDistanceToPoints(e){return e.shapes.map((t=>this.divideWireByEqualDistanceToPoints(Object.assign(Object.assign({},e),{shape:t}))))}pointOnWireAtParam(e){return this.och.wiresService.pointOnWireAtParam(e)}pointOnWireAtLength(e){return this.och.wiresService.pointOnWireAtLength(e)}tangentOnWireAtParam(e){return this.och.wiresService.tangentOnWireAtParam(e)}tangentOnWireAtLength(e){return this.och.wiresService.tangentOnWireAtLength(e)}derivativesOnWireAtLength(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1),i=new this.occ.GCPnts_AbscissaPoint_2(r,e.length,r.FirstParameter()),n=i.Parameter(),s=this.och.entitiesService.gpPnt([0,0,0]),o=this.och.entitiesService.gpVec([0,0,0]),a=this.och.entitiesService.gpVec([0,0,0]),c=this.och.entitiesService.gpVec([0,0,0]);r.D3(n,s,o,a,c);const h=[[o.X(),o.Y(),o.Z()],[a.X(),a.Y(),a.Z()],[c.X(),c.Y(),c.Z()]];return o.delete(),a.delete(),c.delete(),r.delete(),i.delete(),s.delete(),h}derivativesOnWireAtParam(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1),i=this.och.entitiesService.gpPnt([0,0,0]),n=this.och.entitiesService.gpVec([0,0,0]),s=this.och.entitiesService.gpVec([0,0,0]),o=this.och.entitiesService.gpVec([0,0,0]),a=this.och.vecHelper.remap(e.param,0,1,r.FirstParameter(),r.LastParameter());r.D3(a,i,n,s,o);const c=[[n.X(),n.Y(),n.Z()],[s.X(),s.Y(),s.Z()],[o.X(),o.Y(),o.Z()]];return n.delete(),s.delete(),o.delete(),r.delete(),i.delete(),c}startPointOnWire(e){return this.och.wiresService.startPointOnWire(e)}endPointOnWire(e){return this.och.wiresService.endPointOnWire(e)}createCircleWire(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.wire)}createEllipseWire(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.wire)}createSquareWire(e){return this.och.wiresService.createSquareWire(e)}createStarWire(e){return this.och.wiresService.createStarWire(e)}createChristmasTreeWire(e){return this.och.wiresService.createChristmasTreeWire(e)}createParallelogramWire(e){return this.och.wiresService.createParallelogramWire(e)}createHeartWire(e){return this.och.wiresService.createHeartWire(e)}createNGonWire(e){return this.och.wiresService.createNGonWire(e)}createRectangleWire(e){return this.och.wiresService.createRectangleWire(e)}createLPolygonWire(e){return this.och.wiresService.createLPolygonWire(e)}getWire(e){return this.och.shapeGettersService.getWire(e)}getWires(e){return this.och.shapeGettersService.getWires(e)}getWireLength(e){return this.och.wiresService.getWireLength(e)}getWiresLengths(e){return this.och.wiresService.getWiresLengths(e)}getWireCenterOfMass(e){return this.och.wiresService.getWireCenterOfMass(e)}getWiresCentersOfMass(e){return e.shapes.map((e=>this.och.wiresService.getWireCenterOfMass({shape:e})))}reversedWire(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}reversedWireFromReversedEdges(e){const t=e.shape,r=this.och.edgesService.getEdgesAlongWire({shape:t}).map((e=>this.och.converterService.getActualTypeOfShape(e.Reversed()))),i=this.och.converterService.combineEdgesAndWiresIntoAWire({shapes:r.reverse()}),n=this.och.converterService.getActualTypeOfShape(i);return i.delete(),r.forEach((e=>e.delete())),n}placeWireOnFace(e){const t=e.wire,r=e.face,i=this.och.surfaceFromFace({shape:r});return this.och.wiresService.placeWire(t,i)}placeWiresOnFace(e){const t=e.wires,r=e.face,i=this.och.surfaceFromFace({shape:r});return t.map((e=>this.och.wiresService.placeWire(e,i)))}closeOpenWire(e){const t=e.shape,r=this.och.wiresService.startPointOnWire({shape:t}),i=this.och.wiresService.endPointOnWire({shape:t});if(this.och.vecHelper.vectorsTheSame(r,i,1e-7))return t;const n=this.createLineWire({start:i,end:r}),s=this.addEdgesAndWiresToWire({shape:t,shapes:[n]});return n.delete(),s}project(e){const t=e.wire,r=this.och.entitiesService.gpDir(e.direction),i=new this.occ.BRepProj_Projection_1(t,e.shape,r),n=i.Shape();return r.delete(),i.delete(),n}wiresToPoints(e){const t=this.getWires({shape:e.shape}),r=[];return t.forEach((t=>{const i=this.och.edgesService.edgesToPoints(Object.assign(Object.assign({},e),{shape:t})).flat(),n=this.och.vecHelper.removeConsecutiveDuplicates(i,!1);r.push(n)})),r}projectWires(e){const t=[];return e.wires.forEach((r=>{const i=this.och.entitiesService.gpDir(e.direction),n=new this.occ.BRepProj_Projection_1(r,e.shape,i),s=n.Shape();t.push(s),i.delete(),n.delete()})),t}createWireFromTwoCirclesTan(e){return this.och.wiresService.createWireFromTwoCirclesTan(e)}}class te{constructor(e,t){this.vertex=new Z(e,t),this.edge=new $(e,t),this.wire=new ee(e,t),this.face=new Y(e,t),this.shell=new Q(e,t),this.solid=new K(e,t),this.compound=new X(e,t),this.shape=new J(e,t)}}class re{constructor(e){this.occ=e}BRep_Tool_Range_1(e,t,r){return this.occ.BRep_Tool.Range_1(e,t,r)}BRep_Tool_Curve_2(e,t,r){return this.occ.BRep_Tool.Curve_2(e,t,r)}BRepTools_UVBounds_1(e,t,r,i,n){return this.occ.BRepTools.UVBounds_1(e,t,r,i,n)}}class ie{constructor(e){this.occ=e}forEachWire(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_WIRE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_WIRE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Wire_2(i.Current()));i.delete()}forEachEdge(e,t){const r={};let i=0;const n=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(n.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);n.More();n.Next()){const e=this.occ.TopoDS.Edge_1(n.Current()),s=e.HashCode(1e8);Object.prototype.hasOwnProperty.call(r,s)||(r[s]=i,i++,t(i,e))}return n.delete(),r}forEachEdgeAlongWire(e,t){const r={};let i=0;const n=new this.occ.BRepTools_WireExplorer_1;for(n.Init_1(e);n.More();n.Next()){const e=this.occ.TopoDS.Edge_1(n.Current()),s=e.HashCode(1e8);Object.prototype.hasOwnProperty.call(r,s)||(r[s]=i,i++,t(i,e))}return n.delete(),r}forEachFace(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_FACE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_FACE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Face_1(i.Current()));i.delete()}forEachShell(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_SHELL,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_SHELL,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Shell_1(i.Current()));i.delete()}forEachVertex(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Vertex_1(i.Current()));i.delete()}forEachSolid(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_SOLID,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_SOLID,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Solid_2(i.Current()));i.delete()}}class ne{constructor(e){this.occ=e}getShapeTypeEnum(e){let t=U.shapeTypeEnum.unknown;const r=e.ShapeType();return t=r===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?U.shapeTypeEnum.edge:r===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?U.shapeTypeEnum.wire:r===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?U.shapeTypeEnum.vertex:r===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?U.shapeTypeEnum.solid:r===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?U.shapeTypeEnum.shell:r===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?U.shapeTypeEnum.face:r===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?U.shapeTypeEnum.compSolid:r===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?U.shapeTypeEnum.compound:U.shapeTypeEnum.shape,t}getGccEntPositionFromEnum(e){let t=this.occ.GccEnt_Position.GccEnt_noqualifier;return t=e===U.gccEntPositionEnum.unqualified?this.occ.GccEnt_Position.GccEnt_unqualified:e===U.gccEntPositionEnum.enclosed?this.occ.GccEnt_Position.GccEnt_enclosed:e===U.gccEntPositionEnum.enclosing?this.occ.GccEnt_Position.GccEnt_enclosing:e===U.gccEntPositionEnum.outside?this.occ.GccEnt_Position.GccEnt_outside:(U.gccEntPositionEnum.noqualifier,this.occ.GccEnt_Position.GccEnt_noqualifier),t}getTopAbsStateEnum(e){let t=U.topAbsStateEnum.unknown;return t=e===this.occ.TopAbs_State.TopAbs_IN?U.topAbsStateEnum.in:e===this.occ.TopAbs_State.TopAbs_OUT?U.topAbsStateEnum.out:e===this.occ.TopAbs_State.TopAbs_ON?U.topAbsStateEnum.on:U.topAbsStateEnum.unknown,t}convertFourSidesStrictEnumToTwoCircleInclusionEnum(e){return e===U.fourSidesStrictEnum.inside?U.twoCircleInclusionEnum.inside:e===U.fourSidesStrictEnum.outside?U.twoCircleInclusionEnum.outside:e===U.fourSidesStrictEnum.insideOutside?U.twoCircleInclusionEnum.insideOutside:e===U.fourSidesStrictEnum.outsideInside?U.twoCircleInclusionEnum.outsideInside:U.twoCircleInclusionEnum.none}}class se{constructor(e){this.occ=e}getActualTypeOfShape(e){let t=e;return t=e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?this.occ.TopoDS.Edge_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?this.occ.TopoDS.Wire_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?this.occ.TopoDS.Vertex_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?this.occ.TopoDS.Solid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?this.occ.TopoDS.Shell_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?this.occ.TopoDS.Face_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.occ.TopoDS.CompSolid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.occ.TopoDS.Compound_1(e):e,t}combineEdgesAndWiresIntoAWire(e){if(void 0===e.shapes)throw Error("Shapes are not defined");const t=new this.occ.BRepBuilderAPI_MakeWire_1;if(e.shapes.forEach((e=>{e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?t.Add_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE&&t.Add_2(e)})),t.IsDone()){this.occ.BRepLib.BuildCurves3d_1(t.Wire(),1e-7,this.occ.GeomAbs_Shape.GeomAbs_C1,14,0);const e=t.Wire();return t.delete(),e}{let e;const r=t.Error();throw t.delete(),r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_DisconnectedWire?e="Wire is disconnected and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_EmptyWire?e="Wire is empty and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_NonManifoldWire?e="Wire is non manifold and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_WireDone&&(e="Wire is done"),new Error(e)}}vertexToPoint(e){const t=this.occ.BRep_Tool.Pnt(e.shape),r=[t.X(),t.Y(),t.Z()];return t.delete(),r}getGeomCurveFromEdge(e,t,r){const i=e.Location_1();return this.occ.BRep_Tool.Curve_1(e,i,t,r).get()}makeCompound(e){const t=new this.occ.TopoDS_Compound,r=new this.occ.BRep_Builder;return r.MakeCompound(t),e.shapes.forEach((e=>{const i=new this.occ.BRepBuilderAPI_Copy_2(e,!0,!1),n=i.Shape();r.Add(t,n),i.delete(),n.delete()})),r.delete(),t}makeCompoundIfNeeded(e,t){if(t){const t=this.makeCompound({shapes:e});return e.forEach((e=>e.delete())),t}return e}}class oe{constructor(e){this.occ=e}createCircle(e,t,r,i){const n=this.gcMakeCircle(t,r,e);if(i===U.typeSpecificityEnum.curve)return n;{const e=this.bRepBuilderAPIMakeEdge(n);if(i===U.typeSpecificityEnum.edge)return e;{const t=this.bRepBuilderAPIMakeWire(e);if(i===U.typeSpecificityEnum.wire)return e.delete(),t;if(i===U.typeSpecificityEnum.face)return this.bRepBuilderAPIMakeFaceFromWire(t,!0)}}return n}createEllipse(e,t,r,i,n){const s=this.gcMakeEllipse(r,i,e,t);if(n===U.typeSpecificityEnum.curve)return s;{const e=this.bRepBuilderAPIMakeEdge(s);if(n===U.typeSpecificityEnum.edge)return e;{const t=this.bRepBuilderAPIMakeWire(e);if(n===U.typeSpecificityEnum.wire)return e.delete(),t;if(n===U.typeSpecificityEnum.face)return this.bRepBuilderAPIMakeFaceFromWire(t,!0)}}return s}makeVertex(e){const t=this.gpPnt(e),r=new this.occ.BRepBuilderAPI_MakeVertex(t),i=r.Vertex();return t.delete(),r.delete(),i}gpPnt2d(e){return new this.occ.gp_Pnt2d_3(e[0],e[1])}gpPnt(e){return new this.occ.gp_Pnt_3(e[0],e[1],e[2])}gpVec(e){return new this.occ.gp_Vec_4(e[0],e[1],e[2])}gpXYZ(e){return new this.occ.gp_XYZ_2(e[0],e[1],e[2])}gpVec2d(e){return new this.occ.gp_Vec2d_4(e[0],e[1])}gpDir(e){return new this.occ.gp_Dir_4(e[0],e[1],e[2])}gpDir2d(e){return new this.occ.gp_Dir2d_4(e[0],e[1])}gcMakeCircle(e,t,r){const i=new this.occ.GC_MakeCircle_2(this.gpAx2(e,t),r),n=i.Value().get();return i.delete(),n}gcMakeEllipse(e,t,r,i){const n=this.gpAx2(e,t),s=new this.occ.GC_MakeEllipse_2(n,i,r);if(s.IsDone()){const e=s.Value().get();return s.delete(),n.delete(),e}throw new Error("Ellipse could not be created.")}bRepBuilderAPIMakeEdge(e){const t=this.castToHandleGeomCurve(e),r=new this.occ.BRepBuilderAPI_MakeEdge_24(t),i=r.Edge();return r.delete(),t.delete(),i}bRepBuilderAPIMakeWire(e){const t=new this.occ.BRepBuilderAPI_MakeWire_2(e),r=t.Wire();return t.delete(),r}bRepBuilderAPIMakeShell(e){const t=this.occ.BRep_Tool.Surface_2(e),r=new this.occ.BRepBuilderAPI_MakeShell_2(t,!1),i=r.Shell();return r.delete(),t.delete(),i}bRepBuilderAPIMakeFaceFromWires(e,t){let r;const i=[];return e.forEach((e=>{if(i.length>0){const t=new this.occ.BRepBuilderAPI_MakeFace_22(i[i.length-1],e);i.push(t.Face()),t.delete()}else{const r=new this.occ.BRepBuilderAPI_MakeFace_15(e,t);i.push(r.Face()),r.delete()}})),i.length>0&&(r=i.pop(),i.forEach((e=>e.delete()))),r}bRepBuilderAPIMakeFaceFromWire(e,t){const r=new this.occ.BRepBuilderAPI_MakeFace_15(e,t),i=r.Face();return r.delete(),i}bRepBuilderAPIMakeFaceFromSurface(e,t){const r=new this.occ.Handle_Geom_Surface_2(e),i=new this.occ.BRepBuilderAPI_MakeFace_8(r,t),n=i.Face();return i.delete(),r.delete(),n}bRepBuilderAPIMakeFaceFromSurfaceAndWire(e,t,r){const i=new this.occ.Handle_Geom_Surface_2(e),n=new this.occ.BRepBuilderAPI_MakeFace_21(i,t,r),s=n.Face();return n.delete(),i.delete(),s}bRepPrimAPIMakeSphere(e,t,r){const i=this.gpAx2(e,t),n=new this.occ.BRepPrimAPI_MakeSphere_9(i,r),s=n.Shape();return n.delete(),i.delete(),s}gpAx3(e,t){return new this.occ.gp_Ax3_4(this.gpPnt(e),this.gpDir(t))}gpAx2(e,t){return new this.occ.gp_Ax2_3(this.gpPnt(e),this.gpDir(t))}gpAx2FromTwoVectors(e,t,r){return new this.occ.gp_Ax2_2(this.gpPnt(e),this.gpDir(t),this.gpDir(r))}gpAx1(e,t){return new this.occ.gp_Ax1_2(this.gpPnt(e),this.gpDir(t))}gpAx2d(e,t){const r=this.gpPnt2d(e),i=this.gpDir2d(t);return new this.occ.gp_Ax2d_2(r,i)}gpAx22d(e,t,r){const i=this.gpPnt2d(e),n=this.gpDir2d(t),s=this.gpDir2d(r),o=new this.occ.gp_Ax22d_2(i,n,s);return n.delete(),s.delete(),i.delete(),o}gpPln(e,t){const r=this.gpPnt(e),i=this.gpDir(t),n=new this.occ.gp_Pln_3(r,i);return r.delete(),i.delete(),n}bRepPrimAPIMakeCylinder(e,t,r,i){const n=this.gpAx2(e,t),s=new this.occ.BRepPrimAPI_MakeCylinder_3(n,r,i),o=s.Shape();return s.delete(),n.delete(),o}bRepPrimAPIMakeCylinderBetweenPoints(e,t,r){const i=this.gpPnt(e),n=this.gpPnt(t),s=new this.occ.gp_Vec_5(i,n),o=s.Magnitude(),a=this.gpAx2(e,[s.X(),s.Y(),s.Z()]),c=new this.occ.BRepPrimAPI_MakeCylinder_3(a,r,o),h=c.Shape();return c.delete(),a.delete(),i.delete(),n.delete(),s.delete(),h}bRepPrimAPIMakeBox(e,t,r,i){const n=this.gpPnt([-e/2+i[0],-r/2+i[1],-t/2+i[2]]),s=new this.occ.BRepPrimAPI_MakeBox_3(n,e,r,t),o=s.Shape();return s.delete(),n.delete(),o}castToHandleGeomCurve(e){return new this.occ.Handle_Geom_Curve_2(e)}}class ae{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.occ=e,this.enumService=t,this.entitiesService=r,this.converterService=i,this.booleansService=n,this.shapeGettersService=s,this.edgesService=o,this.transformsService=a,this.vecHelper=c,this.wiresService=h,this.facesService=l,this.shellsService=u}loftAdvanced(e){if(e.periodic&&!e.closed)throw new Error("Cant construct periodic non closed loft.");const t=new this.occ.BRepOffsetAPI_ThruSections(e.makeSolid,e.straight,e.tolerance),r=[],i=[];if(e.startVertex){const r=this.entitiesService.makeVertex(e.startVertex);t.AddVertex(r),i.push(r)}if(e.closed&&!e.periodic)e.shapes.push(e.shapes[0]);else if(e.closed&&e.periodic){const i=[];e.shapes.forEach((t=>{this.enumService.getShapeTypeEnum(t)===U.shapeTypeEnum.edge&&(t=this.entitiesService.bRepBuilderAPIMakeWire(t));const r=this.wiresService.divideWireByParamsToPoints({shape:t,nrOfDivisions:e.nrPeriodicSections,removeStartPoint:!1,removeEndPoint:!1});i.push(r)}));for(let n=0;n<=e.nrPeriodicSections;n++){const s=i.map((e=>e[n])),o=this.wiresService.interpolatePoints({points:s,tolerance:e.tolerance,periodic:!0});t.AddWire(o),r.push(o)}}e.periodic||e.shapes.forEach((e=>{t.AddWire(e)}));const n=[];if(e.endVertex){const r=this.entitiesService.makeVertex(e.endVertex);t.AddVertex(r),n.push(r)}let s;e.useSmoothing&&t.SetSmoothing(e.useSmoothing),e.maxUDegree&&t.SetMaxDegree(e.maxUDegree),e.parType===U.approxParametrizationTypeEnum.approxChordLength?s=this.occ.Approx_ParametrizationType.Approx_ChordLength:e.parType===U.approxParametrizationTypeEnum.approxCentripetal?s=this.occ.Approx_ParametrizationType.Approx_Centripetal:e.parType===U.approxParametrizationTypeEnum.approxIsoParametric&&(s=this.occ.Approx_ParametrizationType.Approx_IsoParametric),s&&t.SetParType(s),t.CheckCompatibility(!1);const o=t.Shape(),a=this.converterService.getActualTypeOfShape(o);return o.delete(),t.delete(),r.forEach((e=>e.delete())),i.forEach((e=>e.delete())),n.forEach((e=>e.delete())),a}closestPointsBetweenTwoShapes(e,t){const r=new this.occ.Message_ProgressRange_1,i=new this.occ.BRepExtrema_DistShapeShape_2(e,t,this.occ.Extrema_ExtFlag.Extrema_ExtFlag_MIN,this.occ.Extrema_ExtAlgo.Extrema_ExtAlgo_Grad,r),n=new this.occ.Message_ProgressRange_1;if(i.Perform(n),i.IsDone()&&i.NbSolution()>0){const e=i.PointOnShape1(1),t=i.PointOnShape2(1);return[[e.X(),e.Y(),e.Z()],[t.X(),t.Y(),t.Z()]]}throw new Error("Closest points could not be found.")}closestPointsOnShapeFromPoints(e){return e.points.map((e=>this.entitiesService.makeVertex(e))).map((t=>this.closestPointsBetweenTwoShapes(t,e.shape))).map((e=>e[1]))}closestPointsOnShapesFromPoints(e){const t=e.points.map((e=>this.entitiesService.makeVertex(e))),r=[];return e.shapes.forEach((e=>{const i=t.map((t=>this.closestPointsBetweenTwoShapes(t,e)));r.push(...i.map((e=>e[1])))})),r}distancesToShapeFromPoints(e){return e.points.map((e=>this.entitiesService.makeVertex(e))).map((t=>this.closestPointsBetweenTwoShapes(t,e.shape))).map((e=>this.vecHelper.distanceBetweenPoints(e[0],e[1])))}loft(e){const t=new this.occ.BRepOffsetAPI_ThruSections(e.makeSolid,!1,1e-6);e.shapes.forEach((e=>{this.enumService.getShapeTypeEnum(e)===U.shapeTypeEnum.edge&&(e=this.entitiesService.bRepBuilderAPIMakeWire(e)),t.AddWire(e)})),t.CheckCompatibility(!1);const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);return r.delete(),t.delete(),i}offset(e){return this.offsetAdv({shape:e.shape,face:e.face,distance:e.distance,tolerance:e.tolerance,joinType:U.joinTypeEnum.arc,removeIntEdges:!1})}offsetAdv(e){if(e.tolerance||(e.tolerance=.1),0===e.distance)return e.shape;let t;const r=this.getJoinType(e.joinType),i=this.occ.BRepOffset_Mode.BRepOffset_Skin,n=[];if(this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.wire||this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge){let s;this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge?(s=this.entitiesService.bRepBuilderAPIMakeWire(e.shape),n.push(s)):s=e.shape;try{t=new this.occ.BRepOffsetAPI_MakeOffset_1,e.face?t.Init_1(e.face,r,!1):t.Init_2(r,!1),t.AddWire(s);const i=new this.occ.Message_ProgressRange_1;t.Build(i),t.Perform(e.distance,0)}catch(n){t=new this.occ.BRepOffsetAPI_MakeOffsetShape,t.PerformByJoin(s,e.distance,e.tolerance,i,!1,!1,r,e.removeIntEdges,new this.occ.Message_ProgressRange_1)}}else{const n=e.shape;t=new this.occ.BRepOffsetAPI_MakeOffsetShape,t.PerformByJoin(n,e.distance,e.tolerance,i,!1,!1,r,e.removeIntEdges,new this.occ.Message_ProgressRange_1)}const s=t.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),t&&t.delete(),n.forEach((e=>e.delete())),o}offset3DWire(e){const t=this.extrude({shape:e.shape,direction:e.direction}),r=this.makeThickSolidSimple({shape:t,offset:e.offset}),i=this.shapeGettersService.getEdges({shape:e.shape}).length,n=(4*i+2)/2-1,s=n-i+1,o=[];let a;this.shapeGettersService.getFaces({shape:r}).forEach(((e,t)=>{if(t>=s&&t<=n){const t=this.shapeGettersService.getEdges({shape:e})[2];o.push(t)}}));try{a=this.converterService.combineEdgesAndWiresIntoAWire({shapes:o}),a=a.Reversed(),a=this.converterService.getActualTypeOfShape(a)}catch(e){return a=o,a}return a}extrudeShapes(e){return e.shapes.map((t=>{const r=this.extrude({shape:t,direction:e.direction}),i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}))}extrude(e){const t=new this.occ.gp_Vec_4(e.direction[0],e.direction[1],e.direction[2]),r=new this.occ.BRepPrimAPI_MakePrism_1(e.shape,t,!1,!0),i=r.Shape();return r.delete(),t.delete(),i}splitShapeWithShapes(e){const t=new this.occ.TopTools_ListOfShape_1;return e.shapes.forEach((e=>{t.Append_1(e)})),this.occ.BitByBitDev.BitSplit(e.shape,t)}revolve(e){let t;if(e.angle||(e.angle=360),e.direction||(e.direction=[0,0,1]),e.angle>=360){const r=new this.occ.gp_Pnt_3(0,0,0),i=new this.occ.gp_Dir_4(e.direction[0],e.direction[1],e.direction[2]),n=new this.occ.gp_Ax1_2(r,i),s=new this.occ.BRepPrimAPI_MakeRevol_2(e.shape,n,e.copy);t=s.Shape(),s.delete(),r.delete(),i.delete(),n.delete()}else{const r=new this.occ.gp_Pnt_3(0,0,0),i=new this.occ.gp_Dir_4(e.direction[0],e.direction[1],e.direction[2]),n=new this.occ.gp_Ax1_2(r,i),s=new this.occ.BRepPrimAPI_MakeRevol_1(e.shape,n,.0174533*e.angle,e.copy);t=s.Shape(),s.delete(),r.delete(),i.delete(),n.delete()}const r=this.converterService.getActualTypeOfShape(t);return t.delete(),r}rotatedExtrude(e){const t=this.transformsService.translate({translation:[0,e.height,0],shape:e.shape}),r=this.transformsService.rotate({axis:[0,1,0],angle:e.angle,shape:t}),i=this.wiresService.createBSpline({points:[[0,0,0],[0,e.height,0]],closed:!1}),n=[];for(let t=0;t<=30;t++){const r=t/30;n.push([20*Math.sin(r*e.angle*.0174533),e.height*r,20*Math.cos(r*e.angle*.0174533)])}const s=this.wiresService.createBSpline({points:n,closed:!1}),o=new this.occ.BRepOffsetAPI_MakePipeShell(i);o.SetMode_5(s,!0,this.occ.BRepFill_TypeOfContact.BRepFill_NoContact),o.Add_1(e.shape,!1,!1),o.Add_1(r,!1,!1),o.Build(new this.occ.Message_ProgressRange_1),o.MakeSolid();const a=o.Shape(),c=this.converterService.getActualTypeOfShape(a);return a.delete(),o.delete(),s.delete(),i.delete(),r.delete(),t.delete(),c}pipe(e){const t=new this.occ.BRepOffsetAPI_MakePipeShell(e.shape);e.shapes.forEach((e=>{t.Add_1(e,!1,!1)})),t.Build(new this.occ.Message_ProgressRange_1),t.MakeSolid();const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);return r.delete(),t.delete(),i}pipePolylineWireNGon(e){const t=e.shape,r=[],i=this.shapeGettersService.getEdges({shape:t});i.forEach(((t,n)=>{const s=this.edgesService.startPointOnEdge({shape:t}),o=this.edgesService.tangentOnEdgeAtParam({shape:t,param:0});let a,c=o;if(n>0&&n{n.Add_1(e,!1,!1)})),n.Build(new this.occ.Message_ProgressRange_1),n.MakeSolid();const s=n.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),n.delete(),o}pipeWireCylindrical(e){const t=e.shape,r=[],i=this.shapeGettersService.getEdges({shape:t});i.forEach(((t,n)=>{const s=this.edgesService.startPointOnEdge({shape:t}),o=this.edgesService.tangentOnEdgeAtParam({shape:t,param:0});let a,c=o;if(n>0&&n{n.Add_1(e,!1,!1)})),n.Build(new this.occ.Message_ProgressRange_1),n.MakeSolid();const s=n.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),n.delete(),o}pipeWiresCylindrical(e){return e.shapes.map((t=>this.pipeWireCylindrical({shape:t,radius:e.radius})))}makeThickSolidSimple(e){const t=new this.occ.BRepOffsetAPI_MakeThickSolid;t.MakeThickSolidBySimple(e.shape,e.offset),t.Build(new this.occ.Message_ProgressRange_1);const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);let n=i;if(e.offset>0){const e=this.shapeGettersService.getFaces({shape:i}).map((e=>e.Reversed()));n=this.shellsService.sewFaces({shapes:e,tolerance:1e-7}),i.delete()}return t.delete(),r.delete(),n}makeThickSolidByJoin(e){const t=new this.occ.TopTools_ListOfShape_1;e.shapes.forEach((e=>{t.Append_1(e)}));const r=new this.occ.BRepOffsetAPI_MakeThickSolid,i=this.getJoinType(e.joinType);r.MakeThickSolidByJoin(e.shape,t,e.offset,e.tolerance,this.occ.BRepOffset_Mode.BRepOffset_Skin,e.intersection,e.selfIntersection,i,e.removeIntEdges,new this.occ.Message_ProgressRange_1);const n=r.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),r.delete(),t.delete(),s}getJoinType(e){let t;switch(e){case U.joinTypeEnum.arc:t=this.occ.GeomAbs_JoinType.GeomAbs_Arc;break;case U.joinTypeEnum.intersection:t=this.occ.GeomAbs_JoinType.GeomAbs_Intersection;break;case U.joinTypeEnum.tangent:t=this.occ.GeomAbs_JoinType.GeomAbs_Tangent}return t}getBRepOffsetMode(e){let t;switch(e){case U.bRepOffsetModeEnum.skin:t=this.occ.BRepOffset_Mode.BRepOffset_Skin;break;case U.bRepOffsetModeEnum.pipe:t=this.occ.BRepOffset_Mode.BRepOffset_Pipe;break;case U.bRepOffsetModeEnum.rectoVerso:t=this.occ.BRepOffset_Mode.BRepOffset_RectoVerso}return t}slice(e){if(e.step<=0)throw new Error("Step needs to be positive.");const{bbox:t,transformedShape:r}=this.createBBoxAndTransformShape(e.shape,e.direction),i=[];if(!t.IsThin(1e-4)){const{minY:n,maxY:s,maxDist:o}=this.computeBounds(t),a=[];for(let t=n;t=h?c:h;return l*=1.2,{minY:i,maxY:n,maxDist:l}}applySlices(e,t,r,i){const n=[];if(this.enumService.getShapeTypeEnum(e)===U.shapeTypeEnum.solid)n.push(e);else{const t=this.shapeGettersService.getSolids({shape:e});n.push(...t)}if(0===n.length)throw new Error("No solids found to slice.");n.forEach((e=>{const n=new U.IntersectionDto;n.keepEdges=!0,n.shapes=[e];const s=this.converterService.makeCompound({shapes:t});n.shapes.push(s),this.booleansService.intersection(n).forEach((e=>{if(e&&!e.IsNull()){const t=this.transformsService.align({shape:e,fromOrigin:[0,0,0],fromDirection:[0,1,0],toOrigin:[0,0,0],toDirection:r});i.push(t)}}))}))}}class ce{constructor(e,t,r,i){this.occ=e,this.converterService=t,this.entitiesService=r,this.vecHelper=i}alignAndTranslate(e){const t=this.align({shape:e.shape,fromOrigin:[0,0,0],fromDirection:[0,1,0],toOrigin:[0,0,0],toDirection:e.direction}),r=this.translate({shape:t,translation:e.center});return t.delete(),r}translate(e){const t=new this.occ.gp_Trsf_1,r=new this.occ.gp_Vec_4(e.translation[0],e.translation[1],e.translation[2]);t.SetTranslation_1(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),t.delete(),i.delete(),r.delete(),s}mirror(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx1(e.origin,e.direction);t.SetMirror_2(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),i.delete(),t.delete(),r.delete(),s}mirrorAlongNormal(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx2(e.origin,e.normal);t.SetMirror_3(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return r.delete(),n.delete(),i.delete(),t.delete(),s}rotate(e){let t;if(0!==e.angle){const t=new this.occ.gp_Trsf_1,r=new this.occ.gp_Vec_4(e.axis[0],e.axis[1],e.axis[2]),i=new this.occ.gp_Dir_4(e.axis[0],e.axis[1],e.axis[2]),n=new this.occ.gp_Pnt_3(0,0,0),s=new this.occ.gp_Ax1_2(n,i);t.SetRotation_1(s,this.vecHelper.degToRad(e.angle));const o=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),a=o.Shape(),c=this.converterService.getActualTypeOfShape(a);return a.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),t.delete(),c}t=e.shape;const r=this.converterService.getActualTypeOfShape(t);return 0!==e.angle&&t.delete(),r}align(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx3(e.fromOrigin,e.fromDirection),i=this.entitiesService.gpAx3(e.toOrigin,e.toDirection);t.SetDisplacement(r,i);const n=new this.occ.TopLoc_Location_2(t),s=e.shape.Moved(n,!1);t.delete(),r.delete(),i.delete();const o=this.converterService.getActualTypeOfShape(s);return s.delete(),o}}class he{constructor(e,t){this.occ=e,this.shapeGettersService=t}intersection(e){if(e.shapes.length<2)throw new Error("Intersection requires 2 or more shapes to be given");const t=e.shapes[0];let r=[];for(let i=1;i0&&(r=r.map((e=>{const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e,!0,!0,!1);t.Build();const r=t.Shape();return t.delete(),r}))),r}difference(e){let t=e.shape;const r=e.shapes;for(let e=0;e{t++})),t}getSolidFromCompound(e,t){if(!e||e.ShapeType()>this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID||e.IsNull())return console.error("Not a compound shape!"),e;t||(t=0);let r=e,i=0;return this.iteratorService.forEachSolid(e,((e,n)=>{e===t&&(r=this.occ.TopoDS.Solid_1(n)),i++})),0===i&&console.error("NO SOLIDS FOUND IN SHAPE!"),r.hash=e.hash+1,r}getEdges(e){if(e.shape&&this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge)return[e.shape];if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is of incorrect type");const t=[];return this.iteratorService.forEachEdge(e.shape,((e,r)=>{t.push(r)})),t}getEdge(e){if(!e.shape||e.shape.ShapeType&&e.shape.ShapeType()>this.occ.TopAbs_ShapeEnum.TopAbs_WIRE||e.shape.IsNull())throw new Error("Edge can not be found for shape that is not provided or is of incorrect type");e.index||(e.index=0);let t={},r=!1;if(this.iteratorService.forEachEdge(e.shape,((i,n)=>{i===e.index&&(t=n,r=!0)})),r)return t;throw new Error(`Edge can not be found for shape on index ${e.index}`)}getWires(e){const t=[];return this.iteratorService.forEachWire(e.shape,((e,r)=>{t.push(r)})),t}getWire(e){if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is null");const t=this.enumService.getShapeTypeEnum(e.shape);if(t===U.shapeTypeEnum.wire||t===U.shapeTypeEnum.edge||t===U.shapeTypeEnum.vertex)throw new Error("Shape is of incorrect type");let r;if(e.index||(e.index=0),this.iteratorService.forEachWire(e.shape,((t,i)=>{t===e.index&&(r=this.occ.TopoDS.Wire_1(i))})),!r)throw Error("Wire not found");return r}getFaces(e){const t=[];return this.iteratorService.forEachFace(e.shape,((e,r)=>{t.push(r)})),t}getSolids(e){const t=[];return this.iteratorService.forEachSolid(e.shape,((e,r)=>{t.push(r)})),t}getFace(e){if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is null");const t=this.enumService.getShapeTypeEnum(e.shape);if(t===U.shapeTypeEnum.wire||t===U.shapeTypeEnum.edge||t===U.shapeTypeEnum.vertex)throw new Error("Shape is of incorrect type");e.index||(e.index=0);let r={},i=0;if(this.iteratorService.forEachFace(e.shape,((t,n)=>{t===e.index&&(r=this.occ.TopoDS.Face_1(n)),i++})),i{t.push(r)})),t}}class ue{constructor(e,t,r,i,n,s,o,a,c,h){this.occ=e,this.occRefReturns=t,this.shapeGettersService=r,this.entitiesService=i,this.iteratorService=n,this.converterService=s,this.enumService=o,this.geomService=a,this.transformsService=c,this.vecHelper=h}getCornerPointsOfEdgesForShape(e){const t=this.shapeGettersService.getEdges(e);let r=[];return t.forEach((e=>{const t={current:0},i={current:0},n=this.occRefReturns.BRep_Tool_Curve_2(e,t,i);try{const e=n.get();if(e){const n=e.Value(t.current),s=e.Value(i.current),o=[n.X(),n.Y(),n.Z()],a=[s.X(),s.Y(),s.Z()];n.delete(),s.delete(),r.push(o),r.push(a)}}catch(e){console.log(e)}})),r.length>0&&(r=this.vecHelper.removeAllDuplicateVectors(r)),r}getCircularEdgesAlongWire(e){return this.getEdgesAlongWire(e).filter((e=>this.isEdgeCircular({shape:e})))}getLinearEdgesAlongWire(e){return this.getEdgesAlongWire(e).filter((e=>this.isEdgeLinear({shape:e})))}getEdgesAlongWire(e){if(e.shape&&this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge)return[e.shape];if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is of incorrect type");const t=[],r=this.fixEdgeOrientationsAlongWire(e);return this.iteratorService.forEachEdgeAlongWire(r,((e,r)=>{t.push(r)})),t}fixEdgeOrientationsAlongWire(e){const t=[];return this.iteratorService.forEachEdgeAlongWire(e.shape,((e,r)=>{t.push(r)})),this.converterService.combineEdgesAndWiresIntoAWire({shapes:t})}arcThroughThreePoints(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpPnt(e.middle),i=this.entitiesService.gpPnt(e.end),n=new this.occ.GC_MakeArcOfCircle_4(t,r,i),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),a}arcThroughTwoPointsAndTangent(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpVec(e.tangentVec),i=this.entitiesService.gpPnt(e.end),n=new this.occ.GC_MakeArcOfCircle_5(t,r,i),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),a}arcFromCircleAndTwoAngles(e){const t=this.getGpCircleFromEdge({shape:e.circle}),r=this.vecHelper.degToRad(e.alphaAngle1),i=this.vecHelper.degToRad(e.alphaAngle2),n=new this.occ.GC_MakeArcOfCircle_1(t,r,i,e.sense),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),n.delete(),s.delete(),o.delete(),a}arcFromCirclePointAndAngle(e){const t=this.getGpCircleFromEdge({shape:e.circle}),r=this.vecHelper.degToRad(e.alphaAngle),i=this.entitiesService.gpPnt(e.point),n=new this.occ.GC_MakeArcOfCircle_2(t,i,r,e.sense),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),n.delete(),i.delete(),s.delete(),o.delete(),a}lineEdge(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpPnt(e.end),i=new this.occ.GC_MakeSegment_1(t,r).Value(),n=i.get(),s=new this.occ.Handle_Geom_Curve_2(n),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return o.delete(),s.delete(),t.delete(),r.delete(),i.delete(),n.delete(),a}getEdgeLength(e){const t=e.shape,r=new this.occ.GProp_GProps_1;this.occ.BRepGProp.LinearProperties(t,r,!1,!1);const i=r.Mass();return r.delete(),i}getEdgesLengths(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getEdgeLength({shape:e})))}getEdgesCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.geomService.getLinearCenterOfMass({shape:e})))}edgesToPoints(e){const t=this.enumService.getShapeTypeEnum(e.shape);let r=[];r=t===U.shapeTypeEnum.edge?[e.shape]:t===U.shapeTypeEnum.wire?this.getEdgesAlongWire({shape:e.shape}):this.shapeGettersService.getEdges({shape:e.shape});const i=[],n=r.map((e=>this.startPointOnEdge({shape:e})));return r.forEach((t=>{const r=[],n=new this.occ.TopLoc_Location_1,s=new this.occ.BRepAdaptor_Curve_2(t),o=new this.occ.GCPnts_TangentialDeflection_2(s,e.angularDeflection,e.curvatureDeflection,e.minimumOfPoints,e.uTolerance,e.minimumLength),a=o.NbPoints(),c=[];for(let e=0;ee.delete())),n.delete(),s.delete(),o.delete()})),i.forEach(((e,t)=>{const r=this.vecHelper.distanceBetweenPoints(e[0],n[t]);this.vecHelper.distanceBetweenPoints(n[t],e[e.length-1]){const r=new this.occ.GCPnts_AbscissaPoint_2(t,e,t.FirstParameter()),i=r.Parameter();return r.delete(),i})).map((e=>{const r=this.entitiesService.gpPnt([0,0,0]);t.D0(e,r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}))}divideCurveToNrSegments(e,t,r){const i=e.shape,n=[];for(let i=0;i<=e.nrOfDivisions;i++){const s=i/e.nrOfDivisions,o=this.vecHelper.remap(s,0,1,t,r);n.push(o)}return e.removeStartPoint&&n.shift(),e.removeEndPoint&&n.pop(),n.map((e=>{const t=this.entitiesService.gpPnt([0,0,0]);i.D0(e,t);const r=[t.X(),t.Y(),t.Z()];return t.delete(),r}))}startPointOnCurve(e){const t=e.shape,r=this.entitiesService.gpPnt([0,0,0]);t.D0(t.FirstParameter(),r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}endPointOnCurve(e){const t=e.shape,r=this.entitiesService.gpPnt([0,0,0]);t.D0(t.LastParameter(),r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}getLinearCenterOfMass(e){const t=e.shape,r=new this.occ.GProp_GProps_1;this.occ.BRepGProp.LinearProperties(t,r,!1,!1);const i=r.CentreOfMass(),n=[i.X(),i.Y(),i.Z()];return r.delete(),n}}class pe{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.occ=e,this.occRefReturns=t,this.vecHelper=r,this.shapesHelperService=i,this.shapeGettersService=n,this.transformsService=s,this.enumService=o,this.entitiesService=a,this.converterService=c,this.geomService=h,this.edgesService=l,this.booleansService=u}getWireLength(e){return this.shapeGettersService.getEdges(e).map((e=>this.edgesService.getEdgeLength({shape:e}))).reduce(((e,t)=>e+t),0)}getWiresLengths(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getWireLength({shape:e})))}createRectangleWire(e){const t=e.width/2,r=e.length/2,i=[[t,0,r],[-t,0,r],[-t,0,-r],[t,0,-r]].reverse(),n=this.createPolygonWire({points:i}),s=this.transformsService.alignAndTranslate({shape:n,direction:e.direction,center:e.center});return n.delete(),s}createSquareWire(e){return this.createRectangleWire({width:e.size,length:e.size,center:e.center,direction:e.direction})}createChristmasTreeWire(e){const t=this.createLineWire({start:[e.innerDist,0,0],end:[0,e.height,0]}),r=this.createLineWire({start:[e.outerDist,0,0],end:[0,e.height,0]}),i=this.divideWireByEqualDistanceToPoints({shape:t,nrOfDivisions:e.nrSkirts,removeEndPoint:!1,removeStartPoint:!1}),n=this.divideWireByEqualDistanceToPoints({shape:r,nrOfDivisions:e.nrSkirts,removeEndPoint:!1,removeStartPoint:!1}),s=[];if(e.trunkWidth>0&&e.trunkHeight>0?(s.push([0,-e.trunkHeight,0]),s.push([e.trunkWidth/2,-e.trunkHeight,0]),s.push([e.trunkWidth/2,0,0])):s.push([0,0,0]),i.forEach(((t,r)=>{const i=n[r];0===r?s.push(i):0!==r&&r[-e[0],e[1],e[2]]));e.pop(),s.push(...e.reverse())}let o;if(e.trunkHeight>0&&e.trunkWidth>0){const t=s.map((t=>[t[0],t[1]+e.trunkHeight,t[2]]));o=this.createPolylineWire({points:t})}else o=this.createPolylineWire({points:s});const a=this.transformsService.rotate({shape:o,angle:e.rotation,axis:[0,1,0]});return this.transformsService.alignAndTranslate({shape:a,direction:e.direction,center:e.origin})}createStarWire(e){const t=this.shapesHelperService.starLines(e.innerRadius,e.outerRadius,e.numRays,e.half,e.offsetOuterEdges),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createParallelogramWire(e){const t=this.shapesHelperService.parallelogram(e.width,e.height,e.angle,e.aroundCenter),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createHeartWire(e){const t=e.sizeApprox/2,r=[[0,0,.7*t],[t/6,0,.9*t],[t/2,0,t],[.75*t,0,.9*t],[t,0,t/4],[t/2,0,-t/2],[0,0,-t]],i=r.map((e=>[-e[0],e[1],e[2]])),n=1e-5,s=this.interpolatePoints({points:r,periodic:!1,tolerance:n}),o=this.interpolatePoints({points:i.reverse(),periodic:!1,tolerance:n}),a=this.converterService.combineEdgesAndWiresIntoAWire({shapes:[s,o]}),c=this.transformsService.rotate({shape:a,angle:e.rotation,axis:[0,1,0]}),h=this.transformsService.alignAndTranslate({shape:c,direction:e.direction,center:e.center});return a.delete(),c.delete(),s.delete(),o.delete(),h}createNGonWire(e){const t=this.shapesHelperService.ngon(e.nrCorners,e.radius,[0,0]),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createLPolygonWire(e){let t;switch(e.align){case U.directionEnum.outside:t=this.shapesHelperService.polygonL(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;case U.directionEnum.inside:t=this.shapesHelperService.polygonLInverted(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;case U.directionEnum.middle:t=this.shapesHelperService.polygonLMiddle(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;default:t=this.shapesHelperService.polygonL(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond)}const r=this.createPolygonWire({points:t}),i=this.transformsService.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return r.delete(),i.delete(),n}createPolygonWire(e){const t=[];for(let r=0;re.delete())),void t.delete();{const e=i.get(),n=new this.occ.Handle_Geom_Curve_2(e),s=new this.occ.BRepBuilderAPI_MakeEdge_24(n),o=s.Edge(),a=new this.occ.BRepBuilderAPI_MakeWire_2(o),c=a.Wire();return i.Nullify(),i.delete(),n.Nullify(),n.delete(),s.delete(),o.delete(),a.delete(),r.forEach((e=>e.delete())),t.delete(),c}}splitOnPoints(e){const t=1e-7,r=this.startPointOnWire({shape:e.shape}),i=this.endPointOnWire({shape:e.shape}),n=this.vecHelper.vectorsTheSame(i,r,t);n||(e.points.some((e=>this.vecHelper.vectorsTheSame(e,r,t)))||e.points.push(r),e.points.some((e=>this.vecHelper.vectorsTheSame(e,i,t)))||e.points.push(i));const s=this.createLines({lines:e.points.map((e=>({start:e,end:[e[0],e[1]+t,e[2]]}))),returnCompound:!1}),o=this.booleansService.difference({shape:e.shape,shapes:s,keepEdges:!0}),a=this.shapeGettersService.getEdges({shape:o}),c=[];a.forEach((r=>{const i=c[c.length-1],n=this.edgesService.endPointOnEdge({shape:r}),s=this.edgesService.startPointOnEdge({shape:r}),o=e.points.some((e=>this.vecHelper.vectorsTheSame(n,e,t))),a=e.points.some((e=>this.vecHelper.vectorsTheSame(s,e,t)));o&&!a?c.push([r]):!o&&a?i?i.push(r):c.push([r]):o&&a?c.push([r]):o||a||(i?i.push(r):c.push([r]))}));const h=[];if(c.forEach((e=>{const t=this.converterService.combineEdgesAndWiresIntoAWire({shapes:e});h.push(t)})),n&&h.length>1){const r=this.endPointOnWire({shape:h[0]}),i=this.startPointOnWire({shape:h[h.length-1]});if(this.vecHelper.vectorsTheSame(r,i,t)&&!e.points.find((e=>this.vecHelper.vectorsTheSame(e,r,t)))){const e=this.addEdgesAndWiresToWire({shape:h[h.length-1],shapes:[h[0]]});h[0]=e,h.pop()}}return h}createLines(e){const t=e.lines.map((e=>this.createLineWire(e))).filter((e=>void 0!==e));return this.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createWireFromTwoCirclesTan(e){const t=this.shapeGettersService.getEdges({shape:e.circle1}),r=this.shapeGettersService.getEdges({shape:e.circle2});if(1===t.length&&1===r.length){const i=t[0],n=r[0],s=this.edgesService.constraintTanLinesOnTwoCircles({circle1:i,circle2:n,positionResult:e.keepLines===U.twoSidesStrictEnum.outside?U.positionResultEnum.keepSide2:U.positionResultEnum.keepSide1,circleRemainders:this.enumService.convertFourSidesStrictEnumToTwoCircleInclusionEnum(e.circleRemainders),tolerance:e.tolerance}),o=this.converterService.combineEdgesAndWiresIntoAWire({shapes:s});return s.forEach((e=>e.delete())),i.delete(),n.delete(),o}throw new Error("Could not find the edges of the provided circle wires.")}createZigZagBetweenTwoWires(e){const t=e.wire1,r=e.wire2,i=this.edgesService.getEdgesAlongWire({shape:t}),n=this.edgesService.getEdgesAlongWire({shape:r}),s=i.map((t=>this.edgesService.divideEdgeByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))),o=n.map((t=>this.edgesService.divideEdgeByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))),a=s.map(((t,r)=>{const i=o[r],n=[];for(let r=0;re.delete())),t.delete(),i.delete(),n.Nullify(),n.delete(),o.Nullify(),o.delete(),a.delete(),c.delete(),h.delete(),l}createBezier(e){const t=new this.occ.TColgp_Array1OfPnt_2(1,e.points.length+(e.closed?1:0));for(let r=1;r<=e.points.length;r++)t.SetValue(r,this.entitiesService.gpPnt(e.points[r-1]));e.closed&&t.SetValue(e.points.length+1,t.Value(1));const r=new this.occ.Geom_BezierCurve_1(t),i=new this.occ.Handle_Geom_Curve_2(r),n=new this.occ.BRepBuilderAPI_MakeEdge_24(i),s=n.Edge(),o=new this.occ.BRepBuilderAPI_MakeWire_2(s),a=o.Wire();return o.delete(),n.delete(),s.delete(),i.delete(),t.delete(),a}addEdgesAndWiresToWire(e){const t=new this.occ.BRepBuilderAPI_MakeWire_1;let r;if(t.Add_2(e.shape),e.shapes.forEach((e=>{e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?t.Add_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE&&t.Add_2(e)})),!t.IsDone())throw new Error("Wire could not be constructed. Check if edges and wires do not have disconnected elements.");return r=t.Wire(),t.delete(),r}startPointOnWire(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1);return this.geomService.startPointOnCurve(Object.assign(Object.assign({},e),{shape:r}))}endPointOnWire(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1);return this.geomService.endPointOnCurve(Object.assign(Object.assign({},e),{shape:r}))}placeWire(e,t){const r=this.shapeGettersService.getEdges({shape:e}),i=[];r.forEach((e=>{const r={current:0},n={current:0};this.occRefReturns.BRep_Tool_Range_1(e,r,n);const s=this.occRefReturns.BRep_Tool_Curve_2(e,r,n);if(!s.IsNull()){const e=this.entitiesService.gpPln([0,0,0],[0,1,0]),o=this.occ.GeomAPI.To2d(s,e),a=o.get(),c=this.edgesService.makeEdgeFromGeom2dCurveAndSurfaceBounded({curve:a,surface:t},r.current,n.current);c&&i.push(c),e.delete(),o.delete()}s.delete()})),r.forEach((e=>e.delete()));const n=this.converterService.combineEdgesAndWiresIntoAWire({shapes:i});return i.forEach((e=>e.delete())),n}}class fe{constructor(e,t,r,i,n,s,o,a){this.occ=e,this.occRefReturns=t,this.entitiesService=r,this.enumService=i,this.shapeGettersService=n,this.converterService=s,this.booleansService=o,this.wiresService=a}createFaceFromWire(e){let t;if(this.enumService.getShapeTypeEnum(e.shape)!==U.shapeTypeEnum.wire)throw new Error("Provided input shape is not a wire");if(e.planar){const r=this.occ.TopoDS.Wire_1(e.shape);t=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(r,e.planar),r.delete()}else{const r=3,i=15,n=2,s=!1,o=1e-5,a=1e-4,c=.01,h=.1,l=8,u=9,d=new this.occ.BRepFill_Filling(r,i,n,s,o,a,c,h,l,u),p=this.shapeGettersService.getEdges(e);if(p.forEach((e=>{d.Add_1(e,this.occ.GeomAbs_Shape.GeomAbs_C0,!0)})),d.Build(),!d.IsDone())throw new Error("Could not create non planar face");t=d.Face(),d.delete(),p.forEach((e=>e.delete()))}return t}getFaceArea(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.SurfaceProperties_1(e.shape,t,!1,!1);const r=t.Mass();return t.delete(),r}getFacesAreas(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getFaceArea({shape:e})))}getFaceCenterOfMass(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.SurfaceProperties_1(e.shape,t,!1,!1);const r=t.CentreOfMass(),i=[r.X(),r.Y(),r.Z()];return t.delete(),r.delete(),i}getFacesCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getFaceCenterOfMass({shape:e})))}filterFacePoints(e){const t=[];if(e.points.length>0){const r=new this.occ.BRepClass_FaceClassifier_1;return e.points.forEach((i=>{const n=this.entitiesService.gpPnt(i);r.Perform_2(e.shape,n,e.tolerance,e.useBndBox,e.gapTolerance);const s=r.State(),o=this.enumService.getTopAbsStateEnum(s);e.keepOn&&o===U.topAbsStateEnum.on&&t.push(i),e.keepIn&&o===U.topAbsStateEnum.in&&t.push(i),e.keepOut&&o===U.topAbsStateEnum.out&&t.push(i),e.keepUnknown&&o===U.topAbsStateEnum.unknown&&t.push(i),n.delete()})),r.delete(),t}return[]}createSquareFace(e){const t=this.wiresService.createSquareWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!0);return t.delete(),r}createRectangleFace(e){const t=this.wiresService.createRectangleWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!0);return t.delete(),r}createFaceFromMultipleCircleTanWires(e){const t=e.circles,r=[];if(e.combination===U.combinationCirclesForFaceEnum.allWithAll)for(let i=0;ithis.createFaceFromWire({shape:t,planar:e.planar})))}faceFromSurface(e){const t=this.entitiesService.bRepBuilderAPIMakeFaceFromSurface(e.shape,e.tolerance);if(t.IsNull())throw t.delete(),new Error("Could not construct a face from the surface. Check if surface is not infinite.");return t}faceFromSurfaceAndWire(e){const t=this.entitiesService.bRepBuilderAPIMakeFaceFromSurfaceAndWire(e.surface,e.wire,e.inside);if(t.IsNull())throw t.delete(),new Error("Could not construct a face from the surface. Check if surface is not infinite.");return t}getUMinBound(e){const t=e.shape,{uMin:r}=this.getUVBounds(t);return r}getUMaxBound(e){const t=e.shape,{uMax:r}=this.getUVBounds(t);return r}getVMinBound(e){const t=e.shape,{vMin:r}=this.getUVBounds(t);return r}getVMaxBound(e){const t=e.shape,{vMax:r}=this.getUVBounds(t);return r}subdivideToPointsControlled(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),i=r.get(),{uMin:n,uMax:s,vMin:o,vMax:a}=this.getUVBounds(t),c=[];for(let t=0;t{const t=i+(n-i)*e[0],a=s+(o-s)*e[1],c=this.entitiesService.gpPnt([0,0,0]);r.D0(t,a,c);const h=[c.X(),c.Y(),c.Z()];return c.delete(),h}));return r.delete(),a}normalsOnUVs(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),{uMin:i,uMax:n,vMin:s,vMax:o}=this.getUVBounds(t),a=e.paramsUV.map((e=>{const t=i+(n-i)*e[0],a=s+(o-s)*e[1],c=this.entitiesService.gpDir([0,1,0]);this.occ.GeomLib.NormEstim(r,this.entitiesService.gpPnt2d([t,a]),1e-7,c);const h=[c.X(),c.Y(),c.Z()];return c.delete(),h}));return r.delete(),a}pointOnUV(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),i=r.get(),{uMin:n,uMax:s,vMin:o,vMax:a}=this.getUVBounds(t),c=n+(s-n)*e.paramU,h=o+(a-o)*e.paramV,l=this.entitiesService.gpPnt([0,0,0]);i.D0(c,h,l);const u=[l.X(),l.Y(),l.Z()];return l.delete(),r.delete(),u}normalOnUV(e){return this.faceNormalOnUV(e)}createPolygonFace(e){const t=this.wiresService.createPolygonWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!1);return t.delete(),r}}class ge{constructor(e,t){this.occ=e,this.shapeGettersService=t}getVerticesAsPoints(e){const t=this.shapeGettersService.getVertices(e);return this.verticesToPoints({shapes:t})}verticesToPoints(e){return e.shapes.map((e=>{const t=this.occ.BRep_Tool.Pnt(e),r=[t.X(),t.Y(),t.Z()];return t.delete(),r}))}}class ve{constructor(e,t,r,i){this.occ=e,this.shapeGettersService=t,this.converterService=r,this.facesService=i}getShellSurfaceArea(e){const t=this.shapeGettersService.getFaces(e);return this.facesService.getFacesAreas({shapes:t}).reduce(((e,t)=>e+t),0)}sewFaces(e){const t=new this.occ.BRepBuilderAPI_Sewing(e.tolerance,!0,!0,!0,!1);e.shapes.forEach((e=>{t.Add(e)}));const r=new this.occ.Message_ProgressRange_1;t.Perform(r);const i=t.SewedShape(),n=this.converterService.getActualTypeOfShape(i);return t.delete(),r.delete(),i.delete(),n}}class me{constructor(e,t,r,i,n,s,o,a,c){this.occ=e,this.vecHelper=t,this.iteratorService=r,this.converterService=i,this.entitiesService=n,this.transformsService=s,this.shapeGettersService=o,this.edgesService=a,this.operationsService=c}filletEdges(e){if(!e.indexes||e.indexes.length&&0===e.indexes.length){if(void 0===e.radius)throw Error("Radius not defined");const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational),r=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE),i=[];for(;r.More();){const n=this.occ.TopoDS.Edge_1(r.Current());i.push(n),t.Add_2(e.radius,n),r.Next()}const n=t.Shape();return t.delete(),r.delete(),i.forEach((e=>e.delete())),n}if(e.indexes&&e.indexes.length>0){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);let r,i=0,n=0;const s=e.indexes;if(this.iteratorService.forEachEdge(e.shape,((r,o)=>{if(s.includes(r)){let r=e.radius;if(e.radiusList&&(r=e.radiusList[n],n++),void 0===r)throw Error("Radius not defined, or radiusList not correct length");t.Add_2(r,o),i++}})),0===i)throw new Error("Fillet Edges Not Found! Make sure you are looking at the object _before_ the Fillet is applied!");r=t.Shape(),t.delete();const o=this.converterService.getActualTypeOfShape(r);return r.delete(),o}}filletEdgesListOneRadius(e){if(e.edges&&e.edges.length>0){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach((r=>{t.Add_2(e.radius,r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesList(e){if(e.edges&&e.edges.length>0&&e.radiusList&&e.radiusList.length>0&&e.edges.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach(((r,i)=>{t.Add_2(e.radiusList[i],r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgeVariableRadius(e){if(e.paramsU&&e.paramsU.length>0&&e.radiusList&&e.radiusList.length>0&&e.paramsU.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);this.assignVariableFilletToEdge(e,t);const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesSameVariableRadius(e){if(e.edges&&e.edges.length>0&&e.radiusList&&e.radiusList.length>0&&e.paramsU.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach((r=>{this.assignVariableFilletToEdge({edge:r,paramsU:e.paramsU,radiusList:e.radiusList,shape:e.shape},t)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesVariableRadius(e){if(e.edges&&e.edges.length>0&&e.radiusLists&&e.radiusLists.length>0&&e.paramsULists.length===e.radiusLists.length&&e.paramsULists.length===e.edges.length&&e.radiusLists.length===e.edges.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach(((r,i)=>{this.assignVariableFilletToEdge({edge:r,paramsU:e.paramsULists[i],radiusList:e.radiusLists[i],shape:e.shape},t)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}assignVariableFilletToEdge(e,t){const r=new this.occ.TColgp_Array1OfPnt2d_2(1,e.paramsU.length);e.paramsU.forEach(((t,i)=>{r.SetValue(i+1,this.entitiesService.gpPnt2d([t,e.radiusList[i]]))})),t.Add_5(r,e.edge)}chamferEdges(e){if(!e.indexes||e.indexes.length&&0===e.indexes.length){if(void 0===e.distance)throw Error("Distance is undefined");const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE),i=[];for(;r.More();){const n=this.occ.TopoDS.Edge_1(r.Current());i.push(n),t.Add_2(e.distance,n),r.Next()}const n=t.Shape();return t.delete(),r.delete(),i.forEach((e=>e.delete())),n}if(e.indexes&&e.indexes.length>0){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);let r,i=0,n=0;const s=e.indexes;this.iteratorService.forEachEdge(e.shape,((r,o)=>{if(s.includes(r)){let r=e.distance;if(e.distanceList&&(r=e.distanceList[n],n++),void 0===r)throw Error("Distance not defined and/or distance list incorrect length");t.Add_2(r,o),i++}})),0===i?(console.error("Chamfer Edges Not Found! Make sure you are looking at the object _before_ the Fillet is applied!"),r=e.shape):r=t.Shape(),t.delete();const o=this.converterService.getActualTypeOfShape(r);return r.delete(),o}}chamferEdgesList(e){if(e.edges&&e.edges.length>0&&e.distanceList&&e.distanceList.length>0&&e.edges.length===e.distanceList.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{const n=e.distanceList[i];if(void 0===n)throw Error("Distance is not defined");t.Add_2(n,r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgeTwoDistances(e){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);t.Add_3(e.distance1,e.distance2,e.edge,e.face);const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}chamferEdgesTwoDistances(e){if(e.edges&&e.edges.length>0&&e.edges.length===e.faces.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{t.Add_3(e.distance1,e.distance2,r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgesTwoDistancesLists(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.distances1&&e.distances1.length>0&&e.distances2&&e.distances2.length>0&&e.edges.length===e.faces.length&&e.edges.length===e.distances1.length&&e.edges.length===e.distances2.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{t.Add_3(e.distances1[i],e.distances2[i],r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgeDistAngle(e){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=this.vecHelper.degToRad(e.angle);t.AddDA(e.distance,r,e.edge,e.face);const i=t.Shape();t.delete();const n=this.converterService.getActualTypeOfShape(i);return i.delete(),n}chamferEdgesDistsAngles(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.distances&&e.distances.length>0&&e.angles&&e.angles.length>0&&e.edges.length===e.distances.length&&e.edges.length===e.faces.length&&e.edges.length===e.angles.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{const n=this.vecHelper.degToRad(e.angles[i]);t.AddDA(e.distances[i],n,r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgesDistAngle(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.edges.length===e.faces.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=this.vecHelper.degToRad(e.angle);e.edges.forEach(((i,n)=>{t.AddDA(e.distance,r,i,e.faces[n])}));const i=t.Shape();t.delete();const n=this.converterService.getActualTypeOfShape(i);return i.delete(),n}}fillet3DWire(e){let t=!1;if(e.radiusList&&e.radiusList.length>0&&e.indexes&&e.indexes.length>0){if(e.radiusList.length!==e.indexes.length)throw new Error("Radius list and indexes are not the same length");t=!0}let r=this.edgesService.fixEdgeOrientationsAlongWire({shape:e.shape});if(t&&e.shape.Closed_1()){const t=this.edgesService.getEdgesAlongWire({shape:e.shape}),i=t.shift(),n=[...t,i];r=this.converterService.combineEdgesAndWiresIntoAWire({shapes:n})}else r=this.converterService.getActualTypeOfShape(e.shape.Reversed());const i=this.operationsService.extrude({shape:r,direction:e.direction});let n=e.indexes;if(t){const t=e.indexes.filter((e=>e>2)),r=Math.max(...t),i=[5];let s=5;for(let e=0;ee.shape.Closed_1()?t<=2?t:i[t-3]:1===t?2:i[t-2]))}const s=this.filletEdges({shape:i,radius:e.radius,indexes:n,radiusList:e.radiusList}),o=[],a=this.shapeGettersService.getFaces({shape:s});a.forEach(((e,t)=>{const r=this.shapeGettersService.getEdges({shape:e})[3];o.push(r)}));const c=this.converterService.combineEdgesAndWiresIntoAWire({shapes:o}),h=this.transformsService.translate({shape:c,translation:e.direction.map((e=>-e))});return i.delete(),s.delete(),a.forEach((e=>e.delete())),o.forEach((e=>e.delete())),h}}class ye{constructor(e,t,r,i,n,s,o){this.occ=e,this.shapeGettersService=t,this.facesService=r,this.enumService=i,this.entitiesService=n,this.converterService=s,this.transformsService=o}fromClosedShell(e){const t=this.converterService.getActualTypeOfShape(e.shape),r=new this.occ.BRepBuilderAPI_MakeSolid_3(t),i=r.Solid();return r.delete(),t.delete(),i}createBox(e){return this.entitiesService.bRepPrimAPIMakeBox(e.width,e.length,e.height,e.center)}createCube(e){return this.entitiesService.bRepPrimAPIMakeBox(e.size,e.size,e.size,e.center)}createBoxFromCorner(e){const t=this.entitiesService.bRepPrimAPIMakeBox(e.width,e.length,e.height,e.corner),r=this.transformsService.translate({shape:t,translation:[e.width/2,e.height/2,e.length/2]});return t.delete(),r}createCylinder(e){return this.entitiesService.bRepPrimAPIMakeCylinder(e.center,e.direction?e.direction:[0,1,0],e.radius,e.height)}createCylindersOnLines(e){return e.lines.map((t=>this.entitiesService.bRepPrimAPIMakeCylinderBetweenPoints(t.start,t.end,e.radius)))}createSphere(e){return this.entitiesService.bRepPrimAPIMakeSphere(e.center,[0,0,1],e.radius)}createCone(e){const t=this.entitiesService.gpAx2(e.center,e.direction),r=new this.occ.BRepPrimAPI_MakeCone_4(t,e.radius1,e.radius2,e.height,e.angle),i=r.Shape();return r.delete(),t.delete(),i}filterSolidPoints(e){const t=[];if(e.points.length>0){const r=new this.occ.BRepClass3d_SolidClassifier_1;return r.Load(e.shape),e.points.forEach((i=>{const n=this.entitiesService.gpPnt(i);r.Perform(n,e.tolerance);const s=r.State(),o=this.enumService.getTopAbsStateEnum(s);e.keepOn&&o===U.topAbsStateEnum.on&&t.push(i),e.keepIn&&o===U.topAbsStateEnum.in&&t.push(i),e.keepOut&&o===U.topAbsStateEnum.out&&t.push(i),e.keepUnknown&&o===U.topAbsStateEnum.unknown&&t.push(i),n.delete()})),r.delete(),t}return[]}getSolidVolume(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.VolumeProperties_1(e.shape,t,!0,!1,!1);const r=t.Mass();return t.delete(),r}getSolidSurfaceArea(e){const t=this.shapeGettersService.getFaces(e);return this.facesService.getFacesAreas({shapes:t}).reduce(((e,t)=>e+t),0)}getSolidsVolumes(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getSolidVolume({shape:e})))}getSolidCenterOfMass(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.VolumeProperties_1(e.shape,t,!0,!1,!1);const r=t.CentreOfMass(),i=[r.X(),r.Y(),r.Z()];return t.delete(),r.delete(),i}getSolidsCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getSolidCenterOfMass({shape:e})))}getSolids(e){return this.shapeGettersService.getSolids(e)}}class Se{constructor(e,t,r){this.vecHelper=e,this.shapesHelperService=t,this.occ=r,this.occRefReturns=new re(r),this.iteratorService=new ie(r),this.enumService=new ne(r),this.converterService=new se(r),this.entitiesService=new oe(r),this.shapeGettersService=new le(r,this.enumService,this.iteratorService),this.geomService=new de(r,this.vecHelper,this.entitiesService),this.booleansService=new he(r,this.shapeGettersService),this.transformsService=new ce(r,this.converterService,this.entitiesService,this.vecHelper),this.verticesService=new ge(r,this.shapeGettersService),this.edgesService=new ue(r,this.occRefReturns,this.shapeGettersService,this.entitiesService,this.iteratorService,this.converterService,this.enumService,this.geomService,this.transformsService,this.vecHelper),this.wiresService=new pe(r,this.occRefReturns,this.vecHelper,this.shapesHelperService,this.shapeGettersService,this.transformsService,this.enumService,this.entitiesService,this.converterService,this.geomService,this.edgesService,this.booleansService),this.facesService=new fe(r,this.occRefReturns,this.entitiesService,this.enumService,this.shapeGettersService,this.converterService,this.booleansService,this.wiresService),this.shellsService=new ve(r,this.shapeGettersService,this.converterService,this.facesService),this.solidsService=new ye(r,this.shapeGettersService,this.facesService,this.enumService,this.entitiesService,this.converterService,this.transformsService),this.operationsService=new ae(r,this.enumService,this.entitiesService,this.converterService,this.booleansService,this.shapeGettersService,this.edgesService,this.transformsService,this.vecHelper,this.wiresService,this.facesService,this.shellsService),this.filletsService=new me(r,this.vecHelper,this.iteratorService,this.converterService,this.entitiesService,this.transformsService,this.shapeGettersService,this.edgesService,this.operationsService)}surfaceFromFace(e){const t=e.shape;return this.occ.BRep_Tool.Surface_2(t).get()}}class be{constructor(e,t){this.occ=e,this.och=t}union(e){return this.och.booleansService.union(e)}difference(e){return this.och.booleansService.difference(e)}intersection(e){const t=this.och.booleansService.intersection(e);return this.och.converterService.makeCompound({shapes:t})}}class we{constructor(e,t){this.occ=e,this.och=t}saveShapeSTEP(e){const t=e.shape;let r;if(e.adjustYtoZ){const t=this.och.transformsService.rotate({shape:e.shape,axis:[1,0,0],angle:-90});r=this.och.transformsService.mirrorAlongNormal({shape:t,origin:[0,0,0],normal:[0,0,1]}),t.delete()}const i=new this.occ.STEPControl_Writer_1;let n;n=r||t;const s=new this.occ.Message_ProgressRange_1;let o,a;try{o=i.Transfer(n,this.occ.STEPControl_StepModelType.STEPControl_AsIs,!0,s)}catch(e){throw new Error("Failed when calling writer.Transfer.")}if(o!==this.occ.IFSelect_ReturnStatus.IFSelect_RetDone)throw new Error("Failed when transfering to step writer.");if(i.Write("x")!==this.occ.IFSelect_ReturnStatus.IFSelect_RetDone)throw new Error("Failed when writing step file.");{const e=this.occ.FS.readFile("/x",{encoding:"utf8"});this.occ.FS.unlink("/x"),a=e}return r&&r.delete(),s.delete(),a}loadSTEPorIGES(e){const t=e.fileName,r=e.filetext,i=(()=>{switch(t.toLowerCase().split(".").pop()){case"step":case"stp":return"step";case"iges":case"igs":return"iges";default:return}})();let n;if(this.occ.FS.createDataFile("/",`file.${i}`,r,!0,!0,!0),"step"===i)n=new this.occ.STEPControl_Reader_1;else{if("iges"!==i)return void console.error("opencascade can't parse this extension! (yet)");n=new this.occ.IGESControl_Reader_1}if(n.ReadFile(`file.${i}`)===this.occ.IFSelect_ReturnStatus.IFSelect_RetDone){const t=new this.occ.Message_ProgressRange_1;n.TransferRoots(t),t.delete();let r,s=n.OneShape();if(e.adjustZtoY){const e=this.och.transformsService.mirrorAlongNormal({shape:s,origin:[0,0,0],normal:[0,0,1]});r=this.och.transformsService.rotate({shape:e,axis:[1,0,0],angle:90}),e.delete()}return this.occ.FS.unlink(`/file.${i}`),r&&(s.delete(),s=r),s}console.error("Something in OCCT went wrong trying to read "+t)}}class Ee{constructor(e,t){this.occ=e,this.och=t}closestPointsBetweenTwoShapes(e){return this.och.operationsService.closestPointsBetweenTwoShapes(e.shape1,e.shape2)}closestPointsOnShapeFromPoints(e){return this.och.operationsService.closestPointsOnShapeFromPoints(e)}closestPointsOnShapesFromPoints(e){return this.och.operationsService.closestPointsOnShapesFromPoints(e)}distancesToShapeFromPoints(e){return this.och.operationsService.distancesToShapeFromPoints(e)}loft(e){return this.och.operationsService.loft(e)}loftAdvanced(e){return this.och.operationsService.loftAdvanced(e)}offset(e){return this.och.operationsService.offset(e)}offsetAdv(e){return this.och.operationsService.offsetAdv(e)}offset3DWire(e){return this.och.operationsService.offset3DWire(e)}extrudeShapes(e){return this.och.operationsService.extrudeShapes(e)}extrude(e){return this.och.operationsService.extrude(e)}splitShapeWithShapes(e){return this.och.operationsService.splitShapeWithShapes(e)}revolve(e){return this.och.operationsService.revolve(e)}rotatedExtrude(e){return this.och.operationsService.rotatedExtrude(e)}pipe(e){return this.och.operationsService.pipe(e)}pipePolylineWireNGon(e){return this.och.operationsService.pipePolylineWireNGon(e)}pipeWireCylindrical(e){return this.och.operationsService.pipeWireCylindrical(e)}pipeWiresCylindrical(e){return this.och.operationsService.pipeWiresCylindrical(e)}makeThickSolidSimple(e){return this.och.operationsService.makeThickSolidSimple(e)}makeThickSolidByJoin(e){return this.och.operationsService.makeThickSolidByJoin(e)}slice(e){return this.och.operationsService.slice(e)}sliceInStepPattern(e){return this.och.operationsService.sliceInStepPattern(e)}}class Te{constructor(e,t){this.occ=e,this.och=t}transform(e){const t=this.scale({shape:e.shape,factor:e.scaleFactor}),r=this.rotate({shape:t,axis:e.rotationAxis,angle:e.rotationAngle}),i=this.translate({shape:r,translation:e.translation});return t.delete(),r.delete(),i}rotate(e){return this.och.transformsService.rotate(e)}rotateAroundCenter(e){const t=this.translate({shape:e.shape,translation:e.center.map((e=>-e))}),r=e.angle,i=this.rotate({shape:t,axis:e.axis,angle:r}),n=this.translate({shape:i,translation:e.center});return i.delete(),t.delete(),n}align(e){return this.och.transformsService.align(e)}alignAndTranslate(e){return this.och.transformsService.alignAndTranslate(e)}translate(e){return this.och.transformsService.translate(e)}scale(e){const t=new this.occ.gp_Trsf_1,r=this.och.entitiesService.gpPnt([0,0,0]);t.SetScale(r,e.factor);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.och.converterService.getActualTypeOfShape(n);return r.delete(),t.delete(),i.delete(),n.delete(),s}scale3d(e){const t=this.translate({shape:e.shape,translation:e.center.map((e=>-e))}),r=new this.occ.gp_GTrsf_1,i=e.scale,n=new this.occ.gp_Mat_2(i[0],0,0,0,i[1],0,0,0,i[2]);let s;r.SetVectorialPart(n);try{const i=new this.occ.BRepBuilderAPI_GTransform_2(t,r,!1),n=new this.occ.Message_ProgressRange_1;i.Build(n);const o=i.Shape();s=this.translate({shape:o,translation:e.center}),i.delete(),o.delete(),n.delete()}catch(e){throw new Error("Could not scale the shape")}return t.delete(),r.delete(),n.delete(),s}mirror(e){return this.och.transformsService.mirror(e)}mirrorAlongNormal(e){return this.och.transformsService.mirrorAlongNormal(e)}transformShapes(e){return this.checkIfListsEqualLength([e.shapes,e.translations,e.rotationAxes,e.rotationAngles,e.scaleFactors]),e.shapes.map(((t,r)=>this.transform({shape:t,translation:e.translations[r],rotationAxis:e.rotationAxes[r],rotationAngle:e.rotationAngles[r],scaleFactor:e.scaleFactors[r]})))}rotateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.axes,e.angles]),e.shapes.map(((t,r)=>this.rotate({shape:t,axis:e.axes[r],angle:e.angles[r]})))}rotateAroundCenterShapes(e){return this.checkIfListsEqualLength([e.shapes,e.axes,e.angles]),e.shapes.map(((t,r)=>this.rotateAroundCenter({shape:t,axis:e.axes[r],angle:e.angles[r],center:e.centers[r]})))}alignShapes(e){return this.checkIfListsEqualLength([e.shapes,e.fromOrigins,e.fromDirections,e.toOrigins,e.toDirections]),e.shapes.map(((t,r)=>this.align({shape:t,fromOrigin:e.fromOrigins[r],fromDirection:e.fromDirections[r],toOrigin:e.toOrigins[r],toDirection:e.toDirections[r]})))}alignAndTranslateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.centers,e.directions]),e.shapes.map(((t,r)=>this.alignAndTranslate({shape:t,center:e.centers[r],direction:e.directions[r]})))}translateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.translations]),e.shapes.map(((t,r)=>this.translate({shape:t,translation:e.translations[r]})))}scaleShapes(e){return this.checkIfListsEqualLength([e.shapes,e.factors]),e.shapes.map(((t,r)=>this.scale({shape:t,factor:e.factors[r]})))}scale3dShapes(e){return this.checkIfListsEqualLength([e.shapes,e.scales,e.centers]),e.shapes.map(((t,r)=>this.scale3d({shape:t,scale:e.scales[r],center:e.centers[r]})))}mirrorShapes(e){return this.checkIfListsEqualLength([e.shapes,e.directions,e.origins]),e.shapes.map(((t,r)=>this.mirror({shape:t,origin:e.origins[r],direction:e.directions[r]})))}mirrorAlongNormalShapes(e){return this.checkIfListsEqualLength([e.shapes,e.normals,e.origins]),e.shapes.map(((t,r)=>this.mirrorAlongNormal({shape:t,normal:e.normals[r],origin:e.origins[r]})))}checkIfListsEqualLength(e){const t=e[0].length;if(e.some((e=>e.length!==t)))throw new Error("Some of the list lengths are not the same. For this operation to work all lists need to be of equal length")}}class xe{constructor(e,t){this.occ=e,this.och=t}filletEdges(e){return this.och.filletsService.filletEdges(e)}filletEdgesList(e){return this.och.filletsService.filletEdgesList(e)}filletEdgesListOneRadius(e){return this.och.filletsService.filletEdgesListOneRadius(e)}filletEdgeVariableRadius(e){return this.och.filletsService.filletEdgeVariableRadius(e)}filletEdgesVariableRadius(e){return this.och.filletsService.filletEdgesVariableRadius(e)}filletEdgesSameVariableRadius(e){return this.och.filletsService.filletEdgesSameVariableRadius(e)}chamferEdges(e){return this.och.filletsService.chamferEdges(e)}chamferEdgesList(e){return this.och.filletsService.chamferEdgesList(e)}chamferEdgeDistAngle(e){return this.och.filletsService.chamferEdgeDistAngle(e)}chamferEdgesDistAngle(e){return this.och.filletsService.chamferEdgesDistAngle(e)}chamferEdgesDistsAngles(e){return this.och.filletsService.chamferEdgesDistsAngles(e)}chamferEdgeTwoDistances(e){return this.och.filletsService.chamferEdgeTwoDistances(e)}chamferEdgesTwoDistances(e){return this.och.filletsService.chamferEdgesTwoDistances(e)}chamferEdgesTwoDistancesLists(e){return this.och.filletsService.chamferEdgesTwoDistancesLists(e)}filletTwoEdgesInPlaneIntoAWire(e){const t=this.och.entitiesService.gpPln(e.planeOrigin,e.planeDirection),r=new this.occ.ChFi2d_FilletAlgo_3(e.edge1,e.edge2,t);r.Perform(e.radius);const i=this.och.entitiesService.gpPnt(e.planeOrigin),n=new this.occ.TopoDS_Edge,s=new this.occ.TopoDS_Edge;let o=-1;void 0!==e.solution&&(o=e.solution);const a=r.Result(i,n,s,o),c=this.och.converterService.combineEdgesAndWiresIntoAWire({shapes:[n,a,s]});return r.delete(),i.delete(),t.delete(),n.delete(),s.delete(),a.delete(),c}fillet3DWire(e){return this.och.filletsService.fillet3DWire(e)}fillet2d(e){if(e.indexes&&e.radiusList&&e.radiusList.length!==e.indexes.length)throw new Error("When using radius list, length of the list must match index list of corners that you want to fillet.");let t,r=!1;if(e.shape.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE)t=this.och.converterService.getActualTypeOfShape(e.shape),r=!0;else{if(e.shape.ShapeType()!==this.occ.TopAbs_ShapeEnum.TopAbs_WIRE)throw new Error("You can only fillet a 2d wire or a 2d face.");{const r=new this.occ.BRepBuilderAPI_MakeFace_15(e.shape,!0),i=new this.occ.Message_ProgressRange_1;r.Build(i);const n=r.Shape();t=this.och.converterService.getActualTypeOfShape(n),n.delete(),i.delete(),r.delete()}}const i=new this.occ.BRepFilletAPI_MakeFillet2d_2(t),n=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);let s=1;const o=[];for(;n.More();n.Next()){const e=this.occ.TopoDS.Vertex_1(n.Current());s%2==0&&o.push(e),s++}r||e.shape.Closed_1()||o.pop();let a=0;o.forEach(((t,r)=>{e.indexes?e.indexes.includes(r+1)&&(this.applyRadiusToVertex(e,i,t,a),a++):this.applyRadiusToVertex(e,i,t,r)}));const c=new this.occ.Message_ProgressRange_1;let h;if(i.Build(c),r)h=i.Shape();else if(i.IsDone()){const e=i.Shape(),t=this.och.shapeGettersService.getWires({shape:e});1===t.length&&(h=t[0])}else{const r=this.och.facesService.faceNormalOnUV({shape:t,paramU:.5,paramV:.5});h=this.fillet3DWire({shape:e.shape,radius:e.radius,radiusList:e.radiusList,indexes:e.indexes,direction:r})}return n.delete(),i.delete(),c.delete(),o.forEach((e=>e.delete())),h}applyRadiusToVertex(e,t,r,i){if(e.radiusList){const n=e.radiusList;t.AddFillet(r,n[i])}else e.radius&&t.AddFillet(r,e.radius)}}class ke{constructor(e,t){this.occ=e,this.och=t}fixEdgeOrientationsAlongWire(e){return this.och.edgesService.fixEdgeOrientationsAlongWire(e)}basicShapeRepair(e){const t=new this.occ.ShapeFix_Shape_1;t.Init(e.shape),t.SetPrecision(e.precision),t.SetMaxTolerance(e.maxTolerance),t.SetMinTolerance(e.minTolerance);const r=new this.occ.Message_ProgressRange_1;t.Perform(r),r.delete();const i=t.Shape();return t.delete(),i}fixSmallEdgeOnWire(e){const t=new this.occ.ShapeFix_Wire_1;return t.Load_1(e.shape),t.FixSmall_1(e.lockvtx,e.precsmall),t.Perform(),t.Wire()}}class Ce{constructor(e,t){this.occ=e,this.och=t,this.shapes=new te(e,t),this.geom=new q(e,t),this.transforms=new Te(e,t),this.operations=new Ee(e,t),this.booleans=new be(e,t),this.fillets=new xe(e,t),this.shapeFix=new ke(e,t),this.io=new we(e,t)}shapesToMeshes(e){return e.shapes.map((t=>this.shapeToMesh({shape:t,precision:e.precision,adjustYtoZ:e.adjustYtoZ})))}shapeToMesh(e){const t=[],r=[],i=[];let n=e.shape;if(n.IsNull())return{faceList:t,edgeList:r,pointsList:[]};if(this.occ.BRepTools.Clean(n,!0),e.adjustYtoZ){const t=this.och.transformsService.rotate({shape:e.shape,axis:[1,0,0],angle:-90}),r=this.och.transformsService.mirrorAlongNormal({shape:t,origin:[0,0,0],normal:[0,0,1]});t.delete(),n.delete(),n=r}const s=[],o=this.och.shapeGettersService.getFaces({shape:n});let a;o&&o.length&&(a=new this.occ.BRepMesh_IncrementalMesh_2(n,e.precision,!1,.5,!1),o.forEach(((e,r)=>{const i=new this.occ.TopLoc_Location_1,n=this.occ.BRep_Tool.Triangulation(e,i,0);if(n.IsNull())return void console.error("Encountered Null Face!");const o={vertex_coord:[],normal_coord:[],uvs:[],tri_indexes:[],vertex_coord_vec:[],number_of_triangles:0,face_index:r},a=new this.occ.Poly_Connect_2(n),c=n.get();o.vertex_coord=new Array(3*c.NbNodes()),o.vertex_coord_vec=[];for(let e=0;e{const n={vertex_coord:[],edge_index:-1},s=new this.occ.TopLoc_Location_1,o=new this.occ.BRepAdaptor_Curve_2(t),a=new this.occ.GCPnts_TangentialDeflection_2(o,e.precision,.1,2,1e-9,1e-7);n.vertex_coord=[];const c=a.NbPoints(),h=[];for(let e=0;ee.delete())),s.delete(),o.delete(),a.delete(),this.occ.BRepTools.Clean(t,!0)}));const c=this.och.shapeGettersService.getVertices({shape:n});return c.length>0&&c.forEach((e=>{const t=this.occ.BRep_Tool.Pnt(e);i.push([t.X(),t.Y(),t.Z()]),t.delete()})),a&&a.Delete(),this.occ.BRepTools.Clean(n,!0),{faceList:t,edgeList:r,pointsList:i}}}var Pe,Ae=(Pe=(Pe="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,i;(e=void 0!==(e=e||{})?e:{}).ready=new Promise((function(e,r){t=e,i=r}));var n,s,o,a,c,h,l=Object.assign({},e),u=[],d="./this.program",p=(e,t)=>{throw t},f="object"==typeof window,g="function"==typeof importScripts,v="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";v?(m=g?r(699).dirname(m)+"/":"//",h=()=>{c||(a=r(439),c=r(699))},n=function(e,t){return h(),e=c.normalize(e),a.readFileSync(e,t?void 0:"utf8")},o=e=>{var t=n(e,!0);return t.buffer||(t=new Uint8Array(t)),t},s=(e,t,r)=>{h(),e=c.normalize(e),a.readFile(e,(function(e,i){e?r(e):t(i.buffer)}))},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof yr))throw e})),process.on("unhandledRejection",(function(e){throw e})),p=(e,t)=>{if(te())throw process.exitCode=e,t;var r;(r=t)instanceof yr||S("exiting due to exception: "+r),process.exit(e)},e.inspect=function(){return"[Emscripten Module object]"}):(f||g)&&(g?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),Pe&&(m=Pe),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",n=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),s=(e,t,r)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)});var y=e.print||console.log.bind(console),S=e.printErr||console.warn.bind(console);Object.assign(e,l),l=null,e.arguments&&(u=e.arguments),e.thisProgram&&(d=e.thisProgram),e.quit&&(p=e.quit);var b;function w(e){w.shown||(w.shown={}),w.shown[e]||(w.shown[e]=1,S(e))}e.wasmBinary&&(b=e.wasmBinary);var E,T=e.noExitRuntime||!0;"object"!=typeof WebAssembly&&ae("no native wasm support detected");var x,k=!1;function C(e,t){e||ae(t)}var P="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function A(e,t,r){for(var i=(t>>>=0)+r,n=t;e[n]&&!(n>=i);)++n;if(n-t>16&&e.buffer&&P)return P.decode(e.subarray(t,n));for(var s="";t>10,56320|1023&h)}}else s+=String.fromCharCode((31&o)<<6|a)}else s+=String.fromCharCode(o)}return s}function _(e,t){return(e>>>=0)?A(B,e,t):""}function O(e,t,r,i){if(!(i>0))return 0;for(var n=r>>>=0,s=r+i-1,o=0;o=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++o)),a<=127){if(r>=s)break;t[r++>>>0]=a}else if(a<=2047){if(r+1>=s)break;t[r++>>>0]=192|a>>6,t[r++>>>0]=128|63&a}else if(a<=65535){if(r+2>=s)break;t[r++>>>0]=224|a>>12,t[r++>>>0]=128|a>>6&63,t[r++>>>0]=128|63&a}else{if(r+3>=s)break;t[r++>>>0]=240|a>>18,t[r++>>>0]=128|a>>12&63,t[r++>>>0]=128|a>>6&63,t[r++>>>0]=128|63&a}}return t[r>>>0]=0,r-n}function D(e,t,r){return O(e,B,t,r)}function R(e){for(var t=0,r=0;r=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++r)),i<=127?++t:t+=i<=2047?2:i<=65535?3:4}return t}var F,L,B,M,I,U,W,N,G,H="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0;function V(e,t){for(var r=e,i=r>>1,n=i+t/2;!(i>=n)&&I[i>>>0];)++i;if((r=i<<1)-e>32&&H)return H.decode(B.subarray(e>>>0,r>>>0));for(var s="",o=0;!(o>=t/2);++o){var a=M[e+2*o>>>1];if(0==a)break;s+=String.fromCharCode(a)}return s}function z(e,t,r){if(void 0===r&&(r=2147483647),r<2)return 0;for(var i=t,n=(r-=2)<2*e.length?r/2:e.length,s=0;s>>1]=o,t+=2}return M[t>>>1]=0,t-i}function j(e){return 2*e.length}function q(e,t){for(var r=0,i="";!(r>=t/4);){var n=U[e+4*r>>>2];if(0==n)break;if(++r,n>=65536){var s=n-65536;i+=String.fromCharCode(55296|s>>10,56320|1023&s)}else i+=String.fromCharCode(n)}return i}function $(e,t,r){if(void 0===r&&(r=2147483647),r<4)return 0;for(var i=t>>>=0,n=i+r-4,s=0;s=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),U[t>>>2]=o,(t+=4)+4>n)break}return U[t>>>2]=0,t-i}function Y(e){for(var t=0,r=0;r=55296&&i<=57343&&++r,t+=4}return t}function X(e){var t=R(e)+1,r=ur(t);return r&&O(e,L,r,t),r}function Z(t){F=t,e.HEAP8=L=new Int8Array(t),e.HEAP16=M=new Int16Array(t),e.HEAP32=U=new Int32Array(t),e.HEAPU8=B=new Uint8Array(t),e.HEAPU16=I=new Uint16Array(t),e.HEAPU32=W=new Uint32Array(t),e.HEAPF32=N=new Float32Array(t),e.HEAPF64=G=new Float64Array(t)}e.INITIAL_MEMORY;var J,Q=[],K=[],ee=[];function te(){return T}var re=0,ie=null,ne=null;function se(t){re++,e.monitorRunDependencies&&e.monitorRunDependencies(re)}function oe(t){if(re--,e.monitorRunDependencies&&e.monitorRunDependencies(re),0==re&&(null!==ie&&(clearInterval(ie),ie=null),ne)){var r=ne;ne=null,r()}}function ae(t){e.onAbort&&e.onAbort(t),S(t="Aborted("+t+")"),k=!0,x=1,t+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(t);throw i(r),r}var ce,he,le,ue;function de(e){return e.startsWith("data:application/octet-stream;base64,")}function pe(e){return e.startsWith("file://")}function fe(e){try{if(e==ce&&b)return new Uint8Array(b);if(o)return o(e);throw"both async and sync fetching of the wasm failed"}catch(e){ae(e)}}function ge(t){for(;t.length>0;){var r=t.shift();if("function"!=typeof r){var i=r.func;"number"==typeof i?void 0===r.arg?me(i)():me(i)(r.arg):i(void 0===r.arg?null:r.arg)}else r(e)}}de(ce="bitbybit-dev-occt.wasm")||(he=ce,ce=e.locateFile?e.locateFile(he,m):m+he);var ve=[];function me(e){var t=ve[e];return t||(e>=ve.length&&(ve.length=e+1),ve[e]=t=J.get(e)),t}function ye(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){W[this.ptr+4>>>2]=e},this.get_type=function(){return W[this.ptr+4>>>2]},this.set_destructor=function(e){W[this.ptr+8>>>2]=e},this.get_destructor=function(){return W[this.ptr+8>>>2]},this.set_refcount=function(e){U[this.ptr>>>2]=e},this.set_caught=function(e){e=e?1:0,L[this.ptr+12>>>0]=e},this.get_caught=function(){return 0!=L[this.ptr+12>>>0]},this.set_rethrown=function(e){e=e?1:0,L[this.ptr+13>>>0]=e},this.get_rethrown=function(){return 0!=L[this.ptr+13>>>0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var e=U[this.ptr>>>2];U[this.ptr>>>2]=e+1},this.release_ref=function(){var e=U[this.ptr>>>2];return U[this.ptr>>>2]=e-1,1===e},this.set_adjusted_ptr=function(e){W[this.ptr+16>>>2]=e},this.get_adjusted_ptr=function(){return W[this.ptr+16>>>2]},this.get_exception_ptr=function(){if(mr(this.get_type()))return W[this.excPtr>>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var Se={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,i=e.length-1;i>=0;i--){var n=e[i];"."===n?e.splice(i,1):".."===n?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=Se.isAbs(e),r="/"===e.substr(-1);return(e=Se.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=Se.splitPath(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=Se.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments,0);return Se.normalize(e.join("/"))},join2:(e,t)=>Se.normalize(e+"/"+t)},be={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:xe.cwd();if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";e=i+"/"+e,t=Se.isAbs(i)}return(t?"/":"")+(e=Se.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=be.resolve(e).substr(1),t=be.resolve(t).substr(1);for(var i=r(e.split("/")),n=r(t.split("/")),s=Math.min(i.length,n.length),o=s,a=0;a0?r.slice(0,i).toString("utf-8"):null}else"undefined"!=typeof window&&"function"==typeof window.prompt?null!==(t=window.prompt("Input: "))&&(t+="\n"):"function"==typeof readline&&null!==(t=readline())&&(t+="\n");if(!t)return null;e.input=cr(t,!0)}return e.input.shift()},put_char:function(e,t){null===t||10===t?(y(A(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(y(A(e.output,0)),e.output=[])}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(S(A(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(S(A(e.output,0)),e.output=[])}}};function Ee(e){e=function(e,t){return 65536*Math.ceil(e/65536)}(e);var t=vr(65536,e);return t?(function(e,t){B.fill(0,e,e+t)}(t,e),t):0}var Te={ops_table:null,mount:function(e){return Te.createNode(null,"/",16895,0)},createNode:function(e,t,r,i){if(xe.isBlkdev(r)||xe.isFIFO(r))throw new xe.ErrnoError(63);Te.ops_table||(Te.ops_table={dir:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,lookup:Te.node_ops.lookup,mknod:Te.node_ops.mknod,rename:Te.node_ops.rename,unlink:Te.node_ops.unlink,rmdir:Te.node_ops.rmdir,readdir:Te.node_ops.readdir,symlink:Te.node_ops.symlink},stream:{llseek:Te.stream_ops.llseek}},file:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:{llseek:Te.stream_ops.llseek,read:Te.stream_ops.read,write:Te.stream_ops.write,allocate:Te.stream_ops.allocate,mmap:Te.stream_ops.mmap,msync:Te.stream_ops.msync}},link:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,readlink:Te.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:xe.chrdev_stream_ops}});var n=xe.createNode(e,t,r,i);return xe.isDir(n.mode)?(n.node_ops=Te.ops_table.dir.node,n.stream_ops=Te.ops_table.dir.stream,n.contents={}):xe.isFile(n.mode)?(n.node_ops=Te.ops_table.file.node,n.stream_ops=Te.ops_table.file.stream,n.usedBytes=0,n.contents=null):xe.isLink(n.mode)?(n.node_ops=Te.ops_table.link.node,n.stream_ops=Te.ops_table.link.stream):xe.isChrdev(n.mode)&&(n.node_ops=Te.ops_table.chrdev.node,n.stream_ops=Te.ops_table.chrdev.stream),n.timestamp=Date.now(),e&&(e.contents[t]=n,e.timestamp=n.timestamp),n},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,t){t>>>=0;var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var i=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,t){if(t>>>=0,e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr:function(e){var t={};return t.dev=xe.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,xe.isDir(e.mode)?t.size=4096:xe.isFile(e.mode)?t.size=e.usedBytes:xe.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&Te.resizeFileStorage(e,t.size)},lookup:function(e,t){throw xe.genericErrors[44]},mknod:function(e,t,r,i){return Te.createNode(e,t,r,i)},rename:function(e,t,r){if(xe.isDir(e.mode)){var i;try{i=xe.lookupNode(t,r)}catch(e){}if(i)for(var n in i.contents)throw new xe.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink:function(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir:function(e,t){var r=xe.lookupNode(e,t);for(var i in r.contents)throw new xe.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir:function(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink:function(e,t,r){var i=Te.createNode(e,t,41471,0);return i.link=r,i},readlink:function(e){if(!xe.isLink(e.mode))throw new xe.ErrnoError(28);return e.link}},stream_ops:{read:function(e,t,r,i,n){var s=e.node.contents;if(n>=e.node.usedBytes)return 0;var o=Math.min(e.node.usedBytes-n,i);if(o>8&&s.subarray)t.set(s.subarray(n,n+o),r);else for(var a=0;a0||r+t>>=0,L.set(a,s>>>0)}else o=!1,s=a.byteOffset;return{ptr:s,allocated:o}},msync:function(e,t,r,i,n){if(!xe.isFile(e.node.mode))throw new xe.ErrnoError(43);return 2&n||Te.stream_ops.write(e,t,0,i,r,!1),0}}},xe={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(e,t={})=>{if(!(e=be.resolve(xe.cwd(),e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new xe.ErrnoError(32);for(var r=Se.normalizeArray(e.split("/").filter((e=>!!e)),!1),i=xe.root,n="/",s=0;s40)throw new xe.ErrnoError(32)}}return{path:n,node:i}},getPath:e=>{for(var t;;){if(xe.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?r+"/"+t:r+t:r}t=t?e.name+"/"+t:e.name,e=e.parent}},hashName:(e,t)=>{for(var r=0,i=0;i>>0)%xe.nameTable.length},hashAddNode:e=>{var t=xe.hashName(e.parent.id,e.name);e.name_next=xe.nameTable[t],xe.nameTable[t]=e},hashRemoveNode:e=>{var t=xe.hashName(e.parent.id,e.name);if(xe.nameTable[t]===e)xe.nameTable[t]=e.name_next;else for(var r=xe.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode:(e,t)=>{var r=xe.mayLookup(e);if(r)throw new xe.ErrnoError(r,e);for(var i=xe.hashName(e.id,t),n=xe.nameTable[i];n;n=n.name_next){var s=n.name;if(n.parent.id===e.id&&s===t)return n}return xe.lookup(e,t)},createNode:(e,t,r,i)=>{var n=new xe.FSNode(e,t,r,i);return xe.hashAddNode(n),n},destroyNode:e=>{xe.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagModes:{r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},modeStringToFlags:e=>{var t=xe.flagModes[e];if(void 0===t)throw new Error("Unknown file open mode: "+e);return t},flagsToPermissionString:e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>xe.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>xe.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return xe.lookupNode(e,t),20}catch(e){}return xe.nodePermissions(e,"wx")},mayDelete:(e,t,r)=>{var i;try{i=xe.lookupNode(e,t)}catch(e){return e.errno}var n=xe.nodePermissions(e,"wx");if(n)return n;if(r){if(!xe.isDir(i.mode))return 54;if(xe.isRoot(i)||xe.getPath(i)===xe.cwd())return 10}else if(xe.isDir(i.mode))return 31;return 0},mayOpen:(e,t)=>e?xe.isLink(e.mode)?32:xe.isDir(e.mode)&&("r"!==xe.flagsToPermissionString(t)||512&t)?31:xe.nodePermissions(e,xe.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:(e=0,t=xe.MAX_OPEN_FDS)=>{for(var r=e;r<=t;r++)if(!xe.streams[r])return r;throw new xe.ErrnoError(33)},getStream:e=>xe.streams[e],createStream:(e,t,r)=>{xe.FSStream||(xe.FSStream=function(){this.shared={}},xe.FSStream.prototype={},Object.defineProperties(xe.FSStream.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return!!(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}},flags:{get:function(){return this.shared.flags},set:function(e){this.shared.flags=e}},position:{get:function(){return this.shared.position},set:function(e){this.shared.position=e}}})),e=Object.assign(new xe.FSStream,e);var i=xe.nextfd(t,r);return e.fd=i,xe.streams[i]=e,e},closeStream:e=>{xe.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=xe.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new xe.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{xe.devices[e]={stream_ops:t}},getDevice:e=>xe.devices[e],getMounts:e=>{for(var t=[],r=[e];r.length;){var i=r.pop();t.push(i),r.push.apply(r,i.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),xe.syncFSRequests++,xe.syncFSRequests>1&&S("warning: "+xe.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var r=xe.getMounts(xe.root.mount),i=0;function n(e){return xe.syncFSRequests--,t(e)}function s(e){if(e)return s.errored?void 0:(s.errored=!0,n(e));++i>=r.length&&n(null)}r.forEach((t=>{if(!t.type.syncfs)return s(null);t.type.syncfs(t,e,s)}))},mount:(e,t,r)=>{var i,n="/"===r,s=!r;if(n&&xe.root)throw new xe.ErrnoError(10);if(!n&&!s){var o=xe.lookupPath(r,{follow_mount:!1});if(r=o.path,i=o.node,xe.isMountpoint(i))throw new xe.ErrnoError(10);if(!xe.isDir(i.mode))throw new xe.ErrnoError(54)}var a={type:e,opts:t,mountpoint:r,mounts:[]},c=e.mount(a);return c.mount=a,a.root=c,n?xe.root=c:i&&(i.mounted=a,i.mount&&i.mount.mounts.push(a)),c},unmount:e=>{var t=xe.lookupPath(e,{follow_mount:!1});if(!xe.isMountpoint(t.node))throw new xe.ErrnoError(28);var r=t.node,i=r.mounted,n=xe.getMounts(i);Object.keys(xe.nameTable).forEach((e=>{for(var t=xe.nameTable[e];t;){var r=t.name_next;n.includes(t.mount)&&xe.destroyNode(t),t=r}})),r.mounted=null;var s=r.mount.mounts.indexOf(i);r.mount.mounts.splice(s,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,r)=>{var i=xe.lookupPath(e,{parent:!0}).node,n=Se.basename(e);if(!n||"."===n||".."===n)throw new xe.ErrnoError(28);var s=xe.mayCreate(i,n);if(s)throw new xe.ErrnoError(s);if(!i.node_ops.mknod)throw new xe.ErrnoError(63);return i.node_ops.mknod(i,n,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,xe.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,xe.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var r=e.split("/"),i="",n=0;n(void 0===r&&(r=t,t=438),t|=8192,xe.mknod(e,t,r)),symlink:(e,t)=>{if(!be.resolve(e))throw new xe.ErrnoError(44);var r=xe.lookupPath(t,{parent:!0}).node;if(!r)throw new xe.ErrnoError(44);var i=Se.basename(t),n=xe.mayCreate(r,i);if(n)throw new xe.ErrnoError(n);if(!r.node_ops.symlink)throw new xe.ErrnoError(63);return r.node_ops.symlink(r,i,e)},rename:(e,t)=>{var r,i,n=Se.dirname(e),s=Se.dirname(t),o=Se.basename(e),a=Se.basename(t);if(r=xe.lookupPath(e,{parent:!0}).node,i=xe.lookupPath(t,{parent:!0}).node,!r||!i)throw new xe.ErrnoError(44);if(r.mount!==i.mount)throw new xe.ErrnoError(75);var c,h=xe.lookupNode(r,o),l=be.relative(e,s);if("."!==l.charAt(0))throw new xe.ErrnoError(28);if("."!==(l=be.relative(t,n)).charAt(0))throw new xe.ErrnoError(55);try{c=xe.lookupNode(i,a)}catch(e){}if(h!==c){var u=xe.isDir(h.mode),d=xe.mayDelete(r,o,u);if(d)throw new xe.ErrnoError(d);if(d=c?xe.mayDelete(i,a,u):xe.mayCreate(i,a))throw new xe.ErrnoError(d);if(!r.node_ops.rename)throw new xe.ErrnoError(63);if(xe.isMountpoint(h)||c&&xe.isMountpoint(c))throw new xe.ErrnoError(10);if(i!==r&&(d=xe.nodePermissions(r,"w")))throw new xe.ErrnoError(d);xe.hashRemoveNode(h);try{r.node_ops.rename(h,i,a)}catch(e){throw e}finally{xe.hashAddNode(h)}}},rmdir:e=>{var t=xe.lookupPath(e,{parent:!0}).node,r=Se.basename(e),i=xe.lookupNode(t,r),n=xe.mayDelete(t,r,!0);if(n)throw new xe.ErrnoError(n);if(!t.node_ops.rmdir)throw new xe.ErrnoError(63);if(xe.isMountpoint(i))throw new xe.ErrnoError(10);t.node_ops.rmdir(t,r),xe.destroyNode(i)},readdir:e=>{var t=xe.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new xe.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=xe.lookupPath(e,{parent:!0}).node;if(!t)throw new xe.ErrnoError(44);var r=Se.basename(e),i=xe.lookupNode(t,r),n=xe.mayDelete(t,r,!1);if(n)throw new xe.ErrnoError(n);if(!t.node_ops.unlink)throw new xe.ErrnoError(63);if(xe.isMountpoint(i))throw new xe.ErrnoError(10);t.node_ops.unlink(t,r),xe.destroyNode(i)},readlink:e=>{var t=xe.lookupPath(e).node;if(!t)throw new xe.ErrnoError(44);if(!t.node_ops.readlink)throw new xe.ErrnoError(28);return be.resolve(xe.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var r=xe.lookupPath(e,{follow:!t}).node;if(!r)throw new xe.ErrnoError(44);if(!r.node_ops.getattr)throw new xe.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>xe.stat(e,!0),chmod:(e,t,r)=>{var i;if(!(i="string"==typeof e?xe.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);i.node_ops.setattr(i,{mode:4095&t|-4096&i.mode,timestamp:Date.now()})},lchmod:(e,t)=>{xe.chmod(e,t,!0)},fchmod:(e,t)=>{var r=xe.getStream(e);if(!r)throw new xe.ErrnoError(8);xe.chmod(r.node,t)},chown:(e,t,r,i)=>{var n;if(!(n="string"==typeof e?xe.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);n.node_ops.setattr(n,{timestamp:Date.now()})},lchown:(e,t,r)=>{xe.chown(e,t,r,!0)},fchown:(e,t,r)=>{var i=xe.getStream(e);if(!i)throw new xe.ErrnoError(8);xe.chown(i.node,t,r)},truncate:(e,t)=>{if(t<0)throw new xe.ErrnoError(28);var r;if(!(r="string"==typeof e?xe.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);if(xe.isDir(r.mode))throw new xe.ErrnoError(31);if(!xe.isFile(r.mode))throw new xe.ErrnoError(28);var i=xe.nodePermissions(r,"w");if(i)throw new xe.ErrnoError(i);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var r=xe.getStream(e);if(!r)throw new xe.ErrnoError(8);if(!(2097155&r.flags))throw new xe.ErrnoError(28);xe.truncate(r.node,t)},utime:(e,t,r)=>{var i=xe.lookupPath(e,{follow:!0}).node;i.node_ops.setattr(i,{timestamp:Math.max(t,r)})},open:(t,r,i)=>{if(""===t)throw new xe.ErrnoError(44);var n;if(i=void 0===i?438:i,i=64&(r="string"==typeof r?xe.modeStringToFlags(r):r)?4095&i|32768:0,"object"==typeof t)n=t;else{t=Se.normalize(t);try{n=xe.lookupPath(t,{follow:!(131072&r)}).node}catch(e){}}var s=!1;if(64&r)if(n){if(128&r)throw new xe.ErrnoError(20)}else n=xe.mknod(t,i,0),s=!0;if(!n)throw new xe.ErrnoError(44);if(xe.isChrdev(n.mode)&&(r&=-513),65536&r&&!xe.isDir(n.mode))throw new xe.ErrnoError(54);if(!s){var o=xe.mayOpen(n,r);if(o)throw new xe.ErrnoError(o)}512&r&&!s&&xe.truncate(n,0),r&=-131713;var a=xe.createStream({node:n,path:xe.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return a.stream_ops.open&&a.stream_ops.open(a),!e.logReadFiles||1&r||(xe.readFiles||(xe.readFiles={}),t in xe.readFiles||(xe.readFiles[t]=1)),a},close:e=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{xe.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,r)=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new xe.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new xe.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read:(e,t,r,i,n)=>{if(r>>>=0,i<0||n<0)throw new xe.ErrnoError(28);if(xe.isClosed(e))throw new xe.ErrnoError(8);if(1==(2097155&e.flags))throw new xe.ErrnoError(8);if(xe.isDir(e.node.mode))throw new xe.ErrnoError(31);if(!e.stream_ops.read)throw new xe.ErrnoError(28);var s=void 0!==n;if(s){if(!e.seekable)throw new xe.ErrnoError(70)}else n=e.position;var o=e.stream_ops.read(e,t,r,i,n);return s||(e.position+=o),o},write:(e,t,r,i,n,s)=>{if(r>>>=0,i<0||n<0)throw new xe.ErrnoError(28);if(xe.isClosed(e))throw new xe.ErrnoError(8);if(!(2097155&e.flags))throw new xe.ErrnoError(8);if(xe.isDir(e.node.mode))throw new xe.ErrnoError(31);if(!e.stream_ops.write)throw new xe.ErrnoError(28);e.seekable&&1024&e.flags&&xe.llseek(e,0,2);var o=void 0!==n;if(o){if(!e.seekable)throw new xe.ErrnoError(70)}else n=e.position;var a=e.stream_ops.write(e,t,r,i,n,s);return o||(e.position+=a),a},allocate:(e,t,r)=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);if(t<0||r<=0)throw new xe.ErrnoError(28);if(!(2097155&e.flags))throw new xe.ErrnoError(8);if(!xe.isFile(e.node.mode)&&!xe.isDir(e.node.mode))throw new xe.ErrnoError(43);if(!e.stream_ops.allocate)throw new xe.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap:(e,t,r,i,n)=>{if(2&i&&!(2&n)&&2!=(2097155&e.flags))throw new xe.ErrnoError(2);if(1==(2097155&e.flags))throw new xe.ErrnoError(2);if(!e.stream_ops.mmap)throw new xe.ErrnoError(43);return e.stream_ops.mmap(e,t,r,i,n)},msync:(e,t,r,i,n)=>(r>>>=0,e&&e.stream_ops.msync?e.stream_ops.msync(e,t,r,i,n):0),munmap:e=>0,ioctl:(e,t,r)=>{if(!e.stream_ops.ioctl)throw new xe.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile:(e,t={})=>{if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'+t.encoding+'"');var r,i=xe.open(e,t.flags),n=xe.stat(e).size,s=new Uint8Array(n);return xe.read(i,s,0,n,0),"utf8"===t.encoding?r=A(s,0):"binary"===t.encoding&&(r=s),xe.close(i),r},writeFile:(e,t,r={})=>{r.flags=r.flags||577;var i=xe.open(e,r.flags,r.mode);if("string"==typeof t){var n=new Uint8Array(R(t)+1),s=O(t,n,0,n.length);xe.write(i,n,0,s,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");xe.write(i,t,0,t.byteLength,void 0,r.canOwn)}xe.close(i)},cwd:()=>xe.currentPath,chdir:e=>{var t=xe.lookupPath(e,{follow:!0});if(null===t.node)throw new xe.ErrnoError(44);if(!xe.isDir(t.node.mode))throw new xe.ErrnoError(54);var r=xe.nodePermissions(t.node,"x");if(r)throw new xe.ErrnoError(r);xe.currentPath=t.path},createDefaultDirectories:()=>{xe.mkdir("/tmp"),xe.mkdir("/home"),xe.mkdir("/home/web_user")},createDefaultDevices:()=>{xe.mkdir("/dev"),xe.registerDevice(xe.makedev(1,3),{read:()=>0,write:(e,t,r,i,n)=>i}),xe.mkdev("/dev/null",xe.makedev(1,3)),we.register(xe.makedev(5,0),we.default_tty_ops),we.register(xe.makedev(6,0),we.default_tty1_ops),xe.mkdev("/dev/tty",xe.makedev(5,0)),xe.mkdev("/dev/tty1",xe.makedev(6,0));var e=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return function(){return crypto.getRandomValues(e),e[0]}}if(v)try{var t=r(725);return function(){return t.randomBytes(1)[0]}}catch(e){}return function(){ae("randomDevice")}}();xe.createDevice("/dev","random",e),xe.createDevice("/dev","urandom",e),xe.mkdir("/dev/shm"),xe.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{xe.mkdir("/proc");var e=xe.mkdir("/proc/self");xe.mkdir("/proc/self/fd"),xe.mount({mount:()=>{var t=xe.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var r=+t,i=xe.getStream(r);if(!i)throw new xe.ErrnoError(8);var n={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>i.path}};return n.parent=n,n}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{e.stdin?xe.createDevice("/dev","stdin",e.stdin):xe.symlink("/dev/tty","/dev/stdin"),e.stdout?xe.createDevice("/dev","stdout",null,e.stdout):xe.symlink("/dev/tty","/dev/stdout"),e.stderr?xe.createDevice("/dev","stderr",null,e.stderr):xe.symlink("/dev/tty1","/dev/stderr"),xe.open("/dev/stdin",0),xe.open("/dev/stdout",1),xe.open("/dev/stderr",1)},ensureErrnoError:()=>{xe.ErrnoError||(xe.ErrnoError=function(e,t){this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},xe.ErrnoError.prototype=new Error,xe.ErrnoError.prototype.constructor=xe.ErrnoError,[44].forEach((e=>{xe.genericErrors[e]=new xe.ErrnoError(e),xe.genericErrors[e].stack=""})))},staticInit:()=>{xe.ensureErrnoError(),xe.nameTable=new Array(4096),xe.mount(Te,{},"/"),xe.createDefaultDirectories(),xe.createDefaultDevices(),xe.createSpecialDirectories(),xe.filesystems={MEMFS:Te}},init:(t,r,i)=>{xe.init.initialized=!0,xe.ensureErrnoError(),e.stdin=t||e.stdin,e.stdout=r||e.stdout,e.stderr=i||e.stderr,xe.createStandardStreams()},quit:()=>{xe.init.initialized=!1;for(var e=0;e{var r=0;return e&&(r|=365),t&&(r|=146),r},findObject:(e,t)=>{var r=xe.analyzePath(e,t);return r.exists?r.object:null},analyzePath:(e,t)=>{try{e=(i=xe.lookupPath(e,{follow:!t})).path}catch(e){}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var i=xe.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=i.path,r.parentObject=i.node,r.name=Se.basename(e),i=xe.lookupPath(e,{follow:!t}),r.exists=!0,r.path=i.path,r.object=i.node,r.name=i.node.name,r.isRoot="/"===i.path}catch(e){r.error=e.errno}return r},createPath:(e,t,r,i)=>{e="string"==typeof e?e:xe.getPath(e);for(var n=t.split("/").reverse();n.length;){var s=n.pop();if(s){var o=Se.join2(e,s);try{xe.mkdir(o)}catch(e){}e=o}}return o},createFile:(e,t,r,i,n)=>{var s=Se.join2("string"==typeof e?e:xe.getPath(e),t),o=xe.getMode(i,n);return xe.create(s,o)},createDataFile:(e,t,r,i,n,s)=>{var o=t;e&&(e="string"==typeof e?e:xe.getPath(e),o=t?Se.join2(e,t):e);var a=xe.getMode(i,n),c=xe.create(o,a);if(r){if("string"==typeof r){for(var h=new Array(r.length),l=0,u=r.length;l{var n=Se.join2("string"==typeof e?e:xe.getPath(e),t),s=xe.getMode(!!r,!!i);xe.createDevice.major||(xe.createDevice.major=64);var o=xe.makedev(xe.createDevice.major++,0);return xe.registerDevice(o,{open:e=>{e.seekable=!1},close:e=>{i&&i.buffer&&i.buffer.length&&i(10)},read:(e,t,i,n,s)=>{for(var o=0,a=0;a{for(var o=0;o{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!n)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=cr(n(e.url),!0),e.usedBytes=e.contents.length}catch(e){throw new xe.ErrnoError(29)}},createLazyFile:(e,t,r,i,n)=>{function s(){this.lengthKnown=!1,this.chunks=[]}if(s.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},s.prototype.setDataGetter=function(e){this.getter=e},s.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,i=Number(e.getResponseHeader("Content-length")),n=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,s=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,o=1048576;n||(o=i);var a=this;a.setDataGetter((e=>{var t=e*o,n=(e+1)*o-1;if(n=Math.min(n,i-1),void 0===a.chunks[e]&&(a.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>i-1)throw new Error("only "+i+" bytes available! programmer error!");var n=new XMLHttpRequest;if(n.open("GET",r,!1),i!==o&&n.setRequestHeader("Range","bytes="+e+"-"+t),n.responseType="arraybuffer",n.overrideMimeType&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.send(null),!(n.status>=200&&n.status<300||304===n.status))throw new Error("Couldn't load "+r+". Status: "+n.status);return void 0!==n.response?new Uint8Array(n.response||[]):cr(n.responseText||"",!0)})(t,n)),void 0===a.chunks[e])throw new Error("doXHR failed!");return a.chunks[e]})),!s&&i||(o=i=1,i=this.getter(0).length,o=i,y("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=i,this._chunkSize=o,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!g)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var o=new s;Object.defineProperties(o,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var a={isDevice:!1,contents:o}}else a={isDevice:!1,url:r};var c=xe.createFile(e,t,a,i,n);a.contents?c.contents=a.contents:a.url&&(c.contents=null,c.url=a.url),Object.defineProperties(c,{usedBytes:{get:function(){return this.contents.length}}});var h={};function l(e,t,r,i,n){var s=e.node.contents;if(n>=s.length)return 0;var o=Math.min(s.length-n,i);if(s.slice)for(var a=0;a{var t=c.stream_ops[e];h[e]=function(){return xe.forceLoadFile(c),t.apply(null,arguments)}})),h.read=(e,t,r,i,n)=>(xe.forceLoadFile(c),l(e,t,r,i,n)),h.mmap=(e,t,r,i,n)=>{xe.forceLoadFile(c);var s=Ee(t);if(!s)throw new xe.ErrnoError(48);return l(e,L,s,t,r),{ptr:s,allocated:!0}},c.stream_ops=h,c},createPreloadedFile:(e,t,r,i,n,o,a,c,h,l)=>{var u=t?be.resolve(Se.join2(e,t)):e;function d(r){function s(r){l&&l(),c||xe.createDataFile(e,t,r,i,n,h),o&&o(),oe()}Nt.handledByPreloadPlugin(r,u,s,(()=>{a&&a(),oe()}))||s(r)}se(),"string"==typeof r?function(e,t,r,i){var n="al "+e;s(e,(function(t){C(t,'Loading data file "'+e+'" failed (no arrayBuffer).'),d(new Uint8Array(t)),n&&oe()}),(function(t){if(!r)throw'Loading data file "'+e+'" failed.';r()})),n&&se()}(r,0,a):d(r)},indexedDB:()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,DB_NAME:()=>"EM_FS_"+window.location.pathname,DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(e,t,r)=>{t=t||(()=>{}),r=r||(()=>{});var i=xe.indexedDB();try{var n=i.open(xe.DB_NAME(),xe.DB_VERSION)}catch(e){return r(e)}n.onupgradeneeded=()=>{y("creating db"),n.result.createObjectStore(xe.DB_STORE_NAME)},n.onsuccess=()=>{var i=n.result.transaction([xe.DB_STORE_NAME],"readwrite"),s=i.objectStore(xe.DB_STORE_NAME),o=0,a=0,c=e.length;function h(){0==a?t():r()}e.forEach((e=>{var t=s.put(xe.analyzePath(e).object.contents,e);t.onsuccess=()=>{++o+a==c&&h()},t.onerror=()=>{a++,o+a==c&&h()}})),i.onerror=r},n.onerror=r},loadFilesFromDB:(e,t,r)=>{t=t||(()=>{}),r=r||(()=>{});var i=xe.indexedDB();try{var n=i.open(xe.DB_NAME(),xe.DB_VERSION)}catch(e){return r(e)}n.onupgradeneeded=r,n.onsuccess=()=>{var i=n.result;try{var s=i.transaction([xe.DB_STORE_NAME],"readonly")}catch(e){return void r(e)}var o=s.objectStore(xe.DB_STORE_NAME),a=0,c=0,h=e.length;function l(){0==c?t():r()}e.forEach((e=>{var t=o.get(e);t.onsuccess=()=>{xe.analyzePath(e).exists&&xe.unlink(e),xe.createDataFile(Se.dirname(e),Se.basename(e),t.result,!0,!0,!0),++a+c==h&&l()},t.onerror=()=>{c++,a+c==h&&l()}})),s.onerror=r},n.onerror=r}},ke={DEFAULT_POLLMASK:5,calculateAt:function(e,t,r){if(Se.isAbs(t))return t;var i;if(-100===e)i=xe.cwd();else{var n=xe.getStream(e);if(!n)throw new xe.ErrnoError(8);i=n.path}if(0==t.length){if(!r)throw new xe.ErrnoError(44);return i}return Se.join2(i,t)},doStat:function(e,t,r){try{var i=e(t)}catch(e){if(e&&e.node&&Se.normalize(t)!==Se.normalize(xe.getPath(e.node)))return-54;throw e}return U[r>>>2]=i.dev,U[r+4>>>2]=0,U[r+8>>>2]=i.ino,U[r+12>>>2]=i.mode,U[r+16>>>2]=i.nlink,U[r+20>>>2]=i.uid,U[r+24>>>2]=i.gid,U[r+28>>>2]=i.rdev,U[r+32>>>2]=0,ue=[i.size>>>0,(le=i.size,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[r+40>>>2]=ue[0],U[r+44>>>2]=ue[1],U[r+48>>>2]=4096,U[r+52>>>2]=i.blocks,U[r+56>>>2]=i.atime.getTime()/1e3|0,U[r+60>>>2]=0,U[r+64>>>2]=i.mtime.getTime()/1e3|0,U[r+68>>>2]=0,U[r+72>>>2]=i.ctime.getTime()/1e3|0,U[r+76>>>2]=0,ue=[i.ino>>>0,(le=i.ino,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[r+80>>>2]=ue[0],U[r+84>>>2]=ue[1],0},doMsync:function(e,t,r,i,n){var s=B.slice(e,e+r);xe.msync(t,s,n,r,i)},varargs:void 0,get:function(){return ke.varargs+=4,U[ke.varargs-4>>>2]},getStr:function(e){return _(e)},getStreamFromFD:function(e){var t=xe.getStream(e);if(!t)throw new xe.ErrnoError(8);return t}},Ce="To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking";function Ae(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+e)}}var _e=void 0;function Oe(e){for(var t="",r=e;B[r>>>0];)t+=_e[B[r++>>>0]];return t}var De={},Re={},Fe={},Le=48,Be=57;function Me(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=Le&&t<=Be?"_"+e:e}function Ie(e,t){return e=Me(e),new Function("body","return function "+e+'() {\n "use strict"; return body.apply(this, arguments);\n};\n')(t)}function Ue(e,t){var r=Ie(t,(function(e){this.name=t,this.message=e;var r=new Error(e).stack;void 0!==r&&(this.stack=this.toString()+"\n"+r.replace(/^Error(:[^\n]*)?\n/,""))}));return r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message},r}var We=void 0;function Ne(e){throw new We(e)}var Ge=void 0;function He(e){throw new Ge(e)}function Ve(e,t,r){function i(t){var i=r(t);i.length!==e.length&&He("Mismatched type converter count");for(var n=0;n{Re.hasOwnProperty(e)?n[t]=Re[e]:(s.push(e),De.hasOwnProperty(e)||(De[e]=[]),De[e].push((()=>{n[t]=Re[e],++o===s.length&&i(n)})))})),0===s.length&&i(n)}function ze(e,t,r={}){if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");var i=t.name;if(e||Ne('type "'+i+'" must have a positive integer typeid pointer'),Re.hasOwnProperty(e)){if(r.ignoreDuplicateRegistrations)return;Ne("Cannot register type '"+i+"' twice")}if(Re[e]=t,delete Fe[e],De.hasOwnProperty(e)){var n=De[e];delete De[e],n.forEach((e=>e()))}}function je(e){Ne(e.$$.ptrType.registeredClass.name+" instance already deleted")}var qe=!1;function $e(e){}function Ye(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}function Xe(e,t,r){if(t===r)return e;if(void 0===r.baseClass)return null;var i=Xe(e,t,r.baseClass);return null===i?null:r.downcast(i)}var Ze={};var Je=[];function Qe(){for(;Je.length;){var e=Je.pop();e.$$.deleteScheduled=!1,e.delete()}}var Ke=void 0;var et={};function tt(e,t){return t.ptrType&&t.ptr||He("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!=!!t.smartPtr&&He("Both smartPtrType and smartPtr must be specified"),t.count={value:1},rt(Object.create(e,{$$:{value:t}}))}function rt(e){return"undefined"==typeof FinalizationRegistry?(rt=e=>e,e):(qe=new FinalizationRegistry((e=>{Ye(e.$$)})),rt=e=>{var t=e.$$;if(t.smartPtr){var r={$$:t};qe.register(e,r,e)}return e},$e=e=>qe.unregister(e),rt(e))}function it(){}function nt(e,t,r){if(void 0===e[t].overloadTable){var i=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||Ne("Function '"+r+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+e[t].overloadTable+")!"),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[i.argCount]=i}}function st(t,r,i){e.hasOwnProperty(t)?((void 0===i||void 0!==e[t].overloadTable&&void 0!==e[t].overloadTable[i])&&Ne("Cannot register public name '"+t+"' twice"),nt(e,t,t),e.hasOwnProperty(i)&&Ne("Cannot register multiple overloads of a function with the same number of arguments ("+i+")!"),e[t].overloadTable[i]=r):(e[t]=r,void 0!==i&&(e[t].numArguments=i))}function ot(e,t,r,i,n,s,o,a){this.name=e,this.constructor=t,this.instancePrototype=r,this.rawDestructor=i,this.baseClass=n,this.getActualType=s,this.upcast=o,this.downcast=a,this.pureVirtualFunctions=[]}function at(e,t,r){for(;t!==r;)t.upcast||Ne("Expected null or instance of "+r.name+", got an instance of "+t.name),e=t.upcast(e),t=t.baseClass;return e}function ct(e,t){if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name);var r=t.$$.ptrType.registeredClass;return at(t.$$.ptr,r,this.registeredClass)}function ht(e,t){var r;if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),this.isSmartPointer?(r=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,r),r):0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&t.$$.ptrType.isConst&&Ne("Cannot convert argument of type "+(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name)+" to parameter type "+this.name);var i=t.$$.ptrType.registeredClass;if(r=at(t.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&Ne("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?r=t.$$.smartPtr:Ne("Cannot convert argument of type "+(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:r=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)r=t.$$.smartPtr;else{var n=t.clone();r=this.rawShare(r,kt.toHandle((function(){n.delete()}))),null!==e&&e.push(this.rawDestructor,r)}break;default:Ne("Unsupporting sharing policy")}return r}function lt(e,t){if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name),t.$$.ptrType.isConst&&Ne("Cannot convert argument of type "+t.$$.ptrType.name+" to parameter type "+this.name);var r=t.$$.ptrType.registeredClass;return at(t.$$.ptr,r,this.registeredClass)}function ut(e){return this.fromWireType(W[e>>>2])}function dt(e,t,r,i,n,s,o,a,c,h,l){this.name=e,this.registeredClass=t,this.isReference=r,this.isConst=i,this.isSmartPointer=n,this.pointeeType=s,this.sharingPolicy=o,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=h,this.rawDestructor=l,n||void 0!==t.baseClass?this.toWireType=ht:i?(this.toWireType=ct,this.destructorFunction=null):(this.toWireType=lt,this.destructorFunction=null)}function pt(t,r){var i,n,s,o=(t=Oe(t)).includes("j")?(i=t,n=r,s=[],function(){return s.length=0,Object.assign(s,arguments),function(t,r,i){return t.includes("j")?function(t,r,i){var n=e["dynCall_"+t];return i&&i.length?n.apply(null,[r].concat(i)):n.call(null,r)}(t,r,i):me(r).apply(null,i)}(i,n,s)}):me(r);return"function"!=typeof o&&Ne("unknown function pointer with signature "+t+": "+r),o}var ft=void 0;function gt(e){var t=fr(e),r=Oe(t);return dr(t),r}function vt(e,t){var r=[],i={};throw t.forEach((function e(t){i[t]||Re[t]||(Fe[t]?Fe[t].forEach(e):(r.push(t),i[t]=!0))})),new ft(e+": "+r.map(gt).join([", "]))}function mt(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type "+typeof e+" which is not a function");var r=Ie(e.name||"unknownFunctionName",(function(){}));r.prototype=e.prototype;var i=new r,n=e.apply(i,t);return n instanceof Object?n:i}function yt(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function St(e,t,r,i,n){var s=t.length;s<2&&Ne("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var o=null!==t[1]&&null!==r,a=!1,c=1;c0?", ":"")+u),d+=(h?"var rv = ":"")+"invoker(fn"+(u.length>0?", ":"")+u+");\n",a)d+="runDestructors(destructors);\n";else for(c=o?1:2;c>2)+i>>>0]);return r}function wt(e,t,r){return e instanceof Object||Ne(r+' with invalid "this": '+e),e instanceof t.registeredClass.constructor||Ne(r+' incompatible with "this" of type '+e.constructor.name),e.$$.ptr||Ne("cannot call emscripten binding method "+r+" on deleted object"),at(e.$$.ptr,e.$$.ptrType.registeredClass,t.registeredClass)}var Et=[],Tt=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function xt(e){e>4&&0==--Tt[e].refcount&&(Tt[e]=void 0,Et.push(e))}var kt={toValue:e=>(e||Ne("Cannot use deleted val. handle = "+e),Tt[e].value),toHandle:e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var t=Et.length?Et.pop():Tt.length;return Tt[t]={refcount:1,value:e},t}}};function Ct(e,t,r){switch(t){case 0:return function(e){var t=r?L:B;return this.fromWireType(t[e>>>0])};case 1:return function(e){var t=r?M:I;return this.fromWireType(t[e>>>1])};case 2:return function(e){var t=r?U:W;return this.fromWireType(t[e>>>2])};default:throw new TypeError("Unknown integer type: "+e)}}function Pt(e,t){var r=Re[e];return void 0===r&&Ne(t+" has unknown type "+gt(e)),r}function At(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function _t(e,t){switch(t){case 2:return function(e){return this.fromWireType(N[e>>>2])};case 3:return function(e){return this.fromWireType(G[e>>>3])};default:throw new TypeError("Unknown float type: "+e)}}function Ot(e,t,r){switch(t){case 0:return r?function(e){return L[e>>>0]}:function(e){return B[e>>>0]};case 1:return r?function(e){return M[e>>>1]}:function(e){return I[e>>>1]};case 2:return r?function(e){return U[e>>>2]}:function(e){return W[e>>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var Dt={};function Rt(e){var t=Dt[e];return void 0===t?Oe(e):t}var Ft=[];function Lt(){return"object"==typeof globalThis?globalThis:Function("return this")()}var Bt,Mt=[];function It(t,r){if(Nt.mainLoop.timingMode=t,Nt.mainLoop.timingValue=r,!Nt.mainLoop.func)return 1;if(Nt.mainLoop.running||(Nt.mainLoop.running=!0),0==t)Nt.mainLoop.scheduler=function(){var e=0|Math.max(0,Nt.mainLoop.tickStartTime+r-Bt());setTimeout(Nt.mainLoop.runner,e)},Nt.mainLoop.method="timeout";else if(1==t)Nt.mainLoop.scheduler=function(){Nt.requestAnimationFrame(Nt.mainLoop.runner)},Nt.mainLoop.method="rAF";else if(2==t){if("undefined"==typeof setImmediate){var i=[],n="setimmediate";addEventListener("message",(function(e){e.data!==n&&e.data.target!==n||(e.stopPropagation(),i.shift()())}),!0),setImmediate=function(t){i.push(t),g?(void 0===e.setImmediates&&(e.setImmediates=[]),e.setImmediates.push(t),postMessage({target:n})):postMessage(n,"*")}}Nt.mainLoop.scheduler=function(){setImmediate(Nt.mainLoop.runner)},Nt.mainLoop.method="immediate"}return 0}function Ut(e,t){if(!k)if(t)e();else try{e()}catch(e){!function(e){if(e instanceof yr||"unwind"==e)return x;p(1,e)}(e)}}function Wt(e,t){return setTimeout((function(){Ut(e)}),t)}Bt=v?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now();var Nt={mainLoop:{running:!1,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){Nt.mainLoop.scheduler=null,Nt.mainLoop.currentlyRunningMainloop++},resume:function(){Nt.mainLoop.currentlyRunningMainloop++;var e=Nt.mainLoop.timingMode,t=Nt.mainLoop.timingValue,r=Nt.mainLoop.func;Nt.mainLoop.func=null,function(e,t,r,i,n){C(!Nt.mainLoop.func,"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters."),Nt.mainLoop.func=e,Nt.mainLoop.arg=i;var s=Nt.mainLoop.currentlyRunningMainloop;function o(){return!(s0){var t=Date.now(),r=Nt.mainLoop.queue.shift();if(r.func(r.arg),Nt.mainLoop.remainingBlockers){var i=Nt.mainLoop.remainingBlockers,n=i%1==0?i-1:Math.floor(i);r.counted?Nt.mainLoop.remainingBlockers=n:(n+=.5,Nt.mainLoop.remainingBlockers=(8*i+n)/9)}if(y('main loop blocker "'+r.name+'" took '+(Date.now()-t)+" ms"),Nt.mainLoop.updateStatus(),!o())return;setTimeout(Nt.mainLoop.runner,0)}else o()&&(Nt.mainLoop.currentFrameNumber=Nt.mainLoop.currentFrameNumber+1|0,1==Nt.mainLoop.timingMode&&Nt.mainLoop.timingValue>1&&Nt.mainLoop.currentFrameNumber%Nt.mainLoop.timingValue!=0?Nt.mainLoop.scheduler():(0==Nt.mainLoop.timingMode&&(Nt.mainLoop.tickStartTime=Bt()),Nt.mainLoop.runIter(e),o()&&("object"==typeof SDL&&SDL.audio&&SDL.audio.queueNewAudioData&&SDL.audio.queueNewAudioData(),Nt.mainLoop.scheduler())))}}(r,0,0,Nt.mainLoop.arg),It(e,t),Nt.mainLoop.scheduler()},updateStatus:function(){if(e.setStatus){var t=e.statusMessage||"Please wait...",r=Nt.mainLoop.remainingBlockers,i=Nt.mainLoop.expectedBlockers;r?r{C(a.complete,"Image "+t+" could not be decoded");var i=document.createElement("canvas");i.width=a.width,i.height=a.height,i.getContext("2d").drawImage(a,0,0),ir[t]=i,Nt.URLObject.revokeObjectURL(o),r&&r(e)},a.onerror=e=>{y("Image "+o+" could not be decoded"),i&&i()},a.src=o}};e.preloadPlugins.push(t);var r={canHandle:function(t){return!e.noAudioDecoding&&t.substr(-4)in{".ogg":1,".wav":1,".mp3":1}},handle:function(e,t,r,i){var n=!1;function s(i){n||(n=!0,nr[t]=i,r&&r(e))}function o(){n||(n=!0,nr[t]=new Audio,i&&i())}if(!Nt.hasBlobConstructor)return o();try{var a=new Blob([e],{type:Nt.getMimetype(t)})}catch(e){return o()}var c=Nt.URLObject.createObjectURL(a),h=new Audio;h.addEventListener("canplaythrough",(function(){s(h)}),!1),h.onerror=function(r){n||(y("warning: browser could not fully decode audio "+t+", trying slower base64 approach"),h.src="data:audio/x-"+t.substr(-3)+";base64,"+function(e){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="",i=0,n=0,s=0;s=6;){var o=i>>n-6&63;n-=6,r+=t[o]}return 2==n?(r+=t[(3&i)<<4],r+="=="):4==n&&(r+=t[(15&i)<<2],r+="="),r}(e),s(h))},h.src=c,Wt((function(){s(h)}),1e4)}};e.preloadPlugins.push(r);var i=e.canvas;i&&(i.requestPointerLock=i.requestPointerLock||i.mozRequestPointerLock||i.webkitRequestPointerLock||i.msRequestPointerLock||function(){},i.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},i.exitPointerLock=i.exitPointerLock.bind(document),document.addEventListener("pointerlockchange",n,!1),document.addEventListener("mozpointerlockchange",n,!1),document.addEventListener("webkitpointerlockchange",n,!1),document.addEventListener("mspointerlockchange",n,!1),e.elementPointerLock&&i.addEventListener("click",(function(t){!Nt.pointerLock&&e.canvas.requestPointerLock&&(e.canvas.requestPointerLock(),t.preventDefault())}),!1))}function n(){Nt.pointerLock=document.pointerLockElement===e.canvas||document.mozPointerLockElement===e.canvas||document.webkitPointerLockElement===e.canvas||document.msPointerLockElement===e.canvas}},handledByPreloadPlugin:function(t,r,i,n){Nt.init();var s=!1;return e.preloadPlugins.forEach((function(e){s||e.canHandle(r)&&(e.handle(t,r,i,n),s=!0)})),s},createContext:function(t,r,i,n){if(r&&e.ctx&&t==e.canvas)return e.ctx;var s,o;if(r){var a={antialias:!1,alpha:!1,majorVersion:1};if(n)for(var c in n)a[c]=n[c];void 0!==$t&&(o=$t.createContext(t,a))&&(s=$t.getContext(o).GLctx)}else s=t.getContext("2d");return s?(i&&(r||C(void 0===rr,"cannot set in module if GLctx is used, but we are a non-GL context that would replace it"),e.ctx=s,r&&$t.makeContextCurrent(o),e.useWebGL=r,Nt.moduleContextCreatedCallbacks.forEach((function(e){e()})),Nt.init()),s):null},destroyContext:function(e,t,r){},fullscreenHandlersInstalled:!1,lockPointer:void 0,resizeCanvas:void 0,requestFullscreen:function(t,r){Nt.lockPointer=t,Nt.resizeCanvas=r,void 0===Nt.lockPointer&&(Nt.lockPointer=!0),void 0===Nt.resizeCanvas&&(Nt.resizeCanvas=!1);var i=e.canvas;function n(){Nt.isFullscreen=!1;var t=i.parentNode;(document.fullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement)===t?(i.exitFullscreen=Nt.exitFullscreen,Nt.lockPointer&&i.requestPointerLock(),Nt.isFullscreen=!0,Nt.resizeCanvas?Nt.setFullscreenCanvasSize():Nt.updateCanvasDimensions(i)):(t.parentNode.insertBefore(i,t),t.parentNode.removeChild(t),Nt.resizeCanvas?Nt.setWindowedCanvasSize():Nt.updateCanvasDimensions(i)),e.onFullScreen&&e.onFullScreen(Nt.isFullscreen),e.onFullscreen&&e.onFullscreen(Nt.isFullscreen)}Nt.fullscreenHandlersInstalled||(Nt.fullscreenHandlersInstalled=!0,document.addEventListener("fullscreenchange",n,!1),document.addEventListener("mozfullscreenchange",n,!1),document.addEventListener("webkitfullscreenchange",n,!1),document.addEventListener("MSFullscreenChange",n,!1));var s=document.createElement("div");i.parentNode.insertBefore(s,i),s.appendChild(i),s.requestFullscreen=s.requestFullscreen||s.mozRequestFullScreen||s.msRequestFullscreen||(s.webkitRequestFullscreen?function(){s.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)}:null)||(s.webkitRequestFullScreen?function(){s.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),s.requestFullscreen()},exitFullscreen:function(){return!!Nt.isFullscreen&&((document.exitFullscreen||document.cancelFullScreen||document.mozCancelFullScreen||document.msExitFullscreen||document.webkitCancelFullScreen||function(){}).apply(document,[]),!0)},nextRAF:0,fakeRequestAnimationFrame:function(e){var t=Date.now();if(0===Nt.nextRAF)Nt.nextRAF=t+1e3/60;else for(;t+2>=Nt.nextRAF;)Nt.nextRAF+=1e3/60;var r=Math.max(Nt.nextRAF-t,0);setTimeout(e,r)},requestAnimationFrame:function(e){"function"!=typeof requestAnimationFrame?(0,Nt.fakeRequestAnimationFrame)(e):requestAnimationFrame(e)},safeSetTimeout:function(e){return Wt(e)},safeRequestAnimationFrame:function(e){return Nt.requestAnimationFrame((function(){Ut(e)}))},getMimetype:function(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[e.substr(e.lastIndexOf(".")+1)]},getUserMedia:function(e){window.getUserMedia||(window.getUserMedia=navigator.getUserMedia||navigator.mozGetUserMedia),window.getUserMedia(e)},getMovementX:function(e){return e.movementX||e.mozMovementX||e.webkitMovementX||0},getMovementY:function(e){return e.movementY||e.mozMovementY||e.webkitMovementY||0},getMouseWheelDelta:function(e){var t=0;switch(e.type){case"DOMMouseScroll":t=e.detail/3;break;case"mousewheel":t=e.wheelDelta/120;break;case"wheel":switch(t=e.deltaY,e.deltaMode){case 0:t/=100;break;case 1:t/=3;break;case 2:t*=80;break;default:throw"unrecognized mouse wheel delta mode: "+e.deltaMode}break;default:throw"unrecognized mouse wheel event: "+e.type}return t},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(t){if(Nt.pointerLock)"mousemove"!=t.type&&"mozMovementX"in t?Nt.mouseMovementX=Nt.mouseMovementY=0:(Nt.mouseMovementX=Nt.getMovementX(t),Nt.mouseMovementY=Nt.getMovementY(t)),"undefined"!=typeof SDL?(Nt.mouseX=SDL.mouseX+Nt.mouseMovementX,Nt.mouseY=SDL.mouseY+Nt.mouseMovementY):(Nt.mouseX+=Nt.mouseMovementX,Nt.mouseY+=Nt.mouseMovementY);else{var r=e.canvas.getBoundingClientRect(),i=e.canvas.width,n=e.canvas.height,s=void 0!==window.scrollX?window.scrollX:window.pageXOffset,o=void 0!==window.scrollY?window.scrollY:window.pageYOffset;if("touchstart"===t.type||"touchend"===t.type||"touchmove"===t.type){var a=t.touch;if(void 0===a)return;var c=a.pageX-(s+r.left),h=a.pageY-(o+r.top),l={x:c*=i/r.width,y:h*=n/r.height};if("touchstart"===t.type)Nt.lastTouches[a.identifier]=l,Nt.touches[a.identifier]=l;else if("touchend"===t.type||"touchmove"===t.type){var u=Nt.touches[a.identifier];u||(u=l),Nt.lastTouches[a.identifier]=u,Nt.touches[a.identifier]=l}return}var d=t.pageX-(s+r.left),p=t.pageY-(o+r.top);d*=i/r.width,p*=n/r.height,Nt.mouseMovementX=d-Nt.mouseX,Nt.mouseMovementY=p-Nt.mouseY,Nt.mouseX=d,Nt.mouseY=p}},resizeListeners:[],updateResizeListeners:function(){var t=e.canvas;Nt.resizeListeners.forEach((function(e){e(t.width,t.height)}))},setCanvasSize:function(t,r,i){var n=e.canvas;Nt.updateCanvasDimensions(n,t,r),i||Nt.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if("undefined"!=typeof SDL){var t=W[SDL.screen>>>2];t|=8388608,U[SDL.screen>>>2]=t}Nt.updateCanvasDimensions(e.canvas),Nt.updateResizeListeners()},setWindowedCanvasSize:function(){if("undefined"!=typeof SDL){var t=W[SDL.screen>>>2];t&=-8388609,U[SDL.screen>>>2]=t}Nt.updateCanvasDimensions(e.canvas),Nt.updateResizeListeners()},updateCanvasDimensions:function(t,r,i){r&&i?(t.widthNative=r,t.heightNative=i):(r=t.widthNative,i=t.heightNative);var n=r,s=i;if(e.forcedAspectRatio&&e.forcedAspectRatio>0&&(n/s>>16),Z(E.buffer),1}catch(e){}}var Ht={};function Vt(){if(!Vt.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"};for(var t in Ht)void 0===Ht[t]?delete e[t]:e[t]=Ht[t];var r=[];for(var t in e)r.push(t+"="+e[t]);Vt.strings=r}return Vt.strings}function zt(e){for(var t=e.split("."),r=0;r<4;r++){var i=Number(t[r]);if(isNaN(i))return null;t[r]=i}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0}function jt(e){return parseInt(e)}var qt={address_map:{id:1,addrs:{},names:{}},lookup_name:function(e){var t,r=zt(e);if(null!==r)return e;if(null!==(r=function(e){var t,r,i,n,s=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jt(t[t.length-4])+256*jt(t[t.length-3]),t[t.length-3]=jt(t[t.length-2])+256*jt(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),i=0,n=0,r=0;r>>2]:-1;n+=_(U[r+4*s>>>2],o<0?void 0:o)}return n},createContext:function(e,t){if(!e.getContextSafariWebGL2Fixed){function i(t,r){var i=e.getContextSafariWebGL2Fixed(t,r);return"webgl"==t==i instanceof WebGLRenderingContext?i:null}e.getContextSafariWebGL2Fixed=e.getContext,e.getContext=i}var r=e.getContext("webgl",t);return r?$t.registerContext(r,t):0},registerContext:function(e,t){var r=$t.getNewId($t.contexts),i={handle:r,attributes:t,version:t.majorVersion,GLctx:e};return e.canvas&&(e.canvas.GLctxObject=i),$t.contexts[r]=i,(void 0===t.enableExtensionsByDefault||t.enableExtensionsByDefault)&&$t.initExtensions(i),r},makeContextCurrent:function(t){return $t.currentContext=$t.contexts[t],e.ctx=rr=$t.currentContext&&$t.currentContext.GLctx,!(t&&!rr)},getContext:function(e){return $t.contexts[e]},deleteContext:function(e){$t.currentContext===$t.contexts[e]&&($t.currentContext=null),"object"==typeof JSEvents&&JSEvents.removeAllHandlersOnTarget($t.contexts[e].GLctx.canvas),$t.contexts[e]&&$t.contexts[e].GLctx.canvas&&($t.contexts[e].GLctx.canvas.GLctxObject=void 0),$t.contexts[e]=null},initExtensions:function(e){if(e||(e=$t.currentContext),!e.initExtensionsDone){e.initExtensionsDone=!0;var t,r=e.GLctx;!function(e){var t=e.getExtension("ANGLE_instanced_arrays");t&&(e.vertexAttribDivisor=function(e,r){t.vertexAttribDivisorANGLE(e,r)},e.drawArraysInstanced=function(e,r,i,n){t.drawArraysInstancedANGLE(e,r,i,n)},e.drawElementsInstanced=function(e,r,i,n,s){t.drawElementsInstancedANGLE(e,r,i,n,s)})}(r),function(e){var t=e.getExtension("OES_vertex_array_object");t&&(e.createVertexArray=function(){return t.createVertexArrayOES()},e.deleteVertexArray=function(e){t.deleteVertexArrayOES(e)},e.bindVertexArray=function(e){t.bindVertexArrayOES(e)},e.isVertexArray=function(e){return t.isVertexArrayOES(e)})}(r),function(e){var t=e.getExtension("WEBGL_draw_buffers");t&&(e.drawBuffers=function(e,r){t.drawBuffersWEBGL(e,r)})}(r),r.disjointTimerQueryExt=r.getExtension("EXT_disjoint_timer_query"),(t=r).multiDrawWebgl=t.getExtension("WEBGL_multi_draw"),(r.getSupportedExtensions()||[]).forEach((function(e){e.includes("lose_context")||e.includes("debug")||r.getExtension(e)}))}}};function Yt(e){return"]"==e.slice(-1)&&e.lastIndexOf("[")}function Xt(e){var t=rr.currentProgram;if(t){var r=t.uniformLocsById[e];return"number"==typeof r&&(t.uniformLocsById[e]=r=rr.getUniformLocation(t,t.uniformArrayNamesById[e]+(r>0?"["+r+"]":""))),r}$t.recordError(1282)}var Zt=[],Jt=[];function Qt(e){return e%4==0&&(e%100!=0||e%400==0)}var Kt=[31,29,31,30,31,30,31,31,30,31,30,31],er=[31,28,31,30,31,30,31,31,30,31,30,31];var tr=function(e,t,r,i){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=xe.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=i};Object.defineProperties(tr.prototype,{read:{get:function(){return!(365&~this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return!(146&~this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return xe.isDir(this.mode)}},isDevice:{get:function(){return xe.isChrdev(this.mode)}}}),xe.FSNode=tr,xe.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);_e=e}(),We=e.BindingError=Ue(Error,"BindingError"),Ge=e.InternalError=Ue(Error,"InternalError"),it.prototype.isAliasOf=function(e){if(!(this instanceof it))return!1;if(!(e instanceof it))return!1;for(var t=this.$$.ptrType.registeredClass,r=this.$$.ptr,i=e.$$.ptrType.registeredClass,n=e.$$.ptr;t.baseClass;)r=t.upcast(r),t=t.baseClass;for(;i.baseClass;)n=i.upcast(n),i=i.baseClass;return t===i&&r===n},it.prototype.clone=function(){if(this.$$.ptr||je(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e,t=rt(Object.create(Object.getPrototypeOf(this),{$$:{value:(e=this.$$,{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType})}}));return t.$$.count.value+=1,t.$$.deleteScheduled=!1,t},it.prototype.delete=function(){this.$$.ptr||je(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),$e(this),Ye(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},it.prototype.isDeleted=function(){return!this.$$.ptr},it.prototype.deleteLater=function(){return this.$$.ptr||je(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),Je.push(this),1===Je.length&&Ke&&Ke(Qe),this.$$.deleteScheduled=!0,this},e.getInheritedInstanceCount=function(){return Object.keys(et).length},e.getLiveInheritedInstances=function(){var e=[];for(var t in et)et.hasOwnProperty(t)&&e.push(et[t]);return e},e.flushPendingDeletes=Qe,e.setDelayFunction=function(e){Ke=e,Je.length&&Ke&&Ke(Qe)},dt.prototype.getPointee=function(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e},dt.prototype.destructor=function(e){this.rawDestructor&&this.rawDestructor(e)},dt.prototype.argPackAdvance=8,dt.prototype.readValueFromPointer=ut,dt.prototype.deleteObject=function(e){null!==e&&e.delete()},dt.prototype.fromWireType=function(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var r=function(e,t){return t=function(e,t){for(void 0===t&&Ne("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),et[t]}(this.registeredClass,t);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=t,r.$$.smartPtr=e,r.clone();var i=r.clone();return this.destructor(e),i}function n(){return this.isSmartPointer?tt(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):tt(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var s,o=this.registeredClass.getActualType(t),a=Ze[o];if(!a)return n.call(this);s=this.isConst?a.constPointerType:a.pointerType;var c=Xe(t,this.registeredClass,s.registeredClass);return null===c?n.call(this):this.isSmartPointer?tt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c,smartPtrType:this,smartPtr:e}):tt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c})},ft=e.UnboundTypeError=Ue(Error,"UnboundTypeError"),e.count_emval_handles=function(){for(var e=0,t=5;t0?r:R(e)+1,n=new Array(i),s=O(e,n,0,n.length);return t&&(n.length=s),n}var hr,lr={na:function(){return e.HEAP8.length},g:function(e,t,r,i){ae("Assertion failed: "+_(e)+", at: "+[t?_(t):"unknown filename",r,i?_(i):"unknown function"])},b:function(e){return ur(e+24)+24},c:function(e,t,r){throw new ye(e).init(t,r),e},Z:function(e,t){try{return e=ke.getStr(e),xe.chmod(e,t),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},_:function(e,t,r,i){try{if(t=ke.getStr(t),t=ke.calculateAt(e,t),-8&r)return-28;var n=xe.lookupPath(t,{follow:!0}).node;if(!n)return-44;var s="";return 4&r&&(s+="r"),2&r&&(s+="w"),1&r&&(s+="x"),s&&xe.nodePermissions(n,s)?-2:0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},r:function(e,t,r){ke.varargs=r;try{var i=ke.getStreamFromFD(e);switch(t){case 0:return(n=ke.get())<0?-28:xe.createStream(i,n).fd;case 1:case 2:case 6:case 7:return 0;case 3:return i.flags;case 4:var n=ke.get();return i.flags|=n,0;case 5:return n=ke.get(),M[n+0>>>1]=2,0;case 16:case 8:default:return-28;case 9:return 28,U[pr()>>>2]=28,-1}}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},Q:function(e,t){try{var r=ke.getStreamFromFD(e);return ke.doStat(xe.stat,r.path,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},I:function(e,t,r){try{var i=ke.getStreamFromFD(e);i.getdents||(i.getdents=xe.readdir(i.path));for(var n=280,s=0,o=xe.llseek(i,0,1),a=Math.floor(o/n);a>>0,(le=c,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[t+s>>>2]=ue[0],U[t+s+4>>>2]=ue[1],ue=[(a+1)*n>>>0,(le=(a+1)*n,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[t+s+8>>>2]=ue[0],U[t+s+12>>>2]=ue[1],M[t+s+16>>>1]=280,L[t+s+18>>>0]=h,D(l,t+s+19,256),s+=n,a+=1}return xe.llseek(i,a*n,0),s}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},$:function(e,t,r){ke.varargs=r;try{var i=ke.getStreamFromFD(e);switch(t){case 21509:case 21505:case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:case 21523:case 21524:return i.tty?0:-59;case 21519:if(!i.tty)return-59;var n=ke.get();return U[n>>>2]=0,0;case 21520:return i.tty?-28:-59;case 21531:return n=ke.get(),xe.ioctl(i,t,n);default:ae("bad ioctl syscall "+t)}}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},N:function(e,t){try{return e=ke.getStr(e),ke.doStat(xe.lstat,e,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},K:function(e,t,r){try{return t=ke.getStr(t),t=ke.calculateAt(e,t),"/"===(t=Se.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),xe.mkdir(t,r,0),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},O:function(e,t,r,i){try{t=ke.getStr(t);var n=256&i,s=4096&i;return i&=-4353,t=ke.calculateAt(e,t,s),ke.doStat(n?xe.lstat:xe.stat,t,r)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},v:function(e,t,r,i){ke.varargs=i;try{t=ke.getStr(t),t=ke.calculateAt(e,t);var n=i?ke.get():0;return xe.open(t,r,n).fd}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},H:function(e){try{return e=ke.getStr(e),xe.rmdir(e),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},P:function(e,t){try{return e=ke.getStr(e),ke.doStat(xe.stat,e,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},F:function(e,t,r){try{return t=ke.getStr(t),t=ke.calculateAt(e,t),0===r?xe.unlink(t):512===r?xe.rmdir(t):ae("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},W:function(e){},Y:function(e,t){ae(Ce)},X:function(e,t){ae(Ce)},B:function(e,t,r,i,n){},ba:function(e,t,r,i,n){var s=Ae(r);ze(e,{name:t=Oe(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?i:n},argPackAdvance:8,readValueFromPointer:function(e){var i;if(1===r)i=L;else if(2===r)i=M;else{if(4!==r)throw new TypeError("Unknown boolean type size: "+t);i=U}return this.fromWireType(i[e>>>s])},destructorFunction:null})},d:function(t,r,i,n,s,o,a,c,h,l,u,d,p){u=Oe(u),o=pt(s,o),c&&(c=pt(a,c)),l&&(l=pt(h,l)),p=pt(d,p);var f=Me(u);st(f,(function(){vt("Cannot construct "+u+" due to unbound types",[n])})),Ve([t,r,i],n?[n]:[],(function(r){var i,s;r=r[0],s=n?(i=r.registeredClass).instancePrototype:it.prototype;var a=Ie(f,(function(){if(Object.getPrototypeOf(this)!==h)throw new We("Use 'new' to construct "+u);if(void 0===d.constructor_body)throw new We(u+" has no accessible constructor");var e=d.constructor_body[arguments.length];if(void 0===e)throw new We("Tried to invoke ctor of "+u+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(d.constructor_body).toString()+") parameters instead!");return e.apply(this,arguments)})),h=Object.create(s,{constructor:{value:a}});a.prototype=h;var d=new ot(u,a,h,p,i,o,c,l),g=new dt(u,d,!0,!1,!1),v=new dt(u+"*",d,!1,!1,!1),m=new dt(u+" const*",d,!1,!0,!1);return Ze[t]={pointerType:v,constPointerType:m},function(t,r,i){e.hasOwnProperty(t)||He("Replacing nonexistant public symbol"),e[t].overloadTable,e[t]=r,e[t].argCount=i}(f,a),[g,v,m]}))},f:function(e,t,r,i,n,s,o){var a=bt(r,i);t=Oe(t),s=pt(n,s),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t;function n(){vt("Cannot call "+i+" due to unbound types",a)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]);var c=e.registeredClass.constructor;return void 0===c[t]?(n.argCount=r-1,c[t]=n):(nt(c,t,i),c[t].overloadTable[r-1]=n),Ve([],a,(function(e){var n=[e[0],null].concat(e.slice(1)),a=St(i,n,null,s,o);return void 0===c[t].overloadTable?(a.argCount=r-1,c[t]=a):c[t].overloadTable[r-1]=a,[]})),[]}))},e:function(e,t,r,i,n,s){C(t>0);var o=bt(t,r);n=pt(i,n),Ve([],[e],(function(e){var r="constructor "+(e=e[0]).name;if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new We("Cannot register multiple constructors with identical number of parameters ("+(t-1)+") for class '"+e.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return e.registeredClass.constructor_body[t-1]=()=>{vt("Cannot construct "+e.name+" due to unbound types",o)},Ve([],o,(function(i){return i.splice(1,0,null),e.registeredClass.constructor_body[t-1]=St(r,i,null,n,s),[]})),[]}))},a:function(e,t,r,i,n,s,o,a){var c=bt(r,i);t=Oe(t),s=pt(n,s),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t;function n(){vt("Cannot call "+i+" due to unbound types",c)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),a&&e.registeredClass.pureVirtualFunctions.push(t);var h=e.registeredClass.instancePrototype,l=h[t];return void 0===l||void 0===l.overloadTable&&l.className!==e.name&&l.argCount===r-2?(n.argCount=r-2,n.className=e.name,h[t]=n):(nt(h,t,i),h[t].overloadTable[r-2]=n),Ve([],c,(function(n){var a=St(i,n,e,s,o);return void 0===h[t].overloadTable?(a.argCount=r-2,h[t]=a):h[t].overloadTable[r-2]=a,[]})),[]}))},k:function(e,t,r,i,n,s,o,a,c,h){t=Oe(t),n=pt(i,n),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t,l={get:function(){vt("Cannot access "+i+" due to unbound types",[r,o])},enumerable:!0,configurable:!0};return l.set=c?()=>{vt("Cannot access "+i+" due to unbound types",[r,o])}:e=>{Ne(i+" is a read-only property")},Object.defineProperty(e.registeredClass.instancePrototype,t,l),Ve([],c?[r,o]:[r],(function(r){var o=r[0],l={get:function(){var t=wt(this,e,i+" getter");return o.fromWireType(n(s,t))},enumerable:!0};if(c){c=pt(a,c);var u=r[1];l.set=function(t){var r=wt(this,e,i+" setter"),n=[];c(h,r,u.toWireType(n,t)),yt(n)}}return Object.defineProperty(e.registeredClass.instancePrototype,t,l),[]})),[]}))},aa:function(e,t){ze(e,{name:t=Oe(t),fromWireType:function(e){var t=kt.toValue(e);return xt(e),t},toWireType:function(e,t){return kt.toHandle(t)},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:null})},i:function(e,t,r,i){var n=Ae(r);function s(){}t=Oe(t),s.values={},ze(e,{name:t,constructor:s,fromWireType:function(e){return this.constructor.values[e]},toWireType:function(e,t){return t.value},argPackAdvance:8,readValueFromPointer:Ct(t,n,i),destructorFunction:null}),st(t,s)},h:function(e,t,r){var i=Pt(e,"enum");t=Oe(t);var n=i.constructor,s=Object.create(i.constructor.prototype,{value:{value:r},constructor:{value:Ie(i.name+"_"+t,(function(){}))}});n.values[r]=s,n[t]=s},y:function(e,t,r){var i=Ae(r);ze(e,{name:t=Oe(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:_t(t,i),destructorFunction:null})},l:function(e,t,r,i,n){t=Oe(t),-1===n&&(n=4294967295);var s=Ae(r),o=e=>e;if(0===i){var a=32-8*r;o=e=>e<>>a}var c=t.includes("unsigned");ze(e,{name:t,fromWireType:o,toWireType:c?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:Ot(t,s,0!==i),destructorFunction:null})},j:function(e,t,r){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function n(e){var t=W,r=t[(e>>=2)>>>0],n=t[e+1>>>0];return new i(F,n,r)}ze(e,{name:r=Oe(r),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{ignoreDuplicateRegistrations:!0})},x:function(e,t){var r="std::string"===(t=Oe(t));ze(e,{name:t,fromWireType:function(e){var t,i=W[e>>>2];if(r)for(var n=e+4,s=0;s<=i;++s){var o=e+4+s;if(s==i||0==B[o>>>0]){var a=_(n,o-n);void 0===t?t=a:(t+=String.fromCharCode(0),t+=a),n=o+1}}else{var c=new Array(i);for(s=0;s>>0]);t=c.join("")}return dr(e),t},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i="string"==typeof t;i||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||Ne("Cannot pass non-string to std::string");var n=(r&&i?()=>R(t):()=>t.length)(),s=ur(4+n+1);if(W[(s>>>=0)>>>2]=n,r&&i)D(t,s+4,n+1);else if(i)for(var o=0;o255&&(dr(s),Ne("String has UTF-16 code units that do not fit in 8 bits")),B[s+4+o>>>0]=a}else for(o=0;o>>0]=t[o];return null!==e&&e.push(dr,s),s},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:function(e){dr(e)}})},s:function(e,t,r){var i,n,s,o,a;r=Oe(r),2===t?(i=V,n=z,o=j,s=()=>I,a=1):4===t&&(i=q,n=$,o=Y,s=()=>W,a=2),ze(e,{name:r,fromWireType:function(e){for(var r,n=W[e>>>2],o=s(),c=e+4,h=0;h<=n;++h){var l=e+4+h*t;if(h==n||0==o[l>>>a]){var u=i(c,l-c);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),c=l+t}}return dr(e),r},toWireType:function(e,i){"string"!=typeof i&&Ne("Cannot pass non-string to C++ string type "+r);var s=o(i),c=ur(4+s+t);return W[(c>>>=0)>>>2]=s>>a,n(i,c+4,s+t),null!==e&&e.push(dr,c),c},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:function(e){dr(e)}})},ca:function(e,t){ze(e,{isVoid:!0,name:t=Oe(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},T:function(){return Date.now()},S:function(){return!0},n:function(e,t,r){e=kt.toValue(e),t=Pt(t,"emval::as");var i=[],n=kt.toHandle(i);return U[r>>>2]=n,t.toWireType(i,e)},sa:function(e,t,r,i,n){return(e=Ft[e])(t=kt.toValue(t),r=Rt(r),function(e){var t=[];return U[e>>>2]=kt.toHandle(t),t}(i),n)},wa:xt,ta:function(e){return 0===e?kt.toHandle(Lt()):(e=Rt(e),kt.toHandle(Lt()[e]))},ra:function(e,t){var r=function(e,t){for(var r=new Array(e),i=0;i>>2],"parameter "+i);return r}(e,t),i=r[0],n=i.name+"_$"+r.slice(1).map((function(e){return e.name})).join("_")+"$",s=Mt[n];if(void 0!==s)return s;for(var o=["retType"],a=[i],c="",h=0;h4&&(Tt[e].refcount+=1)},qa:function(e){return kt.toHandle(Rt(e))},ua:function(e){yt(kt.toValue(e)),xt(e)},o:function(e,t,r){e=kt.toValue(e),t=kt.toValue(t),r=kt.toValue(r),e[t]=r},m:function(e,t){var r=(e=Pt(e,"_emval_take_value")).readValueFromPointer(t);return kt.toHandle(r)},va:function(e){return e=kt.toValue(e),kt.toHandle(typeof e)},U:function(e,t){var r=new Date(1e3*U[e>>>2]);U[t>>>2]=r.getSeconds(),U[t+4>>>2]=r.getMinutes(),U[t+8>>>2]=r.getHours(),U[t+12>>>2]=r.getDate(),U[t+16>>>2]=r.getMonth(),U[t+20>>>2]=r.getFullYear()-1900,U[t+24>>>2]=r.getDay();var i=new Date(r.getFullYear(),0,1),n=(r.getTime()-i.getTime())/864e5|0;U[t+28>>>2]=n,U[t+36>>>2]=-60*r.getTimezoneOffset();var s=new Date(r.getFullYear(),6,1).getTimezoneOffset(),o=i.getTimezoneOffset(),a=0|(s!=o&&r.getTimezoneOffset()==Math.min(o,s));U[t+32>>>2]=a},J:function(e,t,r,i,n,s){try{e>>>=0;var o=xe.getStream(n);o&&(2&r&&ke.doMsync(e,o,t,i,s),xe.munmap(o))}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},V:function e(t,r,i){e.called||(e.called=!0,function(e,t,r){var i=(new Date).getFullYear(),n=new Date(i,0,1),s=new Date(i,6,1),o=n.getTimezoneOffset(),a=s.getTimezoneOffset(),c=Math.max(o,a);function h(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}U[e>>>2]=60*c,U[t>>>2]=Number(o!=a);var l=h(n),u=h(s),d=X(l),p=X(u);a>>2]=d,W[r+4>>>2]=p):(W[r>>>2]=p,W[r+4>>>2]=d)}(t,r,i))},u:function(){ae("")},G:function(){return 4294901760},da:function(e,t,r){(0|e)===e&&(e=_(e)),e=be.resolve(e);var i=ir[e];if(i){var n=i.getContext("2d").getImageData(0,0,i.width,i.height),s=ur(i.width*i.height*4);return B.set(n.data,s>>>0),U[t>>>2]=i.width,U[r>>>2]=i.height,s}return 0},R:function(e,t,r){B.copyWithin(e>>>0,t>>>0,t+r>>>0)},E:function(e){var t,r=B.length,i=4294901760;if((e>>>=0)>i)return!1;for(var n=1;n<=4;n*=2){var s=r*(1+.2/n);if(s=Math.min(s,e+100663296),Gt(Math.min(i,(t=Math.max(e,s))+(65536-t%65536)%65536)))return!0}return!1},L:function(e,t){var r=0;return Vt().forEach((function(i,n){var s=t+r;W[e+4*n>>>2]=s,function(e,t,r){for(var i=0;i>>0]=e.charCodeAt(i);L[t>>>0]=0}(i,s),r+=i.length+1})),0},M:function(e,t){var r=Vt();W[e>>>2]=r.length;var i=0;return r.forEach((function(e){i+=e.length+1})),W[t>>>2]=i,0},oa:function(t){!function(t,r){var i;x=t,x=i=t,te()||(e.onExit&&e.onExit(i),k=!0),p(i,new yr(i))}(t)},p:function(e){try{var t=ke.getStreamFromFD(e);return xe.close(t),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},w:function(e,t,r,i){try{var n=function(e,t,r,i){for(var n=0,s=0;s>>2],a=W[t+4>>>2];t+=8;var c=xe.read(e,L,o,a,undefined);if(c<0)return-1;if(n+=c,c>>2]=n,0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},A:function(e,t,r,i,n){try{var s=(c=r)+2097152>>>0<4194305-!!(a=t)?(a>>>0)+4294967296*c:NaN;if(isNaN(s))return 61;var o=ke.getStreamFromFD(e);return xe.llseek(o,s,i),ue=[o.position>>>0,(le=o.position,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[n>>>2]=ue[0],U[n+4>>>2]=ue[1],o.getdents&&0===s&&0===i&&(o.getdents=null),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}var a,c},q:function(e,t,r,i){try{var n=function(e,t,r,i){for(var n=0,s=0;s>>2],a=W[t+4>>>2];t+=8;var c=xe.write(e,L,o,a,undefined);if(c<0)return-1;n+=c}return n}(ke.getStreamFromFD(e),t,r);return W[i>>>2]=n,0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},pa:function(e){return function(e){var t=ur(20),r=ur(e.length+1);D(e,r,e.length+1),W[t>>>2]=r;var i=ur(4);W[i>>>2]=0,W[t+4>>>2]=i,U[t+8>>>2]=2,U[t+12>>>2]=4;var n=ur(12);return W[n>>>2]=n+8,W[n+4>>>2]=0,U[n+8>>>2]=zt(qt.lookup_name(e)),W[t+16>>>2]=n,t}(_(e))},ma:function(e,t){if(t=_(t),e=$t.programs[e]){!function(e){var t,r,i=e.uniformLocsById,n=e.uniformSizeAndIdsByName;if(!i)for(e.uniformLocsById=i={},e.uniformArrayNamesById={},t=0;t0?o.slice(0,c):o,l=e.uniformIdCounter;for(e.uniformIdCounter+=a,n[h]=[a,l],r=0;r0&&(i=jt(t.slice(s+1))>>>0,n=t.slice(0,s));var o=e.uniformSizeAndIdsByName[n];if(o&&i>>2],i[n+1]=N[r+(4*n+4)>>>2];else i=N.subarray(r>>>2,r+8*t>>>2);rr.uniform2fv(Xt(e),i)},ja:function(e,t,r){if(t<=144)for(var i=Jt[2*t-1],n=0;n<2*t;n+=2)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2];else i=U.subarray(r>>>2,r+8*t>>>2);rr.uniform2iv(Xt(e),i)},fa:function(e,t,r){if(t<=96)for(var i=Zt[3*t-1],n=0;n<3*t;n+=3)i[n]=N[r+4*n>>>2],i[n+1]=N[r+(4*n+4)>>>2],i[n+2]=N[r+(4*n+8)>>>2];else i=N.subarray(r>>>2,r+12*t>>>2);rr.uniform3fv(Xt(e),i)},ia:function(e,t,r){if(t<=96)for(var i=Jt[3*t-1],n=0;n<3*t;n+=3)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2],i[n+2]=U[r+(4*n+8)>>>2];else i=U.subarray(r>>>2,r+12*t>>>2);rr.uniform3iv(Xt(e),i)},ea:function(e,t,r){if(t<=72){var i=Zt[4*t-1],n=N;r>>=2;for(var s=0;s<4*t;s+=4){var o=r+s;i[s]=n[o>>>0],i[s+1]=n[o+1>>>0],i[s+2]=n[o+2>>>0],i[s+3]=n[o+3>>>0]}}else i=N.subarray(r>>>2,r+16*t>>>2);rr.uniform4fv(Xt(e),i)},ha:function(e,t,r){if(t<=72)for(var i=Jt[4*t-1],n=0;n<4*t;n+=4)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2],i[n+2]=U[r+(4*n+8)>>>2],i[n+3]=U[r+(4*n+12)>>>2];else i=U.subarray(r>>>2,r+16*t>>>2);rr.uniform4iv(Xt(e),i)},C:function(e){},D:function(e,t,r,i){return function(e,t,r,i){var n=U[i+40>>>2],s={tm_sec:U[i>>>2],tm_min:U[i+4>>>2],tm_hour:U[i+8>>>2],tm_mday:U[i+12>>>2],tm_mon:U[i+16>>>2],tm_year:U[i+20>>>2],tm_wday:U[i+24>>>2],tm_yday:U[i+28>>>2],tm_isdst:U[i+32>>>2],tm_gmtoff:U[i+36>>>2],tm_zone:n?_(n):""},o=_(r),a={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var c in a)o=o.replace(new RegExp(c,"g"),a[c]);var h=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["January","February","March","April","May","June","July","August","September","October","November","December"];function u(e,t,r){for(var i="number"==typeof e?e.toString():e||"";i.length0?1:0}var i;return 0===(i=r(e.getFullYear()-t.getFullYear()))&&0===(i=r(e.getMonth()-t.getMonth()))&&(i=r(e.getDate()-t.getDate())),i}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function g(e){var t=function(e,t){for(var r=new Date(e.getTime());t>0;){var i=Qt(r.getFullYear()),n=r.getMonth(),s=(i?Kt:er)[n];if(!(t>s-r.getDate()))return r.setDate(r.getDate()+t),r;t-=s-r.getDate()+1,r.setDate(1),n<11?r.setMonth(n+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r}(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),i=new Date(t.getFullYear()+1,0,4),n=f(r),s=f(i);return p(n,t)<=0?p(s,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var v={"%a":function(e){return h[e.tm_wday].substring(0,3)},"%A":function(e){return h[e.tm_wday]},"%b":function(e){return l[e.tm_mon].substring(0,3)},"%B":function(e){return l[e.tm_mon]},"%C":function(e){return d((e.tm_year+1900)/100|0,2)},"%d":function(e){return d(e.tm_mday,2)},"%e":function(e){return u(e.tm_mday,2," ")},"%g":function(e){return g(e).toString().substring(2)},"%G":function(e){return g(e)},"%H":function(e){return d(e.tm_hour,2)},"%I":function(e){var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":function(e){return d(e.tm_mday+function(e,t){for(var r=0,i=0;i<=t;r+=e[i++]);return r}(Qt(e.tm_year+1900)?Kt:er,e.tm_mon-1),3)},"%m":function(e){return d(e.tm_mon+1,2)},"%M":function(e){return d(e.tm_min,2)},"%n":function(){return"\n"},"%p":function(e){return e.tm_hour>=0&&e.tm_hour<12?"AM":"PM"},"%S":function(e){return d(e.tm_sec,2)},"%t":function(){return"\t"},"%u":function(e){return e.tm_wday||7},"%U":function(e){var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":function(e){var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&Qt(e.tm_year)||(t=1)}}else{t=52;var i=(e.tm_wday+7-e.tm_yday-1)%7;(4==i||5==i&&Qt(e.tm_year%400-1))&&t++}return d(t,2)},"%w":function(e){return e.tm_wday},"%W":function(e){var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":function(e){return(e.tm_year+1900).toString().substring(2)},"%Y":function(e){return e.tm_year+1900},"%z":function(e){var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":function(e){return e.tm_zone},"%%":function(){return"%"}};for(var c in o=o.replace(/%%/g,"\0\0"),v)o.includes(c)&&(o=o.replace(new RegExp(c,"g"),v[c](s)));var m=cr(o=o.replace(/\0\0/g,"%"),!1);return m.length>t?0:(function(e,t){L.set(e,t>>>0)}(m,e),m.length-1)}(e,t,r,i)}},ur=(function(){var t={a:lr};function r(t,r){var i,n=t.exports;e.asm=n,Z((E=e.asm.xa).buffer),J=e.asm.Ea,i=e.asm.ya,K.unshift(i),oe()}function n(e){r(e.instance)}function o(e){return function(){if(!b&&(f||g)){if("function"==typeof fetch&&!pe(ce))return fetch(ce,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+ce+"'";return e.arrayBuffer()})).catch((function(){return fe(ce)}));if(s)return new Promise((function(e,t){s(ce,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return fe(ce)}))}().then((function(e){return WebAssembly.instantiate(e,t)})).then((function(e){return e})).then(e,(function(e){S("failed to asynchronously prepare wasm: "+e),ae(e)}))}if(se(),e.instantiateWasm)try{return e.instantiateWasm(t,r)}catch(e){return S("Module.instantiateWasm callback failed with error: "+e),!1}(b||"function"!=typeof WebAssembly.instantiateStreaming||de(ce)||pe(ce)||v||"function"!=typeof fetch?o(n):fetch(ce,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,t).then(n,(function(e){return S("wasm streaming compile failed: "+e),S("falling back to ArrayBuffer instantiation"),o(n)}))}))).catch(i)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.ya).apply(null,arguments)},e._malloc=function(){return(ur=e._malloc=e.asm.za).apply(null,arguments)}),dr=e._free=function(){return(dr=e._free=e.asm.Aa).apply(null,arguments)},pr=e.___errno_location=function(){return(pr=e.___errno_location=e.asm.Ba).apply(null,arguments)},fr=e.___getTypeName=function(){return(fr=e.___getTypeName=e.asm.Ca).apply(null,arguments)},gr=(e.___embind_register_native_and_builtin_types=function(){return(e.___embind_register_native_and_builtin_types=e.asm.Da).apply(null,arguments)},e._htons=function(){return(gr=e._htons=e.asm.Fa).apply(null,arguments)}),vr=e._emscripten_builtin_memalign=function(){return(vr=e._emscripten_builtin_memalign=e.asm.Ga).apply(null,arguments)},mr=e.___cxa_is_pointer_type=function(){return(mr=e.___cxa_is_pointer_type=e.asm.Ha).apply(null,arguments)};function yr(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function Sr(r){function i(){hr||(hr=!0,e.calledRun=!0,k||(e.noFSInit||xe.init.initialized||xe.init(),xe.ignorePermissions=!1,we.init(),ge(K),t(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),function(){if(e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;)t=e.postRun.shift(),ee.unshift(t);var t;ge(ee)}()))}r=r||u,re>0||(function(){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)t=e.preRun.shift(),Q.unshift(t);var t;ge(Q)}(),re>0||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),i()}),1)):i()))}if(e.dynCall_jiji=function(){return(e.dynCall_jiji=e.asm.Ia).apply(null,arguments)},e.dynCall_viijii=function(){return(e.dynCall_viijii=e.asm.Ja).apply(null,arguments)},e.dynCall_iiiiij=function(){return(e.dynCall_iiiiij=e.asm.Ka).apply(null,arguments)},e.dynCall_iiiiijj=function(){return(e.dynCall_iiiiijj=e.asm.La).apply(null,arguments)},e.dynCall_iiiiiijj=function(){return(e.dynCall_iiiiiijj=e.asm.Ma).apply(null,arguments)},e.dynCall_viiiiji=function(){return(e.dynCall_viiiiji=e.asm.Na).apply(null,arguments)},e.dynCall_viiijj=function(){return(e.dynCall_viiijj=e.asm.Oa).apply(null,arguments)},e.FS=xe,ne=function e(){hr||Sr(),hr||(ne=e)},e.run=Sr,e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Sr(),e.ready});const _e=Ae;class Oe{constructor(e){this.occ=e,this.hashesFromPreviousRun={},this.usedHashes={},this.argCache={}}cleanAllCache(){Object.keys(this.usedHashes).forEach((e=>{if(this.argCache[e])try{const t=this.argCache[e];this.occ.BRepTools.Clean(t,!0),this.occ.BRepTools.CleanGeometry(t),t.delete()}catch(e){}})),this.argCache={},this.usedHashes={},this.hashesFromPreviousRun={}}cleanCacheForHash(e){if(this.argCache[e])try{const t=this.argCache[e];this.occ.BRepTools.Clean(t,!0),this.occ.BRepTools.CleanGeometry(t),t.delete()}catch(e){}delete this.argCache[e],delete this.usedHashes[e],delete this.hashesFromPreviousRun[e]}cleanUpCache(){}isOCCTObject(e){return null!=e&&!Array.isArray(e)&&void 0!==e.$$||Array.isArray(e)&&e.length>0&&void 0!==e[0].$$}cacheOp(e,t){let r=null;const i=this.computeHash(e);this.usedHashes[i]=i,this.hashesFromPreviousRun[i]=i;const n=this.checkCache(i);if(n)this.isOCCTObject(n)?(r=n,r.hash=n.hash):n.value&&(r=n.value);else if(r=t(),Array.isArray(r)&&this.isOCCTObject(r))r.forEach(((t,r)=>{const i=this.computeHash(Object.assign(Object.assign({},e),{index:r}));t.hash=i,this.addToCache(i,t)}));else if(this.isOCCTObject(r))r.hash=i,this.addToCache(i,r);else if(r.compound&&r.data&&r.shapes&&r.shapes.length>0){const t=r,n=this.computeHash(Object.assign(Object.assign({},e),{index:"compound"}));t.compound.hash=n,this.addToCache(n,t.compound),t.shapes.forEach(((t,r)=>{const i=this.computeHash(Object.assign(Object.assign({},e),{index:r}));t.shape.hash=i,this.addToCache(i,t.shape)})),this.addToCache(i,{value:t})}else this.addToCache(i,{value:r});return r}checkCache(e){return this.argCache[e]||null}addToCache(e,t){const r=t;return r.hash=e,this.argCache[e]=r,e}computeHash(e,t){let r=JSON.stringify(e);r=r.replace(/(\"ptr\"\:(-?[0-9]*?)\,)/g,""),r=r.replace(/(\"ptr\"\:(-?[0-9]*))/g,""),r.includes("ptr")&&console.error("YOU DONE MESSED UP YOUR REGEX.");const i=Math.random.toString()+r;return t?i:this.stringToHash(i)}stringToHash(e){let t=0;if(0===e.length)return t;for(let r=0;re.hash!==t.hash||e.ptr!==t.ptr))}dupShape(e){return e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?this.occ.TopoDS.Wire_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?this.occ.TopoDS.Shell_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?this.occ.TopoDS.Edge_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?this.occ.TopoDS.Solid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?this.occ.TopoDS.Face_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.occ.TopoDS.Compound_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.occ.TopoDS.CompSolid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?this.occ.TopoDS.Vertex_1(e):void 0}}let De,Re,Fe;class Le{static distributeBetweenBounds(e,t,r,i=!1){const n=[];let s=r;for(i&&n.push(s);s>t;)s-=e,n.push(s);return n}static computeSideA(e,t){const r=e*Math.PI/180,i=t/Math.cos(r),n=Math.pow(i,2)-Math.pow(t,2);return Math.sqrt(n)}static computeSideAFromHypotenuseAndAngle(e,t){const r=e*Math.PI/180;return t*Math.sin(r)}static computeHypotenuse(e,t){return t/Math.cos(e*Math.PI/180)}}var Be,Me,Ie,Ue,We,Ne;!function(e){e.low="low",e.middle="middle",e.high="high"}(Be||(Be={}));class Ge{constructor(){this.lod=Be.low}}class He{}class Ve{constructor(e,t,r,i,n,s,o,a,c){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.addRadiusNarrow=r),void 0!==i&&(this.addRadiusWide=i),void 0!==n&&(this.addMiddleHeight=n),void 0!==s&&(this.addTopHeight=s),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==c&&(this.origin=c)}}class ze{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class je{}class qe{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=Be.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==r&&(this.archCenterThickness=r),void 0!==i&&(this.edgesThickness=i),void 0!==n&&(this.thickness=n),void 0!==s&&(this.baseHeight=s),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.origin=h),void 0!==l&&(this.direction=l),void 0!==u&&(this.scale=u)}}class $e{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class Ye{}class Xe{}class Ze{}class Je{constructor(e,t,r,i,n,s,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==r&&(this.fullModel=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.decorationThickness=n),void 0!==s&&(this.rotation=s),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class Qe{constructor(){this.type="parametric-model",this.name="eternalLove"}}class Ke{}class et{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==r&&(this.radiusTopOffset=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.fillet=n),void 0!==s&&(this.nrOfHandles=s),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.scale=h),void 0!==l&&(this.origin=l),void 0!==u&&(this.direction=u)}}class tt{constructor(){this.type="parametric-model",this.name="calmCup"}}class rt{}class it{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y,S,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==r&&(this.radiusTopOffset=r),void 0!==i&&(this.radiusMidOffset=i),void 0!==n&&(this.rotationTopAngle=n),void 0!==s&&(this.rotationMidAngle=s),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==c&&(this.nrSkinCellDivisionsTop=c),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==l&&(this.skinCellOuterHeight=l),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==p&&(this.skinCellTopHeight=p),void 0!==f&&(this.thickness=f),void 0!==g&&(this.bottomThickness=g),void 0!==v&&(this.precision=v),void 0!==m&&(this.rotation=m),void 0!==y&&(this.scale=y),void 0!==S&&(this.origin=S),void 0!==b&&(this.direction=b)}}class nt{constructor(){this.type="parametric-model",this.name="dragonCup"}}class st{}class ot{}class at{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==r&&(this.widthBack=r),void 0!==i&&(this.widthFront=i),void 0!==n&&(this.length=n),void 0!==s&&(this.backOffset=s),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==c&&(this.filletRadius=c),void 0!==h&&(this.phoneHeight=h),void 0!==l&&(this.phoneWidth=l),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdges=p),void 0!==f&&(this.rotation=f),void 0!==g&&(this.scale=g),void 0!==v&&(this.origin=v),void 0!==m&&(this.direction=m)}}class ct{constructor(){this.type="parametric-model",this.name="phoneNest"}}class ht extends He{}class lt{}class ut extends He{}class dt{}class pt{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class ft{}class gt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==r&&(this.nrSides=r),void 0!==i&&(this.nrOffsets=i),void 0!==n&&(this.height=n),void 0!==s&&(this.coverHeight=s),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==c&&(this.radiusOffset=c),void 0!==h&&(this.thickness=h),void 0!==l&&(this.ornamentalThickness=l),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==p&&(this.fillet=p),void 0!==f&&(this.precision=f),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==m&&(this.origin=m),void 0!==y&&(this.direction=y)}}class vt{constructor(){this.type="parametric-model",this.name="spicyBox"}}class mt{}class yt{}class St{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y,S,b,w,E,T,x,k,C,P,A,_){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=Be.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==r&&(this.terraceWidth=r),void 0!==i&&(this.widthSecondWing=i),void 0!==n&&(this.lengthSecondWing=n),void 0!==s&&(this.heightWalls=s),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==c&&(this.roofOffset=c),void 0!==h&&(this.roofInsideOverhang=h),void 0!==l&&(this.roofMaxDistAttachmentBeams=l),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==p&&(this.roofOutsideOverhang=p),void 0!==f&&(this.columnSize=f),void 0!==g&&(this.ceilingBeamHeight=g),void 0!==v&&(this.ceilingBeamWidth=v),void 0!==m&&(this.nrCeilingBeamsBetweenColumns=m),void 0!==y&&(this.distBetweenColumns=y),void 0!==S&&(this.floorHeight=S),void 0!==b&&(this.groundLevel=b),void 0!==w&&(this.facadePanelThickness=w),void 0!==E&&(this.windowWidthOffset=E),void 0!==T&&(this.windowHeightOffset=T),void 0!==x&&(this.windowFrameThickness=x),void 0!==k&&(this.windowGlassFrameThickness=k),void 0!==C&&(this.lod=C),void 0!==P&&(this.skinOpacity=P),void 0!==A&&(this.rotation=A),void 0!==_&&(this.origin=_)}}class bt{constructor(){this.type="parametric-model",this.name="zenHideout"}}class wt{}class Et{}class Tt{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class xt{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class kt extends xt{}class Ct extends Tt{}class Pt{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class At{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class _t extends Pt{}class Ot extends At{}class Dt{}class Rt{}class Ft{}class Lt{}class Bt{}class Mt{}class It{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class Ut extends It{}class Wt{}class Nt{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=Be.high,this.center=[0,0,0],this.direction=[0,1,0]}}class Gt extends Nt{}class Ht{}class Vt{}class zt{constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class jt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==r&&(this.interiorHeight=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.holeDiameter=n),void 0!==s&&(this.holeDistToBottom=s),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==c&&(this.baseAttachmentHeight=c),void 0!==h&&(this.roofOverhang=h),void 0!==l&&(this.rotation=l),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class qt{constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class $t{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==r&&(this.interiorHeight=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.holeDiameter=n),void 0!==s&&(this.holeDistToBottom=s),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==c&&(this.baseAttachmentHeight=c),void 0!==h&&(this.roofOverhang=h),void 0!==l&&(this.roofAngle=l),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class Yt{constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class Xt{}class Zt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==r&&(this.backRestHeight=r),void 0!==i&&(this.width=i),void 0!==n&&(this.length=n),void 0!==s&&(this.thickness=s),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==c&&(this.filletRadius=c),void 0!==h&&(this.precision=h),void 0!==l&&(this.drawEdges=l),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==p&&(this.origin=p),void 0!==f&&(this.direction=f)}}class Jt{constructor(){this.type="parametric-model",this.name="snakeChair"}}class Qt extends He{}class Kt{}class er extends He{}class tr{}class rr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class ir{}class nr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.topThickness=i),void 0!==n&&(this.topOffset=n),void 0!==s&&(this.bottomThickness=s),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==c&&(this.radiusLegBottom=c),void 0!==h&&(this.nrLegPairs=h),void 0!==l&&(this.precision=l),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==p&&(this.scale=p),void 0!==f&&(this.origin=f),void 0!==g&&(this.direction=g)}}class sr{constructor(){this.type="parametric-model",this.name="elegantTable"}}class or extends He{}class ar{}class cr extends He{}class hr extends He{}class lr{constructor(){this.index=0}}class ur{}class dr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class pr{}class fr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.chamfer=i),void 0!==n&&(this.topThickness=n),void 0!==s&&(this.topGlassOffset=s),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==c&&(this.shelfTopOffset=c),void 0!==h&&(this.shelfThickness=h),void 0!==l&&(this.legWidth=l),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdges=p),void 0!==f&&(this.rotation=f),void 0!==g&&(this.scale=g),void 0!==v&&(this.origin=v),void 0!==m&&(this.direction=m)}}class gr{constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class vr extends He{}class mr{}class yr extends He{}class Sr extends He{}class br extends He{}class wr{constructor(){this.index=0}}class Er{}class Tr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class xr{}class kr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.supportLength=i),void 0!==n&&(this.shelfHeight=n),void 0!==s&&(this.thickness=s),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==c&&(this.nrOrnamentPlanks=c),void 0!==h&&(this.ornamentDepth=h),void 0!==l&&(this.filletRadius=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class Cr{constructor(){this.type="parametric-model",this.name="snakeTable"}}class Pr extends He{}class Ar{}class _r extends He{}class Or{}class Dr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(Me||(Me={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(Ie||(Ie={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(Ue||(Ue={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(We||(We={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(Ne||(Ne={}));const Rr=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class Fr{constructor(e,t,r,i,n,s,o,a,c){this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==r&&(this.fontVariant=r),void 0!==i&&(this.fontSize=i),void 0!==n&&(this.height=n),void 0!==s&&(this.rotation=s),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==c&&(this.originAlignment=c)}}class Lr{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.facePlanar=!1,this.faceTextVar=Ue.separatedExtrusion,this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==r&&(this.faceTextVar=r),void 0!==i&&(this.text=i),void 0!==n&&(this.fontType=n),void 0!==s&&(this.fontVariant=s),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.originParamU=h),void 0!==l&&(this.originParamV=l),void 0!==u&&(this.originAlignment=u)}}class Br{constructor(){this.type="parametric-model",this.name="text3d"}}class Mr{constructor(){this.index=0}}class Ir{}class Ur{}class Wr{constructor(e,t,r,i,n,s,o,a,c,h){this.faceTextVar=Ue.separatedExtrusion,this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==r&&(this.fontType=r),void 0!==i&&(this.fontVariant=i),void 0!==n&&(this.fontSize=n),void 0!==s&&(this.height=s),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==c&&(this.originParamV=c),void 0!==h&&(this.originAlignment=h)}}class Nr{constructor(e,t,r){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==r&&(this.definitions=r)}}class Gr{constructor(e,t,r,i){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==i&&(this.height=i)}}class Hr{constructor(e,t,r,i,n,s,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==r&&(this.uNumber=r),void 0!==i&&(this.vNumber=i),void 0!==n&&(this.affectMinHeight=n),void 0!==s&&(this.affectMaxHeight=s),void 0!==o&&(this.precision=o)}}class Vr{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class zr{constructor(){this.index=0}}class jr{}class qr{}class $r{}class Yr{}class Xr{constructor(){this.faceIndex=0}}class Zr{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class Jr{constructor(){this.faceIndex=0,this.uIndex=0}}class Qr{constructor(){this.faceIndex=0,this.vIndex=0}}class Kr{}class ei{}var ti,ri,ii;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(ti||(ti={}));class ni{static parse(e,t,r){const i=[e];let n=0;for(;i.length>0;){const e=i.pop();if("object"==typeof e&&null!==e)if(Array.isArray(e))for(let t=0;t{const a=o.shapes[e];if(a){const c=t.transforms.rotate({shape:a,angle:r,axis:[0,1,0]}),h=t.transforms.alignAndTranslate({shape:c,direction:i,center:n});1!==s[0]||1!==s[1]||1!==s[2]?(o.shapes[e]=t.transforms.scale3d({shape:h,scale:s,center:n}),h.delete()):o.shapes[e]=h,c.delete()}})),Object.keys(o).forEach((e=>{const a=o[e];a&&Array.isArray(a)?o[e]=a.map((e=>e&&"object"==typeof e&&null!==e&&e.shapes?this.alignAndTranslateShapesWithChildren(e,t,r,i,n,s):e)):a&&"object"==typeof a&&null!==a&&a.shapes&&(o[e]=this.alignAndTranslateShapesWithChildren(a,t,r,i,n,s))})),o}static deleteAllShapes(e){Object.keys(e.shapes).forEach((t=>{e.shapes[t].delete()})),Object.keys(e).forEach((t=>{const r=e[t];r&&Array.isArray(r)?r.forEach((e=>{e&&"object"==typeof e&&null!==e&&e.shapes&&this.deleteAllShapes(e)})):r&&"object"==typeof r&&null!==r&&r.shapes&&this.deleteAllShapes(r)}))}static deepCopy(e){const t=Object.assign(Object.assign({},e),{shapes:Object.assign({},e.shapes)});return Object.keys(e).forEach((r=>{const i=e[r];i&&"object"==typeof i&&null!==i?i.shapes&&(t[r]=this.deepCopy(i)):i&&Array.isArray(i)&&(t[r]=i.map((e=>e&&"object"==typeof e&&null!==e&&e.shapes?this.deepCopy(e):e)))})),t}}class si{constructor(e,t,r){this.occtService=e,this.dependencies=r,this.occtAdv=t}wingtipVilla(e){return function(e,t){!function(e){let t;if(["interiorWidth","interiorLength","interiorHeight","chimneyHeight","roofOverhang","thickness","holeDiameter","holeDistToBottom","stickDiameter","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.interiorWidth<=0?t=`interior width can't be ${e.interiorWidth}, which is lower or equal to 0`:e.interiorLength<=0?t=`interior length can't be ${e.interiorLength}, which is lower or equal to 0`:e.interiorHeight<=0?t=`interior height can't be ${e.interiorHeight}, which is lower or equal to 0`:e.chimneyHeight<=0?t=`chimney height can't be ${e.chimneyHeight}, which is lower or equal to 0`:e.interiorWidthe.holeDistToBottom&&(t="The stick diameter is larger than the hole's distance to bottom. Stick can't fit the surface. Model can't be made."),t)throw new Error(t)}(e);const r=e.baseAttachmentHeight,i=e.roofOverhang,n=e.chimneyHeight,s=(e.interiorWidth+2*e.thickness)/2,o=Le.computeSideA(45,s),a=function(e,t){const r=Math.pow(e,2)+Math.pow(t,2);return Math.sqrt(r)}(o,s),c=e.thickness,h=[],l=t.shapes.wire.createPolygonWire({points:[[-s,-r-c,0],[s,-r-c,0],[s,e.interiorHeight,0],[0,e.interiorHeight+o,0],[-s,e.interiorHeight,0]].reverse()});h.push(l);const u=e.interiorLength+e.thickness,d=t.shapes.wire.createPolygonWire({points:[[-s,-c,u],[s,-c,u],[s,e.interiorHeight,u],[0,e.interiorHeight+o,u],[-s,e.interiorHeight,u]].reverse()});h.push(d);const p=t.shapes.wire.createCircleWire({radius:e.holeDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom+e.holeDiameter/2,u]});h.push(p);const f=t.shapes.wire.createCircleWire({radius:e.stickDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom/2,u+c]});h.push(f);const g=t.shapes.face.createFaceFromWire({shape:f,planar:!0});h.push(g);const v=t.operations.extrude({shape:g,direction:[0,0,e.stickLength]}),m=t.shapes.solid.createBoxFromCorner({corner:[-s+c,-c,c],width:e.interiorWidth,length:e.interiorLength,height:c}),y=t.shapes.solid.createBoxFromCorner({corner:[-s,-c,c],width:c,length:e.interiorLength,height:e.interiorHeight+c}),S=t.shapes.solid.createBoxFromCorner({corner:[s-c,-c,c],width:c,length:e.interiorLength,height:e.interiorHeight+c}),b=t.shapes.solid.createBoxFromCorner({corner:[0,0,0],width:a+i,length:e.interiorLength+2*c+i,height:c}),w=t.shapes.solid.createBoxFromCorner({corner:[0,-c,0],width:a+i+c,length:e.interiorLength+2*c+i,height:c}),E=t.transforms.rotate({shape:b,angle:-45,axis:[0,0,1]});h.push(E);const T=t.transforms.translate({shape:E,translation:[0,e.interiorHeight+o,0]}),x=t.shapes.edge.getCornerPointsOfEdgesForShape({shape:T}),k=t.transforms.rotate({shape:w,angle:225,axis:[0,0,1]});h.push(k);const C=t.transforms.translate({shape:k,translation:x[3]}),P=t.shapes.face.createFaceFromWire({shape:l,planar:!0});h.push(P);const A=t.operations.makeThickSolidSimple({shape:P,offset:-e.thickness}),_=t.shapes.face.createFaceFromWire({shape:d,planar:!0});h.push(_);const O=t.operations.splitShapeWithShapes({shape:_,shapes:[p]});h.push(O);const D=t.shapes.face.getFace({shape:O,index:0});h.push(D);const R=t.operations.makeThickSolidSimple({shape:D,offset:-e.thickness}),F=function(e,t,r){const i=e.shapes.face.getFaces({shape:t})[3],n=e.shapes.face.getFaceCenterOfMass({shape:i}),s=e.transforms.scale3d({shape:i,scale:[.3,.3,.3],center:n}),o=e.shapes.edge.getCornerPointsOfEdgesForShape({shape:s}),a=o[0],c=o[1],h=o[2],l=o[3],u=Math.max(a[1],c[1],h[1],l[1]),d=[a[0],u+r,a[2]],p=[c[0],u+r,c[2]],f=[h[0],u+r,h[2]],g=[l[0],u+r,l[2]],v=e.shapes.wire.createPolygonWire({points:[a,c,h,l]}),m=e.shapes.wire.createPolygonWire({points:[d,p,f,g]}),y=e.operations.loft({shapes:[v,m],makeSolid:!0});return i.delete(),s.delete(),v.delete(),m.delete(),y}(t,T,n),L=[m,A,R,y,S,T,C,v,t.shapes.compound.makeCompound({shapes:[T,C]}),t.shapes.compound.makeCompound({shapes:[A,R,y,S]}),F],B=L.map(((r,i)=>{const n=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]});return t.transforms.translate({shape:n,translation:e.origin})})),M=t.shapes.compound.makeCompound({shapes:B});return L.forEach((e=>e.delete())),h.forEach((e=>e.delete())),{compound:M,shapes:B.map(((e,t)=>({id:t.toString(),shape:e}))),data:{type:"parametric-model",name:"wingtipVilla",roof:{compound:"8",shapes:["5","6"]},walls:{compound:"9",shapes:["1","2","3","4"]},floor:{shape:"0"},stick:{shape:"7"},chimney:{shape:"10"},basicPoints:[{kind:"origin",point:e.origin}]}}}(e,this.occtService)}chirpyChalet(e){return function(e,t){!function(e){let t;if(["interiorWidth","interiorLength","interiorHeight","roofAngle","roofOverhang","thickness","holeDiameter","holeDistToBottom","stickDiameter","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.interiorWidth<=0?t=`interior width can't be ${e.interiorWidth}, which is lower or equal to 0`:e.interiorLength<=0?t=`interior length can't be ${e.interiorLength}, which is lower or equal to 0`:e.interiorHeight<=0?t=`interior height can't be ${e.interiorHeight}, which is lower or equal to 0`:e.interiorWidthe.holeDistToBottom&&(t="The stick diameter is larger than the hole's distance to bottom. Stick can't fit the surface. Model can't be made."),t)throw new Error(t)}(e);const r=e.baseAttachmentHeight,i=e.roofOverhang,n=e.roofAngle,s=e.interiorWidth/2,o=e.interiorLength+2*e.thickness,a=Le.computeSideA(n,o),c=Le.computeSideA(n,o-e.thickness),h=function(e,t){const r=Math.pow(e,2)+Math.pow(t,2);return Math.sqrt(r)}(a,o),l=e.thickness,u=[],d=t.shapes.wire.createPolygonWire({points:[[-s,-r-l,0],[s,-r-l,0],[s,e.interiorHeight+c,0],[-s,e.interiorHeight+c,0]].reverse()});u.push(d);const p=e.interiorLength+e.thickness,f=t.shapes.wire.createPolygonWire({points:[[-s,-l,p],[s,-l,p],[s,e.interiorHeight,p],[-s,e.interiorHeight,p]].reverse()});u.push(f);const g=t.shapes.wire.createCircleWire({radius:e.holeDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom+e.holeDiameter/2,p]});u.push(g);const v=t.shapes.wire.createCircleWire({radius:e.stickDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom/2,p+l]});u.push(v);const m=t.shapes.face.createFaceFromWire({shape:v,planar:!0});u.push(m);const y=t.operations.extrude({shape:m,direction:[0,0,e.stickLength]}),S=t.shapes.solid.createBoxFromCorner({corner:[-s,-l,l],width:e.interiorWidth,length:e.interiorLength,height:l}),b=t.shapes.wire.createPolygonWire({points:[[-s,-l,0],[-s,-l,p+l],[-s,e.interiorHeight,p+l],[-s,e.interiorHeight+a,0]].reverse()}),w=t.shapes.face.createFaceFromWire({shape:b,planar:!0}),E=t.operations.extrude({shape:w,direction:[-l,0,0]}),T=t.transforms.translate({shape:E,translation:[e.interiorWidth+l,0,0]}),x=t.shapes.solid.createBoxFromCorner({corner:[-s-l-i,0,0],width:e.interiorWidth+2*l+2*i,length:h+i,height:l}),k=t.transforms.rotate({shape:x,angle:n,axis:[1,0,0]});u.push(k);const C=t.transforms.translate({shape:k,translation:[0,e.interiorHeight+a,0]}),P=t.shapes.face.createFaceFromWire({shape:d,planar:!0});u.push(P);const A=t.operations.makeThickSolidSimple({shape:P,offset:-e.thickness}),_=t.shapes.face.createFaceFromWire({shape:f,planar:!0});u.push(_);const O=t.operations.splitShapeWithShapes({shape:_,shapes:[g]});u.push(O);const D=t.shapes.face.getFace({shape:O,index:0});u.push(D);const R=t.operations.makeThickSolidSimple({shape:D,offset:-e.thickness}),F=[S,A,R,E,T,C,y,t.shapes.compound.makeCompound({shapes:[C]}),t.shapes.compound.makeCompound({shapes:[A,R,E,T]})],L=F.map(((r,i)=>{const n=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]});return t.transforms.translate({shape:n,translation:e.origin})})),B=t.shapes.compound.makeCompound({shapes:L});return F.forEach((e=>e.delete())),u.forEach((e=>e.delete())),{compound:B,shapes:L.map(((e,t)=>({id:t.toString(),shape:e}))),data:{type:"parametric-model",name:"chirpyChalet",roof:{compound:"7",shapes:["5","6"]},walls:{compound:"8",shapes:["1","2","3","4"]},floor:{shape:"0"},stick:{shape:"6"},basicPoints:[{kind:"origin",point:e.origin}]}}}(e,this.occtService)}serenitySwirl(t){return function(t,r,i){if(function(e){let t;if(["swirl","nrOfDivisions","addRadiusNarrow","addRadiusWide","addMiddleHeight","addTopHeight","thickness","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.swirl<0?t="swirl value should be between 0 and 1":e.nrOfDivisions<=0?t=`nrOfDivisions can't be ${e.nrOfDivisions}, which is lower or equal to 0`:e.addRadiusNarrow<0?t=`addRadiusNarrow can't be ${e.addRadiusNarrow}, which is lower then 0`:e.addRadiusWide<0?t=`addRadiusWide can't be ${e.addRadiusWide}, which is lower then 0`:e.addMiddleHeight<=0?t=`addMiddleHeight can't be ${e.addMiddleHeight}, which is lower or equal to 0`:e.addTopHeight<=0?t=`addTopHeight can't be ${e.addTopHeight}, which is lower or equal to 0`:e.thickness<=0?t=`thickness can't be ${e.thickness}, which is lower or equal to 0`:3!==e.origin.length&&(t="The origin should be a vector of 3 numbers."),t)throw new Error(t)}(t),!i.serenitySwirl)throw new Error("Could not compute, to use Serenity Swirl algorithm you must be subscribed.");try{const n=`\n ${i.serenitySwirl}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}arabicArchway(t){return function(t,r,i){if(function(e){let t;if(["nrOfSides","thickness","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.nrOfSides<0?t="swirl value should be between 0 and 1":e.nrOfSides<3?t=`nrOfSides can't be ${e.nrOfSides}, which is lower to 3`:e.nrOfSides>30?t=`nrOfSides can't be ${e.nrOfSides}, which is higher then 30`:e.thickness<=0?t=`thickness can't be ${e.thickness}, which is lower or equal to 0`:3!==e.origin.length&&(t="The origin should be a vector of 3 numbers."),t)throw new Error(t)}(t),!i.arabicArchway)throw new Error("Could not compute, to use Arabic Archway algorithm you must be subscribed.");try{const n=`\n ${i.arabicArchway}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}eternalLove(t){return function(t,r,i,n){if(!n.eternalLove)throw new Error("Could not compute, to use Eternal Love algorithm you must be subscribed to our silver plan.");try{const s=`\n ${n.eternalLove}\n `;return new Function(s).apply({inputs:t,occt:r,occtAdv:i,Inputs:e,Text3D:R})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}calmCup(t){return function(t,r,i,n){if(function(e){let t;if(["height","radiusBottom","radiusTopOffset","thickness","fillet","nrOfHandles","handleDist","precision","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<6*e.thickness?t="Height must be at least 6 times greater than thickness.":e.radiusBottom<=0?t="Radius bottom must be greater than 0.":e.thickness<=0?t="Thickness must be greater than 0.":e.fillet<0||e.fillet>e.thickness/2?t="Fillet must be greater than 0 and less than half of the thickness.":e.handleDist<=2*e.thickness?t="Handle distance from cup must be greater than 2 times the thickness.":e.nrOfHandles<0||e.nrOfHandles>2?t="Nr of handles must be between 0 and 2.":e.radiusTopOffset>.75*e.radiusBottom&&(t="Top offset radius must be less than 0.75 times the bottom radius."),t)throw new Error(t)}(t),!n.calmCup)throw new Error("Could not compute, to use Calm Cup algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.calmCup}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}spicyBox(t){return function(t,r,i,n){if(!n.spicyBox)throw new Error("Could not compute, to use Spicy Box algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.spicyBox}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}dragonCup(t){return function(t,r,i,n){if(function(e){let t;if(["height","radiusBottom","radiusTopOffset","thickness","nrSkinCellsHorizontal","nrSkinCellsVertical","precision","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.radiusBottom<=0?t="Radius bottom must be greater than 0.":e.thickness<=0?t="Thickness must be greater than 0.":e.nrSkinCellsHorizontal<=2?t="Nr of horizontal skin cells must be larger than 2.":e.nrSkinCellsVertical<1&&(t="Nr of horizontal skin cells must be larger than 0."),t)throw new Error(t)}(t),!n.dragonCup)throw new Error("Could not compute, to use Dragon Cup algorithm you must be subscribed to our silver plan.");try{const s=`\n ${n.dragonCup}\n `;return new Function(s).apply({inputs:t,occt:r,occtAdv:i,Inputs:e,Advanced:G})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}zenHideout(t){return function(t,r,i){if(function(e){let t;if([].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),t)throw new Error(t)}(t),!i.zenHideout)throw new Error("Could not compute, to use Zen Hideout algorithm you must be subscribed.");try{const n=`\n ${i.zenHideout}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e,Things:D,MathHelper:Le,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}elegantTable(t){return function(t,r,i,n){if(!n.elegantTable)throw new Error("Could not compute, to use Elegant Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.elegantTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}goodCoffeeTable(t){return function(t,r,i,n){if(function(e){let t;if(["height","width","length","topThickness","topGlassOffset","glassThickness","glassHolderLength","chamfer","legWidth","legDepth","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<=e.topThickness?t="Height must be greated then top thickness.":e.width<=0?t="Width must be greater than 0.":e.width<=2*(e.topGlassOffset+e.glassHolderLength)?t="Width must be greater than two top glass offsets and glass holder lengths.":e.length<=0?t="Length must be greater than 0.":e.length<=2*(e.topGlassOffset+e.glassHolderLength)?t="Length must be greater than two top glass offsets and glass holder lengths.":e.topThickness<=2*e.glassThickness?t="Table top thickness must be greater 2 x glass thickness.":e.glassThickness<=0?t="Glass thickness must be greater than 0":e.glassHolderLengthe.height-e.topThickness-e.shelfThickness?t=`Shelf top offset is larger than ${e.height-e.topThickness-e.shelfThickness}, which make it go underground.`:e.chamfer>=e.topThickness/2?t="Chamfer distance must be lower or equal than half of the top thickness.":e.chamfer>=e.shelfThickness/2?t="Chamfer distance must be lower or equal than half of the shelf thickness.":e.chamfer>=e.topGlassOffset/2?t="Chamfer distance must be lower or equal than half of the top glass offset.":e.chamfer>=e.legWidth/2?t="Chamfer distance must be lower or equal than half of the leg width.":e.chamfer>=e.legDepth/2?t="Chamfer distance must be lower or equal than half of the leg depth.":e.width<=2*e.legWidth?t="Width of the table must be greater or equal to the width of the two legs.":e.length<=2*e.legDepth?t="Length of the table must be greater or equal to the length of the two legs.":e.legDepth>=e.topGlassOffset+e.glassHolderLength?t="The depth of the leg must be lower or equal to the sum of glass offset and glass holder length.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.goodCoffeeTable)throw new Error("Could not compute, to use Good Coffee Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.goodCoffeeTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}snakeChair(t){return function(t,r,i,n){if(function(e){let t;if(["sittingHeight","backRestOffset","backRestHeight","width","length","thickness","ornamentDepth","nrOrnamentPlanks","filletRadius","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.sittingHeight<=2*e.thickness?t="Sitting height must be greater than 2 x thickness.":e.backRestOffset<0?t="Back rest offset can't be negative.":e.backRestHeight<=0?t="Back rest height must be greater than 0":e.width<=0?t="Width must be greater than 0.":e.length<=2*e.thickness?t="Length height must be greater than 2 x thickness.":e.thickness<=0?t="Width must be greater than 0.":e.nrOrnamentPlanks<0?t="Number of ornament planks must be greater than 0":e.filletRadius<=0?t="Fillet radius must be greater than 0.":e.filletRadius>=e.sittingHeight/2?t="Fillet radius must be lower than half of the sitting height.":e.filletRadius>=e.length/2?t="Fillet radius must be lower than half of the length.":e.filletRadius>=e.backRestHeight/2?t="Fillet radius must be lower than half of the back height.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.snakeChair)throw new Error("Could not compute, to use Snake Chair algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.snakeChair}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}snakeTable(t){return function(t,r,i,n){if(function(e){let t;if(["height","width","length","shelfHeight","supportLength","glassThickness","glassOffset","thickness","ornamentDepth","nrOrnamentPlanks","filletRadius","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<=2*e.thickness?t="Sitting height must be greater than 2 x thickness.":e.width<=0?t="Width must be greater than 0.":e.length<=2*e.thickness?t="Length height must be greater than 2 x thickness.":e.thickness<=0?t="Width must be greater than 0.":e.nrOrnamentPlanks<0?t="Number of ornament planks must be greater than 0":e.filletRadius<=0?t="Fillet radius must be greater than 0.":e.filletRadius>=e.height/2?t="Fillet radius must be lower than half of the sitting height.":e.filletRadius>=e.length/2?t="Fillet radius must be lower than half of the length.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.snakeTable)throw new Error("Could not compute, to use Snake Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.snakeTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}phoneNest(t){return function(t,r,i,n){if(!n.phoneNest)throw new Error("Could not compute, to use Phone Nest algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.phoneNest}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}}function oi(e,t,r,i){const n=r.find((t=>t.name===`${e.fontType}-${e.fontVariant}`));if(!n)throw new Error(`Font ${e.fontType}-${e.fontVariant}.ttf does not exist. Current font probably does not have corresponding variant.`);const s=n.font.getPath(e.text,0,0,e.fontSize),o=[];let a=n.font.getPaths(e.text,0,0,e.fontSize,{});const c=n.font.getAdvanceWidth(e.text,e.fontSize),h=s.getBoundingBox();switch(e.originAlignment){case Ne.leftBottom:break;case Ne.leftMiddle:a=n.font.getPaths(e.text,0,(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.leftTop:a=n.font.getPaths(e.text,0,h.y2-h.y1,e.fontSize,{});break;case Ne.centerBottom:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,0,e.fontSize,{});break;case Ne.centerMiddle:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.centerTop:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,h.y2-h.y1,e.fontSize,{});break;case Ne.rightBottom:a=n.font.getPaths(e.text,-(h.x2-h.x1),0,e.fontSize,{});break;case Ne.rightMiddle:a=n.font.getPaths(e.text,-(h.x2-h.x1),(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.rightTop:a=n.font.getPaths(e.text,-(h.x2-h.x1),h.y2-h.y1,e.fontSize,{})}a.forEach((e=>{const r=e.commands,n=[];let s,a,c;for(let e=0;e0?new i.BRepBuilderAPI_MakeFace_22(n[n.length-1],c.Wire()):new i.BRepBuilderAPI_MakeFace_15(c.Wire(),!0),n.push(e.Face()),e.delete(),c.delete()}catch(e){console.error("We could not create faces from this font probably due to self intersections! You should try removing weird characters and pick a more reliable font like 'Roboto'.")}else if("L"===o.type){const e=[-o.x,0,o.y];if(a[0]===e[0]&&a[2]===e[2])continue;const r=t.shapes.edge.line({start:a,end:e});c.Add_1(r),r.delete(),a=e}else if("Q"===o.type){const e=[-o.x1,0,o.y1],r=[-o.x,0,o.y],i=[a,e,r],n=t.shapes.wire.createBezier({points:i,closed:!1});c.Add_2(n),n.delete(),a=r}else if("C"===o.type){const e=[-o.x,0,o.y],r=[a,[-o.x1,0,o.y1],[-o.x2,0,o.y2],e],i=t.shapes.wire.createBezier({points:r,closed:!1});c.Add_2(i),i.delete(),a=e}}if(void 0!==n[n.length-1]){const e=n[n.length-1],r=new U.BasicShapeRepairDto;r.shape=e,r.minTolerance=1e-8,r.maxTolerance=1e-4,r.precision=.001;const i=t.shapeFix.basicShapeRepair(r);e.delete(),o.push(i)}}));const l=new Br;if(l.advanceWidth=c,l.boundingBox={x1:h.x1,y1:h.y1,x2:h.x2,y2:h.y2},e.height>0){const r=o.map((r=>t.operations.extrude({shape:r,direction:[0,e.height,0]})));o.forEach((e=>e.delete()));const i=r.map((r=>{const i=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=t.transforms.alignAndTranslate({shape:i,center:e.origin,direction:e.direction});return i.delete(),n}));i.reverse();const n=t.shapes.solid.getSolidsCentersOfMass({shapes:i});l.characterCenterCoordinates=n;const s=t.shapes.compound.makeCompound({shapes:i});return l.characterParts=i.map(((e,t)=>({id:`character-${t.toString()}`,shapes:{compound:e}}))),ai(l,s)}{const r=o.map((r=>{const i=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=t.transforms.alignAndTranslate({shape:i,center:e.origin,direction:e.direction});return i.delete(),n}));r.reverse(),o.forEach((e=>e.delete()));const i=t.shapes.face.getFacesCentersOfMass({shapes:r});l.characterCenterCoordinates=i;const n=t.shapes.compound.makeCompound({shapes:r});return l.characterParts=r.map(((e,t)=>({id:`character-${t.toString()}`,shapes:{compound:e}}))),ai(l,n)}}function ai(e,t){if(e){const r=[],i=ni.parse(e,r,"text-3d");return{compound:t,shapes:[{id:"1",shape:t},...r],data:Object.assign({compound:"1"},i)}}}String.prototype.codePointAt||(ii=function(e){if(null==this)throw TypeError();var t=String(this),r=t.length,i=e?Number(e):0;if(i!=i&&(i=0),!(i<0||i>=r)){var n,s=t.charCodeAt(i);return s>=55296&&s<=56319&&r>i+1&&(n=t.charCodeAt(i+1))>=56320&&n<=57343?1024*(s-55296)+n-56320+65536:s}},(ri=function(){try{var e={},t=Object.defineProperty,r=t(e,e,e)&&t}catch(e){}return r}())?ri(String.prototype,"codePointAt",{value:ii,configurable:!0,writable:!0}):String.prototype.codePointAt=ii);function ci(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}function hi(e,t){this.source=e,this.sourceIndex=0,this.tag=0,this.bitcount=0,this.dest=t,this.destLen=0,this.ltree=new ci,this.dtree=new ci}var li=new ci,ui=new ci,di=new Uint8Array(30),pi=new Uint16Array(30),fi=new Uint8Array(30),gi=new Uint16Array(30),vi=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),mi=new ci,yi=new Uint8Array(320);function Si(e,t,r,i){var n,s;for(n=0;n>>=1,t}function Ti(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,i+r}function xi(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++n,r+=t.table[n],i-=t.table[n]}while(i>=0);return e.tag=s,e.bitcount-=n,t.trans[r+i]}function ki(e,t,r){var i,n,s,o,a,c;for(i=Ti(e,5,257),n=Ti(e,5,1),s=Ti(e,4,4),o=0;o<19;++o)yi[o]=0;for(o=0;o8;)e.sourceIndex--,e.bitcount-=8;if((t=256*(t=e.source[e.sourceIndex+1])+e.source[e.sourceIndex])!==(65535&~(256*e.source[e.sourceIndex+3]+e.source[e.sourceIndex+2])))return-3;for(e.sourceIndex+=4,r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,0}!function(e,t){var r;for(r=0;r<7;++r)e.table[r]=0;for(e.table[7]=24,e.table[8]=152,e.table[9]=112,r=0;r<24;++r)e.trans[r]=256+r;for(r=0;r<144;++r)e.trans[24+r]=r;for(r=0;r<8;++r)e.trans[168+r]=280+r;for(r=0;r<112;++r)e.trans[176+r]=144+r;for(r=0;r<5;++r)t.table[r]=0;for(t.table[5]=32,r=0;r<32;++r)t.trans[r]=r}(li,ui),Si(di,pi,4,3),Si(fi,gi,2,1),di[28]=0,pi[28]=258;var Ai=function(e,t){var r,i,n=new hi(e,t);do{switch(r=Ei(n),Ti(n,2,0)){case 0:i=Pi(n);break;case 1:i=Ci(n,li,ui);break;case 2:ki(n,n.ltree,n.dtree),i=Ci(n,n.ltree,n.dtree);break;default:i=-3}if(0!==i)throw new Error("Data error")}while(!r);return n.destLenthis.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},Oi.prototype.addX=function(e){this.addPoint(e,null)},Oi.prototype.addY=function(e){this.addPoint(null,e)},Oi.prototype.addBezier=function(e,t,r,i,n,s,o,a){var c=[e,t],h=[r,i],l=[n,s],u=[o,a];this.addPoint(e,t),this.addPoint(o,a);for(var d=0;d<=1;d++){var p=6*c[d]-12*h[d]+6*l[d],f=-3*c[d]+9*h[d]-9*l[d]+3*u[d],g=3*h[d]-3*c[d];if(0!==f){var v=Math.pow(p,2)-4*g*f;if(!(v<0)){var m=(-p+Math.sqrt(v))/(2*f);0=0&&i>0&&(r+=" "),r+=t(n)}return r}e=void 0!==e?e:2;for(var i="",n=0;n"},Di.prototype.toDOMElement=function(e){var t=this.toPathData(e),r=document.createElementNS("http://www.w3.org/2000/svg","path");return r.setAttribute("d",t),r};var Li={fail:Ri,argument:Fi,assert:Fi},Bi=2147483648,Mi={},Ii={},Ui={};function Wi(e){return function(){return e}}Ii.BYTE=function(e){return Li.argument(e>=0&&e<=255,"Byte value should be between 0 and 255."),[e]},Ui.BYTE=Wi(1),Ii.CHAR=function(e){return[e.charCodeAt(0)]},Ui.CHAR=Wi(1),Ii.CHARARRAY=function(e){void 0===e&&(e="",console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."));for(var t=[],r=0;r>8&255,255&e]},Ui.USHORT=Wi(2),Ii.SHORT=function(e){return e>=32768&&(e=-(65536-e)),[e>>8&255,255&e]},Ui.SHORT=Wi(2),Ii.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},Ui.UINT24=Wi(3),Ii.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.ULONG=Wi(4),Ii.LONG=function(e){return e>=Bi&&(e=-(2*Bi-e)),[e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.LONG=Wi(4),Ii.FIXED=Ii.ULONG,Ui.FIXED=Ui.ULONG,Ii.FWORD=Ii.SHORT,Ui.FWORD=Ui.SHORT,Ii.UFWORD=Ii.USHORT,Ui.UFWORD=Ui.USHORT,Ii.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.LONGDATETIME=Wi(8),Ii.TAG=function(e){return Li.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},Ui.TAG=Wi(4),Ii.Card8=Ii.BYTE,Ui.Card8=Ui.BYTE,Ii.Card16=Ii.USHORT,Ui.Card16=Ui.USHORT,Ii.OffSize=Ii.BYTE,Ui.OffSize=Ui.BYTE,Ii.SID=Ii.USHORT,Ui.SID=Ui.USHORT,Ii.NUMBER=function(e){return e>=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?Ii.NUMBER16(e):Ii.NUMBER32(e)},Ui.NUMBER=function(e){return Ii.NUMBER(e).length},Ii.NUMBER16=function(e){return[28,e>>8&255,255&e]},Ui.NUMBER16=Wi(3),Ii.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.NUMBER32=Wi(5),Ii.REAL=function(e){var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t);if(r){var i=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length));t=(Math.round(e*i)/i).toString()}for(var n="",s=0,o=t.length;s>8&255,t[t.length]=255&i}return t},Ui.UTF16=function(e){return 2*e.length};var Ni={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};Mi.MACSTRING=function(e,t,r,i){var n=Ni[i];if(void 0!==n){for(var s="",o=0;o=-128&&e<=127}function zi(e,t,r){for(var i=0,n=e.length;t>8&255,c+256&255)}return s}Ii.MACSTRING=function(e,t){var r=function(e){if(!Gi)for(var t in Gi={},Ni)Gi[t]=new String(t);var r=Gi[e];if(void 0!==r){if(Hi){var i=Hi.get(r);if(void 0!==i)return i}var n=Ni[e];if(void 0!==n){for(var s={},o=0;o=128&&void 0===(s=r[s]))return;i[n]=s}return i}},Ui.MACSTRING=function(e,t){var r=Ii.MACSTRING(e,t);return void 0!==r?r.length:0},Ii.VARDELTAS=function(e){for(var t=0,r=[];t=-128&&i<=127?ji(e,t,r):qi(e,t,r)}return r},Ii.INDEX=function(e){for(var t=1,r=[t],i=[],n=0;n>8,t[u+1]=255&d,t=t.concat(i[l])}return t},Ui.TABLE=function(e){for(var t=0,r=e.fields.length,i=0;i0)return new hn(this.data,this.offset+t).parseStruct(e)},hn.prototype.parsePointer32=function(e){var t=this.parseOffset32();if(t>0)return new hn(this.data,this.offset+t).parseStruct(e)},hn.prototype.parseListOfLists=function(e){for(var t=this.parseOffset16List(),r=t.length,i=this.relativeOffset,n=new Array(r),s=0;s=0;n-=1){var s=un.getUShort(e,t+4+8*n),o=un.getUShort(e,t+4+8*n+2);if(3===s&&(0===o||1===o||10===o)||0===s&&(0===o||1===o||2===o||3===o||4===o)){i=un.getULong(e,t+4+8*n+4);break}}if(-1===i)throw new Error("No valid cmap sub-tables found.");var a=new un.Parser(e,t+i);if(r.format=a.parseUShort(),12===r.format)!function(e,t){var r;t.parseUShort(),e.length=t.parseULong(),e.language=t.parseULong(),e.groupCount=r=t.parseULong(),e.glyphIndexMap={};for(var i=0;i>1,t.skip("uShort",3),e.glyphIndexMap={};for(var o=new un.Parser(r,i+n+14),a=new un.Parser(r,i+n+16+2*s),c=new un.Parser(r,i+n+16+4*s),h=new un.Parser(r,i+n+16+6*s),l=i+n+16+8*s,u=0;u0;t-=1)if(e.get(t).unicode>65535){console.log("Adding CMAP format 12 (needed!)"),r=!1;break}var i=[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:r?1:2},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:r?12:20}];r||(i=i.concat([{name:"cmap12PlatformID",type:"USHORT",value:3},{name:"cmap12EncodingID",type:"USHORT",value:10},{name:"cmap12Offset",type:"ULONG",value:0}])),i=i.concat([{name:"format",type:"USHORT",value:4},{name:"cmap4Length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);var n=new rn.Table("cmap",i);for(n.segments=[],t=0;t>4,s=15&i;if(15===n)break;if(t+=r[n],15===s)break;t+=r[s]}return parseFloat(t)}(e);if(t>=32&&t<=246)return t-139;if(t>=247&&t<=250)return 256*(t-247)+e.parseByte()+108;if(t>=251&&t<=254)return 256*-(t-251)-e.parseByte()-108;throw new Error("Invalid b0 "+t)}function Dn(e,t,r){t=void 0!==t?t:0;var i=new un.Parser(e,t),n=[],s=[];for(r=void 0!==r?r:e.length;i.relativeOffset>1,d.length=0,f=!0}return function r(h){for(var y,S,T,x,k,C,P,A,_,O,D,R,F=0;F1&&!f&&(b=d.shift()+l,f=!0),m+=d.pop(),w(v,m);break;case 5:for(;d.length>0;)v+=d.shift(),m+=d.shift(),u.lineTo(v,m);break;case 6:for(;d.length>0&&(v+=d.shift(),u.lineTo(v,m),0!==d.length);)m+=d.shift(),u.lineTo(v,m);break;case 7:for(;d.length>0&&(m+=d.shift(),u.lineTo(v,m),0!==d.length);)v+=d.shift(),u.lineTo(v,m);break;case 8:for(;d.length>0;)i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 10:k=d.pop()+c,(C=a[k])&&r(C);break;case 11:return;case 12:switch(L=h[F],F+=1,L){case 35:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),P=s+d.shift(),A=o+d.shift(),_=P+d.shift(),O=A+d.shift(),D=_+d.shift(),R=O+d.shift(),v=D+d.shift(),m=R+d.shift(),d.shift(),u.curveTo(i,n,s,o,P,A),u.curveTo(_,O,D,R,v,m);break;case 34:i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),P=s+d.shift(),A=o,_=P+d.shift(),O=o,D=_+d.shift(),R=m,v=D+d.shift(),u.curveTo(i,n,s,o,P,A),u.curveTo(_,O,D,R,v,m);break;case 36:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),P=s+d.shift(),A=o,_=P+d.shift(),O=o,D=_+d.shift(),R=O+d.shift(),v=D+d.shift(),u.curveTo(i,n,s,o,P,A),u.curveTo(_,O,D,R,v,m);break;case 37:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),P=s+d.shift(),A=o+d.shift(),_=P+d.shift(),O=A+d.shift(),D=_+d.shift(),R=O+d.shift(),Math.abs(D-v)>Math.abs(R-m)?v=D+d.shift():m=R+d.shift(),u.curveTo(i,n,s,o,P,A),u.curveTo(_,O,D,R,v,m);break;default:console.log("Glyph "+t.index+": unknown operator 1200"+L),d.length=0}break;case 14:d.length>0&&!f&&(b=d.shift()+l,f=!0),g&&(u.closePath(),g=!1);break;case 19:case 20:E(),F+=p+7>>3;break;case 21:d.length>2&&!f&&(b=d.shift()+l,f=!0),m+=d.pop(),w(v+=d.pop(),m);break;case 22:d.length>1&&!f&&(b=d.shift()+l,f=!0),w(v+=d.pop(),m);break;case 24:for(;d.length>2;)i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);v+=d.shift(),m+=d.shift(),u.lineTo(v,m);break;case 25:for(;d.length>6;)v+=d.shift(),m+=d.shift(),u.lineTo(v,m);i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 26:for(d.length%2&&(v+=d.shift());d.length>0;)i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s,m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 27:for(d.length%2&&(m+=d.shift());d.length>0;)i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o,u.curveTo(i,n,s,o,v,m);break;case 28:y=h[F],S=h[F+1],d.push((y<<24|S<<16)>>16),F+=2;break;case 29:k=d.pop()+e.gsubrsBias,(C=e.gsubrs[k])&&r(C);break;case 30:for(;d.length>0&&(i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m),0!==d.length);)i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),m=o+d.shift(),v=s+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m);break;case 31:for(;d.length>0&&(i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),m=o+d.shift(),v=s+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m),0!==d.length);)i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m);break;default:L<32?console.log("Glyph "+t.index+": unknown operator "+L):L<247?d.push(L-139):L<251?(y=h[F],F+=1,d.push(256*(L-247)+y+108)):L<255?(y=h[F],F+=1,d.push(256*-(L-251)-y-108)):(y=h[F],S=h[F+1],T=h[F+2],x=h[F+3],F+=4,d.push((y<<24|S<<16|T<<8|x)/65536))}}}(r),t.advanceWidth=b,u}function Nn(e,t){var r,i=fn.indexOf(e);return i>=0&&(r=i),(i=t.indexOf(e))>=0?r=i+fn.length:(r=fn.length+t.length,t.push(e)),r}function Gn(e,t,r){for(var i={},n=0;n=i)throw new Error("CFF table CID Font FDSelect has bad FD index value "+n+" (FD count "+i+")");s.push(n)}else{if(3!==a)throw new Error("CFF Table CID Font FDSelect table has unsupported format "+a);var h,l=o.parseCard16(),u=o.parseCard16();if(0!==u)throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+u);for(var d=0;d=i)throw new Error("CFF table CID Font FDSelect has bad FD index value "+n+" (FD count "+i+")");if(h>r)throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+h);for(;u=1&&(r.ulCodePageRange1=i.parseULong(),r.ulCodePageRange2=i.parseULong()),r.version>=2&&(r.sxHeight=i.parseShort(),r.sCapHeight=i.parseShort(),r.usDefaultChar=i.parseUShort(),r.usBreakChar=i.parseUShort(),r.usMaxContent=i.parseUShort()),r},make:function(e){return new rn.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],e)},unicodeRanges:ls,getUnicodeRange:function(e){for(var t=0;t=r.begin&&e=mn.length){var o=i.parseChar();r.names.push(i.parseString(o))}break;case 2.5:r.numberOfGlyphs=i.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var a=0;at.value.tag?1:-1})),t.fields=t.fields.concat(i),t.fields=t.fields.concat(n),t}function Es(e,t,r){for(var i=0;i0)return e.glyphs.get(n).getMetrics()}return r}function Ts(e){for(var t=0,r=0;rv||void 0===t)&&v>0&&(t=v),h 123 are reserved for internal usage");p|=1<0?Xn.make(R):void 0,B=ds.make(),M=jn.make(e.glyphs,{version:e.getEnglishName("version"),fullName:A,familyName:C,weightName:P,postScriptName:_,unitsPerEm:e.unitsPerEm,fontBBox:[0,S.yMin,S.ascender,S.advanceWidthMax]}),I=e.metas&&Object.keys(e.metas).length>0?ms.make(e.metas):void 0,U=[b,w,E,T,F,k,B,M,x];L&&U.push(L),e.tables.gsub&&U.push(vs.make(e.tables.gsub)),I&&U.push(I);for(var W=ws(U),N=Ss(W.encode()),G=W.fields,H=!1,V=0;V>>1,s=e[n].tag;if(s===t)return n;s>>1,s=e[n];if(s===t)return n;s>>1,o=(r=e[s]).start;if(o===t)return r;o0)return t>(r=e[i-1]).end?0:r}function As(e,t){this.font=e,this.tableName=t}function _s(e){As.call(this,e,"gpos")}function Os(e){As.call(this,e,"gsub")}function Ds(e,t){var r=e.length;if(r!==t.length)return!1;for(var i=0;i0?(s=e.parseByte(),t&n||(s=-s),s=r+s):s=(t&n)>0?r:r+e.parseShort(),s}function Bs(e,t,r){var i,n,s=new un.Parser(t,r);if(e.numberOfContours=s.parseShort(),e._xMin=s.parseShort(),e._yMin=s.parseShort(),e._xMax=s.parseShort(),e._yMax=s.parseShort(),e.numberOfContours>0){for(var o=e.endPointIndices=[],a=0;a0)for(var u=s.parseByte(),d=0;d0){var p,f=[];if(h>0){for(var g=0;g=0,f.push(p);for(var v=0,m=0;m0?(2&i)>0?(w.dx=s.parseShort(),w.dy=s.parseShort()):w.matchedPoints=[s.parseUShort(),s.parseUShort()]:(2&i)>0?(w.dx=s.parseChar(),w.dy=s.parseChar()):w.matchedPoints=[s.parseByte(),s.parseByte()],(8&i)>0?w.xScale=w.yScale=s.parseF2Dot14():(64&i)>0?(w.xScale=s.parseF2Dot14(),w.yScale=s.parseF2Dot14()):(128&i)>0&&(w.xScale=s.parseF2Dot14(),w.scale01=s.parseF2Dot14(),w.scale10=s.parseF2Dot14(),w.yScale=s.parseF2Dot14()),e.components.push(w),b=!!(32&i)}if(256&i){e.instructionLength=s.parseUShort(),e.instructions=[];for(var E=0;Et.points.length-1||i.matchedPoints[1]>n.points.length-1)throw Error("Matched points out of range in "+t.name);var o=t.points[i.matchedPoints[0]],a=n.points[i.matchedPoints[1]],c={xScale:i.xScale,scale01:i.scale01,scale10:i.scale10,yScale:i.yScale,dx:0,dy:0};a=Ms([a],c)[0],c.dx=o.x-a.x,c.dy=o.y-a.y,s=Ms(n.points,c)}t.points=t.points.concat(s)}}return Is(t.points)}As.prototype={searchTag:ks,binSearch:Cs,getTable:function(e){var t=this.font.tables[this.tableName];return!t&&e&&(t=this.font.tables[this.tableName]=this.createDefaultTable()),t},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map((function(e){return e.tag})):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var t=!1,r=0;r=0)return i[n].script;if(t){var s={tag:e,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};return i.splice(-1-n,0,s),s.script}}},getLangSysTable:function(e,t,r){var i=this.getScriptTable(e,r);if(i){if(!t||"dflt"===t||"DFLT"===t)return i.defaultLangSys;var n=ks(i.langSysRecords,t);if(n>=0)return i.langSysRecords[n].langSys;if(r){var s={tag:t,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};return i.langSysRecords.splice(-1-n,0,s),s.langSys}}},getFeatureTable:function(e,t,r,i){var n=this.getLangSysTable(e,t,i);if(n){for(var s,o=n.featureIndexes,a=this.font.tables[this.tableName].features,c=0;c=a[h-1].tag,"Features must be added in alphabetical order."),s={tag:r,feature:{params:0,lookupListIndexes:[]}},a.push(s),o.push(h),s.feature}}},getLookupTables:function(e,t,r,i,n){var s=this.getFeatureTable(e,t,r,n),o=[];if(s){for(var a,c=s.lookupListIndexes,h=this.font.tables[this.tableName].lookups,l=0;l=0?r:-1;case 2:var i=Ps(e.ranges,t);return i?i.index+t-i.start:-1}},expandCoverage:function(e){if(1===e.format)return e.glyphs;for(var t=[],r=e.ranges,i=0;i1,'Multiple: "by" must be an array of two or more ids');var n=Rs(this.getLookupTables(r,i,e,2,!0)[0],1,{substFormat:1,coverage:{format:1,glyphs:[]},sequences:[]});Li.assert(1===n.coverage.format,"Multiple: unable to modify coverage table format "+n.coverage.format);var s=t.sub,o=this.binSearch(n.coverage.glyphs,s);o<0&&(o=-1-o,n.coverage.glyphs.splice(o,0,s),n.sequences.splice(o,0,0)),n.sequences[o]=t.by},Os.prototype.addAlternate=function(e,t,r,i){var n=Rs(this.getLookupTables(r,i,e,3,!0)[0],1,{substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});Li.assert(1===n.coverage.format,"Alternate: unable to modify coverage table format "+n.coverage.format);var s=t.sub,o=this.binSearch(n.coverage.glyphs,s);o<0&&(o=-1-o,n.coverage.glyphs.splice(o,0,s),n.alternateSets.splice(o,0,0)),n.alternateSets[o]=t.by},Os.prototype.addLigature=function(e,t,r,i){var n=this.getLookupTables(r,i,e,4,!0)[0],s=n.subtables[0];s||(s={substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]},n.subtables[0]=s),Li.assert(1===s.coverage.format,"Ligature: unable to modify coverage table format "+s.coverage.format);var o=t.sub[0],a=t.sub.slice(1),c={ligGlyph:t.by,components:a},h=this.binSearch(s.coverage.glyphs,o);if(h>=0){for(var l=s.ligatureSets[h],u=0;u=176&&r<=183)n+=r-176+1;else if(r>=184&&r<=191)n+=2*(r-184+1);else if(t&&1===s&&27===r)break}while(s>0);e.ip=n}function co(e,t){exports.DEBUG&&console.log(t.step,"SVTCA["+e.axis+"]"),t.fv=t.pv=t.dpv=e}function ho(e,t){exports.DEBUG&&console.log(t.step,"SPVTCA["+e.axis+"]"),t.pv=t.dpv=e}function lo(e,t){exports.DEBUG&&console.log(t.step,"SFVTCA["+e.axis+"]"),t.fv=e}function uo(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log("SPVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.pv=t.dpv=to(r,i)}function po(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log("SFVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.fv=to(r,i)}function fo(e){exports.DEBUG&&console.log(e.step,"POP[]"),e.stack.pop()}function go(e,t){var r=t.stack.pop(),i=t.z0[r],n=t.fv,s=t.pv;exports.DEBUG&&console.log(t.step,"MDAP["+e+"]",r);var o=s.distance(i,io);e&&(o=t.round(o)),n.setRelative(i,io,o,s),n.touch(i),t.rp0=t.rp1=r}function vo(e,t){var r,i,n,s=t.z2,o=s.length-2;exports.DEBUG&&console.log(t.step,"IUP["+e.axis+"]");for(var a=0;a1?"loop "+(t.loop-a)+": ":"")+"SHP["+(e?"rp1":"rp2")+"]",h)}t.loop=1}function yo(e,t){var r=t.stack,i=e?t.rp1:t.rp2,n=(e?t.z0:t.z1)[i],s=t.fv,o=t.pv,a=r.pop(),c=t.z2[t.contours[a]],h=c;exports.DEBUG&&console.log(t.step,"SHC["+e+"]",a);var l=o.distance(n,n,!1,!0);do{h!==n&&s.setRelative(h,h,l,o),h=h.nextPointOnContour}while(h!==c)}function So(e,t){var r,i,n=t.stack,s=e?t.rp1:t.rp2,o=(e?t.z0:t.z1)[s],a=t.fv,c=t.pv,h=n.pop();switch(exports.DEBUG&&console.log(t.step,"SHZ["+e+"]",h),h){case 0:r=t.tZone;break;case 1:r=t.gZone;break;default:throw new Error("Invalid zone")}for(var l=c.distance(o,o,!1,!0),u=r.length-2,d=0;d",a),t.stack.push(Math.round(64*a))}function xo(e,t){var r=t.stack,i=r.pop(),n=t.fv,s=t.pv,o=t.ppem,a=t.deltaBase+16*(e-1),c=t.deltaShift,h=t.z0;exports.DEBUG&&console.log(t.step,"DELTAP["+e+"]",i,r);for(var l=0;l>4)===o){var p=(15&d)-8;p>=0&&p++,exports.DEBUG&&console.log(t.step,"DELTAPFIX",u,"by",p*c);var f=h[u];n.setRelative(f,f,p*c,s)}}}function ko(e,t){var r=t.stack,i=r.pop();exports.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(i/64))}function Co(e,t){var r=t.stack,i=r.pop(),n=t.ppem,s=t.deltaBase+16*(e-1),o=t.deltaShift;exports.DEBUG&&console.log(t.step,"DELTAC["+e+"]",i,r);for(var a=0;a>4)===n){var l=(15&h)-8;l>=0&&l++;var u=l*o;exports.DEBUG&&console.log(t.step,"DELTACFIX",c,"by",u),t.cvt[c]+=u}}}function Po(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.dpv=to(r,i)}function Ao(e,t){var r=t.stack,i=t.prog,n=t.ip;exports.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var s=0;s=0?1:-1,a=Math.abs(a),e&&(h=s.cvt[u],i&&Math.abs(a-h)":"_")+(i?"R":"_")+(0===n?"Gr":1===n?"Bl":2===n?"Wh":"")+"]",e?u+"("+s.cvt[u]+","+h+")":"",d,"(d =",o,"->",c*a,")"),s.rp1=s.rp0,s.rp2=d,t&&(s.rp0=d)}function Do(e){this.char=e,this.state={},this.activeState=null}function Ro(e,t,r){this.contextName=r,this.startIndex=e,this.endOffset=t}function Fo(e,t,r){this.contextName=e,this.openRange=null,this.ranges=[],this.checkStart=t,this.checkEnd=r}function Lo(e,t){this.context=e,this.index=t,this.length=e.length,this.current=e[t],this.backtrack=e.slice(0,t),this.lookahead=e.slice(t+1)}function Bo(e){this.eventId=e,this.subscribers=[]}function Mo(e){var t=this,r=["start","end","next","newToken","contextStart","contextEnd","insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD","updateContextsRanges"];r.forEach((function(e){Object.defineProperty(t.events,e,{value:new Bo(e)})})),e&&r.forEach((function(r){var i=e[r];"function"==typeof i&&t.events[r].subscribe(i)})),["insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD"].forEach((function(e){t.events[e].subscribe(t.updateContextsRanges)}))}function Io(e){this.tokens=[],this.registeredContexts={},this.contextCheckers=[],this.events={},this.registeredModifiers=[],Mo.call(this,e)}function Uo(e){return/[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(e)}function Wo(e){return/[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(e)}function No(e){return/[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(e)}function Go(e){return/[A-z]/.test(e)}function Ho(e){this.font=e,this.features={}}function Vo(e){this.id=e.id,this.tag=e.tag,this.substitution=e.substitution}function zo(e,t){if(!e)return-1;switch(t.format){case 1:return t.glyphs.indexOf(e);case 2:for(var r=t.ranges,i=0;i=n.start&&e<=n.end){var s=e-n.start;return n.index+s}}break;default:return-1}return-1}function jo(e,t){return-1===zo(e,t.coverage)?null:e+t.deltaGlyphId}function qo(e,t){var r=zo(e,t.coverage);return-1===r?null:t.substitute[r]}function $o(e,t){for(var r=[],i=0;i2)){var r=this.font,i=this._prepState;if(!i||i.ppem!==t){var n=this._fpgmState;if(!n){so.prototype=no,(n=this._fpgmState=new so("fpgm",r.tables.fpgm)).funcs=[],n.font=r,exports.DEBUG&&(console.log("---EXEC FPGM---"),n.step=-1);try{Ns(n)}catch(e){return console.log("Hinting error in FPGM:"+e),void(this._errorState=3)}}so.prototype=n,(i=this._prepState=new so("prep",r.tables.prep)).ppem=t;var s=r.tables.cvt;if(s)for(var o=i.cvt=new Array(s.length),a=t/r.unitsPerEm,c=0;c1))try{return Gs(e,i)}catch(e){return this._errorState<1&&(console.log("Hinting error:"+e),console.log("Note: further hinting errors are silenced")),void(this._errorState=1)}}},Gs=function(e,t){var r,i,n,s=t.ppem/t.font.unitsPerEm,o=s,a=e.components;if(so.prototype=t,a){var c=t.font;i=[],r=[];for(var h=0;h1?"loop "+(e.loop-r)+": ":"")+"SHPIX[]",o,n),i.setRelative(a,a,n),i.touch(a)}e.loop=1},function(e){for(var t=e.stack,r=e.rp1,i=e.rp2,n=e.loop,s=e.z0[r],o=e.z1[i],a=e.fv,c=e.dpv,h=e.z2;n--;){var l=t.pop(),u=h[l];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-n)+": ":"")+"IP[]",l,r,"<->",i),a.interpolate(u,s,o,c),a.touch(u)}e.loop=1},bo.bind(void 0,0),bo.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,i=e.z0[r],n=e.loop,s=e.fv,o=e.pv,a=e.z1;n--;){var c=t.pop(),h=a[c];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-n)+": ":"")+"ALIGNRP[]",c),s.setRelative(h,i,0,o),s.touch(h)}e.loop=1},function(e){exports.DEBUG&&console.log(e.step,"RTDG[]"),e.round=$s},wo.bind(void 0,0),wo.bind(void 0,1),function(e){var t=e.prog,r=e.ip,i=e.stack,n=t[++r];exports.DEBUG&&console.log(e.step,"NPUSHB[]",n);for(var s=0;sr?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"GTEQ[]",r,i),t.push(i>=r?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"EQ[]",r,i),t.push(r===i?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"NEQ[]",r,i),t.push(r!==i?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"ODD[]",r),t.push(Math.trunc(r)%2?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"EVEN[]",r),t.push(Math.trunc(r)%2?0:1)},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"IF[]",t),t||(ao(e,!0),exports.DEBUG&&console.log(e.step,"EIF[]"))},function(e){exports.DEBUG&&console.log(e.step,"EIF[]")},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"AND[]",r,i),t.push(r&&i?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"OR[]",r,i),t.push(r||i?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"NOT[]",r),t.push(r?0:1)},xo.bind(void 0,1),function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SDB[]",t),e.deltaBase=t},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SDS[]",t),e.deltaShift=Math.pow(.5,t)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"ADD[]",r,i),t.push(i+r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"SUB[]",r,i),t.push(i-r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"DIV[]",r,i),t.push(64*i/r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MUL[]",r,i),t.push(i*r/64)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"ABS[]",r),t.push(Math.abs(r))},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"NEG[]",r),t.push(-r)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"FLOOR[]",r),t.push(64*Math.floor(r/64))},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"CEILING[]",r),t.push(64*Math.ceil(r/64))},ko.bind(void 0,0),ko.bind(void 0,1),ko.bind(void 0,2),ko.bind(void 0,3),void 0,void 0,void 0,void 0,function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"WCVTF[]",r,i),e.cvt[i]=r*e.ppem/e.font.unitsPerEm},xo.bind(void 0,2),xo.bind(void 0,3),Co.bind(void 0,1),Co.bind(void 0,2),Co.bind(void 0,3),function(e){var t,r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"SROUND[]",r),e.round=Js,192&r){case 0:t=.5;break;case 64:t=1;break;case 128:t=2;break;default:throw new Error("invalid SROUND value")}switch(e.srPeriod=t,48&r){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*t;break;case 32:e.srPhase=.5*t;break;case 48:e.srPhase=.75*t;break;default:throw new Error("invalid SROUND value")}r&=15,e.srThreshold=0===r?0:(r/8-.5)*t},function(e){var t,r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"S45ROUND[]",r),e.round=Js,192&r){case 0:t=Math.sqrt(2)/2;break;case 64:t=Math.sqrt(2);break;case 128:t=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}switch(e.srPeriod=t,48&r){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*t;break;case 32:e.srPhase=.5*t;break;case 48:e.srPhase=.75*t;break;default:throw new Error("invalid S45ROUND value")}r&=15,e.srThreshold=0===r?0:(r/8-.5)*t},void 0,void 0,function(e){exports.DEBUG&&console.log(e.step,"ROFF[]"),e.round=js},void 0,function(e){exports.DEBUG&&console.log(e.step,"RUTG[]"),e.round=Xs},function(e){exports.DEBUG&&console.log(e.step,"RDTG[]"),e.round=Zs},fo,fo,void 0,void 0,void 0,void 0,void 0,function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANCTRL[]",t)},Po.bind(void 0,0),Po.bind(void 0,1),function(e){var t=e.stack,r=t.pop(),i=0;exports.DEBUG&&console.log(e.step,"GETINFO[]",r),1&r&&(i=35),32&r&&(i|=4096),t.push(i)},void 0,function(e){var t=e.stack,r=t.pop(),i=t.pop(),n=t.pop();exports.DEBUG&&console.log(e.step,"ROLL[]"),t.push(i),t.push(r),t.push(n)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MAX[]",r,i),t.push(Math.max(i,r))},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MIN[]",r,i),t.push(Math.min(i,r))},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANTYPE[]",t)},function(e){var t=e.stack.pop(),r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"INSTCTRL[]",t,r),t){case 1:return void(e.inhibitGridFit=!!r);case 2:return void(e.ignoreCvt=!!r);default:throw new Error("invalid INSTCTRL[] selector")}},void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,Ao.bind(void 0,1),Ao.bind(void 0,2),Ao.bind(void 0,3),Ao.bind(void 0,4),Ao.bind(void 0,5),Ao.bind(void 0,6),Ao.bind(void 0,7),Ao.bind(void 0,8),_o.bind(void 0,1),_o.bind(void 0,2),_o.bind(void 0,3),_o.bind(void 0,4),_o.bind(void 0,5),_o.bind(void 0,6),_o.bind(void 0,7),_o.bind(void 0,8),Oo.bind(void 0,0,0,0,0,0),Oo.bind(void 0,0,0,0,0,1),Oo.bind(void 0,0,0,0,0,2),Oo.bind(void 0,0,0,0,0,3),Oo.bind(void 0,0,0,0,1,0),Oo.bind(void 0,0,0,0,1,1),Oo.bind(void 0,0,0,0,1,2),Oo.bind(void 0,0,0,0,1,3),Oo.bind(void 0,0,0,1,0,0),Oo.bind(void 0,0,0,1,0,1),Oo.bind(void 0,0,0,1,0,2),Oo.bind(void 0,0,0,1,0,3),Oo.bind(void 0,0,0,1,1,0),Oo.bind(void 0,0,0,1,1,1),Oo.bind(void 0,0,0,1,1,2),Oo.bind(void 0,0,0,1,1,3),Oo.bind(void 0,0,1,0,0,0),Oo.bind(void 0,0,1,0,0,1),Oo.bind(void 0,0,1,0,0,2),Oo.bind(void 0,0,1,0,0,3),Oo.bind(void 0,0,1,0,1,0),Oo.bind(void 0,0,1,0,1,1),Oo.bind(void 0,0,1,0,1,2),Oo.bind(void 0,0,1,0,1,3),Oo.bind(void 0,0,1,1,0,0),Oo.bind(void 0,0,1,1,0,1),Oo.bind(void 0,0,1,1,0,2),Oo.bind(void 0,0,1,1,0,3),Oo.bind(void 0,0,1,1,1,0),Oo.bind(void 0,0,1,1,1,1),Oo.bind(void 0,0,1,1,1,2),Oo.bind(void 0,0,1,1,1,3),Oo.bind(void 0,1,0,0,0,0),Oo.bind(void 0,1,0,0,0,1),Oo.bind(void 0,1,0,0,0,2),Oo.bind(void 0,1,0,0,0,3),Oo.bind(void 0,1,0,0,1,0),Oo.bind(void 0,1,0,0,1,1),Oo.bind(void 0,1,0,0,1,2),Oo.bind(void 0,1,0,0,1,3),Oo.bind(void 0,1,0,1,0,0),Oo.bind(void 0,1,0,1,0,1),Oo.bind(void 0,1,0,1,0,2),Oo.bind(void 0,1,0,1,0,3),Oo.bind(void 0,1,0,1,1,0),Oo.bind(void 0,1,0,1,1,1),Oo.bind(void 0,1,0,1,1,2),Oo.bind(void 0,1,0,1,1,3),Oo.bind(void 0,1,1,0,0,0),Oo.bind(void 0,1,1,0,0,1),Oo.bind(void 0,1,1,0,0,2),Oo.bind(void 0,1,1,0,0,3),Oo.bind(void 0,1,1,0,1,0),Oo.bind(void 0,1,1,0,1,1),Oo.bind(void 0,1,1,0,1,2),Oo.bind(void 0,1,1,0,1,3),Oo.bind(void 0,1,1,1,0,0),Oo.bind(void 0,1,1,1,0,1),Oo.bind(void 0,1,1,1,0,2),Oo.bind(void 0,1,1,1,0,3),Oo.bind(void 0,1,1,1,1,0),Oo.bind(void 0,1,1,1,1,1),Oo.bind(void 0,1,1,1,1,2),Oo.bind(void 0,1,1,1,1,3)],Do.prototype.setState=function(e,t){return this.state[e]=t,this.activeState={key:e,value:this.state[e]},this.activeState},Do.prototype.getState=function(e){return this.state[e]||null},Io.prototype.inboundIndex=function(e){return e>=0&&e0&&e<=this.lookahead.length:return this.lookahead[e-1];default:return null}},Io.prototype.rangeToText=function(e){if(e instanceof Ro)return this.getRangeTokens(e).map((function(e){return e.char})).join("")},Io.prototype.getText=function(){return this.tokens.map((function(e){return e.char})).join("")},Io.prototype.getContext=function(e){return this.registeredContexts[e]||null},Io.prototype.on=function(e,t){var r=this.events[e];return r?r.subscribe(t):null},Io.prototype.dispatch=function(e,t){var r=this,i=this.events[e];i instanceof Bo&&i.subscribers.forEach((function(e){e.apply(r,t||[])}))},Io.prototype.registerContextChecker=function(e,t,r){if(this.getContext(e))return{FAIL:"context name '"+e+"' is already registered."};if("function"!=typeof t)return{FAIL:"missing context start check."};if("function"!=typeof r)return{FAIL:"missing context end check."};var i=new Fo(e,t,r);return this.registeredContexts[e]=i,this.contextCheckers.push(i),i},Io.prototype.getRangeTokens=function(e){var t=e.startIndex+e.endOffset;return[].concat(this.tokens.slice(e.startIndex,t))},Io.prototype.getContextRanges=function(e){var t=this.getContext(e);return t?t.ranges:{FAIL:"context checker '"+e+"' is not registered."}},Io.prototype.resetContextsRanges=function(){var e=this.registeredContexts;for(var t in e)e.hasOwnProperty(t)&&(e[t].ranges=[])},Io.prototype.updateContextsRanges=function(){this.resetContextsRanges();for(var e=this.tokens.map((function(e){return e.char})),t=0;t=0;r--){var i=t[r],n=Wo(i),s=No(i);if(!n&&!s)return!0;if(n)return!1}return!1}(o)&&(h|=1),function(e){if(Wo(e.current))return!1;for(var t=0;t=1.2&&(n.markGlyphSets=r.parsePointer(Ca)),n}},Aa=new Array(10);Aa[1]=function(){var e=this.offset+this.relativeOffset,t=this.parseUShort();return 1===t?{posFormat:1,coverage:this.parsePointer(hn.coverage),value:this.parseValueRecord()}:2===t?{posFormat:2,coverage:this.parsePointer(hn.coverage),values:this.parseValueRecordList()}:void Li.assert(!1,"0x"+e.toString(16)+": GPOS lookup type 1 format must be 1 or 2.")},Aa[2]=function(){var e=this.offset+this.relativeOffset,t=this.parseUShort();Li.assert(1===t||2===t,"0x"+e.toString(16)+": GPOS lookup type 2 format must be 1 or 2.");var r=this.parsePointer(hn.coverage),i=this.parseUShort(),n=this.parseUShort();if(1===t)return{posFormat:t,coverage:r,valueFormat1:i,valueFormat2:n,pairSets:this.parseList(hn.pointer(hn.list((function(){return{secondGlyph:this.parseUShort(),value1:this.parseValueRecord(i),value2:this.parseValueRecord(n)}}))))};if(2===t){var s=this.parsePointer(hn.classDef),o=this.parsePointer(hn.classDef),a=this.parseUShort(),c=this.parseUShort();return{posFormat:t,coverage:r,valueFormat1:i,valueFormat2:n,classDef1:s,classDef2:o,class1Count:a,class2Count:c,classRecords:this.parseList(a,hn.list(c,(function(){return{value1:this.parseValueRecord(i),value2:this.parseValueRecord(n)}})))}}},Aa[3]=function(){return{error:"GPOS Lookup 3 not supported"}},Aa[4]=function(){return{error:"GPOS Lookup 4 not supported"}},Aa[5]=function(){return{error:"GPOS Lookup 5 not supported"}},Aa[6]=function(){return{error:"GPOS Lookup 6 not supported"}},Aa[7]=function(){return{error:"GPOS Lookup 7 not supported"}},Aa[8]=function(){return{error:"GPOS Lookup 8 not supported"}},Aa[9]=function(){return{error:"GPOS Lookup 9 not supported"}};var _a=new Array(10),Oa={parse:function(e,t){var r=new hn(e,t=t||0),i=r.parseVersion(1);return Li.argument(1===i||1.1===i,"Unsupported GPOS table version "+i),1===i?{version:i,scripts:r.parseScriptList(),features:r.parseFeatureList(),lookups:r.parseLookupList(Aa)}:{version:i,scripts:r.parseScriptList(),features:r.parseFeatureList(),lookups:r.parseLookupList(Aa),variations:r.parseFeatureVariationsList()}},make:function(e){return new rn.Table("GPOS",[{name:"version",type:"ULONG",value:65536},{name:"scripts",type:"TABLE",value:new rn.ScriptList(e.scripts)},{name:"features",type:"TABLE",value:new rn.FeatureList(e.features)},{name:"lookups",type:"TABLE",value:new rn.LookupList(e.lookups,_a)}])}},Da={parse:function(e,t){var r=new un.Parser(e,t),i=r.parseUShort();if(0===i)return function(e){var t={};e.skip("uShort");var r=e.parseUShort();Li.argument(0===r,"Unsupported kern sub-table version."),e.skip("uShort",2);var i=e.parseUShort();e.skip("uShort",3);for(var n=0;n1&&console.warn("Only the first kern subtable is supported."),e.skip("uLong");var r=255&e.parseUShort();if(e.skip("uShort"),0===r){var i=e.parseUShort();e.skip("uShort",3);for(var n=0;n{try{const r=e?Rr.filter((t=>e.includes(t.key))):Rr,i=r.reduce(((e,t)=>e+t.variants.length),0);let n=0;r.forEach((e=>{e.variants.forEach((r=>{const s=e.key,o=`${s}-${r}`;!function(e,t,r){r=null==r?{}:r;var i="undefined"!=typeof window||r.isUrl?La:Fa;new Promise((function(n,s){i(e,(function(e,i){if(e){if(t)return t(e);s(e)}var o;try{o=Ia(i,r)}catch(e){if(t)return t(e,null);s(e)}if(t)return t(null,o);n(o)}))}))}(`https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.9/fonts/${s}/${o}.ttf`,((e,a)=>{e||(this.fonts.push({name:o,type:s,variant:r,font:a}),n++,n===i&&t({}))}),{isUrl:!0})}))}))}catch(e){r(e)}}))},new((i=void 0)||(i=Promise))((function(e,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,a)}c((n=n.apply(t,r||[])).next())}));var t,r,i,n}text3d(e){return oi(e,this.occtService,this.fonts,this.occ)}text3dFace(t){return function(t,r,i,n,s,o){if(!o.text3dFace)throw new Error("Could not compute, to use Text 3D Face algorithm you must be subscribed to our silver or gold plan.");try{const a=`\n ${o.text3dFace}\n `,c=new Function(a),h={name:"text3dFace"};return c.apply({inputs:t,occt:r,fonts:i,occ:n,vectorHelper:s,Inputs:e,Advanced:G,ShapeParser:ni,text3d:oi,method:h})}catch(e){throw new Error(e)}}(t,this.occtService,this.fonts,this.occ,this.vectorHelper,this.dependencies)}texts3dFace(t){return function(t,r,i,n,s,o){if(!o.text3dFace)throw new Error("Could not compute, to use Texts 3D Face algorithm you must be subscribed to our silver or gold plan.");try{const a=`\n ${o.text3dFace}\n `,c=new Function(a),h={name:"texts3dFace"};return c.apply({inputs:t,occt:r,fonts:i,occ:n,vectorHelper:s,Inputs:e,Advanced:G,ShapeParser:ni,text3d:oi,method:h})}catch(e){throw new Error(e)}}(t,this.occtService,this.fonts,this.occ,this.vectorHelper,this.dependencies)}pyramidSimple(t){return function(t,r,i,n,s){if(function(e){let t;if(["uNumber","vNumber","height","precision"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.uNumber<=0?t="U number mus be greater than 0.":e.vNumber<=0?t="V number must be greater than 0.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!s.patternsFacePatternPyramidSimple)throw new Error("Could not compute, to use Pyramid Simple algorithm you must be subscribed to our silver or gold plan.");try{const o=`\n ${s.patternsFacePatternPyramidSimple}\n `,a=new Function(o),c={name:"pyramidSimple"};return a.apply({inputs:t,occt:r,occ:i,vectorHelper:n,Inputs:e,Advanced:G,ShapeParser:ni,method:c})}catch(e){throw new Error(e)}}(t,this.occtService,this.occ,this.vectorHelper,this.dependencies)}pyramidSimpleAffectors(t){return function(t,r,i,n,s){if(function(e){let t;if(["uNumber","vNumber","defaultHeight","affectMinHeight","affectMaxHeight","precision"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.uNumber<=0?t="U number mus be greater than 0.":e.vNumber<=0?t="V number must be greater than 0.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!s.patternsFacePatternPyramidSimple)throw new Error("Could not compute, to use Pyramid Simple Affectors algorithm you must be subscribed to our silver or gold plan.");try{const o=`\n ${s.patternsFacePatternPyramidSimple}\n `,a=new Function(o),c={name:"pyramidSimpleAffectors"};return a.apply({inputs:t,occt:r,occ:i,vectorHelper:n,Inputs:e,Advanced:G,ShapeParser:ni,method:c})}catch(e){throw new Error(e)}}(t,this.occtService,this.occ,this.vectorHelper,this.dependencies)}}class Wa{constructor(e){this.dependencies={serenitySwirl:void 0};const t=new V,r=new H;this.occtService=new Ce(e,new Se(t,r,e)),this.advanced=new Ua(this.occtService,this.dependencies,e,t),this.things=new si(this.occtService,this.advanced,this.dependencies)}}var Na=function(){return Na=Object.assign||function(e){for(var t,r=1,i=arguments.length;r0&&n[n.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!n||a[1]>n[0]&&a[1]{Re=new Oe(e);const i=new V,n=new H;De=new Ce(e,new Se(i,n,e)),t&&(De.plugins=t,Fe&&Object.keys(Fe).forEach((e=>{De.plugins.dependencies[e]=Fe[e]}))),postMessage("occ-initialised")})(e,t),postMessage("occ-initialised"),[2]}}))}))})):((e,t)=>{let r;t("busy");try{if("shapeToMesh"!==e.action.functionName&&"shapesToMeshes"!==e.action.functionName&&"deleteShape"!==e.action.functionName&&"deleteShapes"!==e.action.functionName&&"startedTheRun"!==e.action.functionName&&"cleanAllCache"!==e.action.functionName&&"addOc"!==e.action.functionName&&"saveShapeSTEP"!==e.action.functionName){Object.keys(e.action.inputs).forEach((t=>{const r=e.action.inputs[t];r&&r.type&&"occ-shape"===r.type&&r.hash&&(e.action.inputs[t]=Re.checkCache(e.action.inputs[t].hash)),r&&Array.isArray(r)&&r.length>0&&(r[0].type&&"occ-shape"===r[0].type&&r[0].hash?e.action.inputs[t]=e.action.inputs[t].map((e=>Re.checkCache(e.hash))):Array.isArray(r[0])&&r[0][0].type&&"occ-shape"===r[0][0].type&&r[0][0].hash&&(e.action.inputs[t]=e.action.inputs[t].map((e=>e.map((e=>Re.checkCache(e.hash)))))))}));const t=e.action.functionName.split(".");let i;if(i=3===t.length?Re.cacheOp(e.action,(()=>De[t[0]][t[1]][t[2]](e.action.inputs))):2===t.length?Re.cacheOp(e.action,(()=>De[t[0]][t[1]](e.action.inputs))):Re.cacheOp(e.action,(()=>De[e.action.functionName](e.action.inputs))),Re.isOCCTObject(i))r=Array.isArray(i)?i.map((e=>({hash:e.hash,type:"occ-shape"}))):{hash:i.hash,type:"occ-shape"};else if(i.compound&&i.data&&i.shapes&&i.shapes.length>0){const e=i;e.shapes=e.shapes.map((e=>({id:e.id,shape:{hash:e.shape.hash,type:"occ-shape"}}))),e.compound={hash:e.compound.hash,type:"occ-shape"},r=e}else r=i}if("saveShapeSTEP"===e.action.functionName&&(e.action.inputs.shape=Re.checkCache(e.action.inputs.shape.hash),r=De.io.saveShapeSTEP(e.action.inputs)),"addOc"===e.action.functionName&&(De&&De.plugins?Object.keys(e.action.inputs).forEach((t=>{De.plugins.dependencies[t]=e.action.inputs[t]})):Fe=e.action.inputs),"shapeToMesh"===e.action.functionName&&(e.action.inputs.shape=Re.checkCache(e.action.inputs.shape.hash),r=De.shapeToMesh(e.action.inputs)),"shapesToMeshes"===e.action.functionName){if(!(e.action.inputs.shapes&&e.action.inputs.shapes.length>0))throw new Error("No shapes detected");e.action.inputs.shapes=e.action.inputs.shapes.map((e=>Re.checkCache(e.hash))),r=De.shapesToMeshes(e.action.inputs)}"deleteShape"===e.action.functionName&&(Re.cleanCacheForHash(e.action.inputs.shape.hash),r={}),"deleteShapes"===e.action.functionName&&(e.action.inputs.shapes.forEach((e=>Re.cleanCacheForHash(e.hash))),r={}),"startedTheRun"===e.action.functionName&&(Re&&Object.keys(Re.usedHashes).length>1e4&&Re.cleanAllCache(),r={}),"cleanAllCache"===e.action.functionName&&(Re.cleanAllCache(),r={}),t({uid:e.uid,result:r})}catch(r){let i,n;e&&e.action&&e.action.inputs&&(i=`Input values were: {${Object.keys(e.action.inputs).map((t=>`${t}: ${JSON.stringify(e.action.inputs[t])}`)).join(",")}}. `),e&&e.action&&e.action.functionName&&(n=`- ${e.action.functionName}`),t({uid:e.uid,result:void 0,error:`OCCT computation failed. ${r} While executing function ${n}. ${i}`})}})(d,postMessage)}))})()})(); \ No newline at end of file